All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.binance.api.client.impl.BinanceApiWebSocketListener Maven / Gradle / Ivy

The newest version!
package com.binance.api.client.impl;

import java.io.IOException;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import com.binance.api.client.BinanceApiCallback;
import com.binance.api.client.exception.BinanceApiException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Binance API WebSocket listener.
 */
public class BinanceApiWebSocketListener extends WebSocketListener {

  private BinanceApiCallback callback;

  private Class eventClass;

  private TypeReference eventTypeReference;

  private boolean closing = false;

  public BinanceApiWebSocketListener(BinanceApiCallback callback, Class eventClass) {
    this.callback = callback;
    this.eventClass = eventClass;
  }

  public BinanceApiWebSocketListener(BinanceApiCallback callback, TypeReference eventTypeReference) {
    this.callback = callback;
    this.eventTypeReference = eventTypeReference;
  }

  @Override
  public void onMessage(WebSocket webSocket, String text) {
    ObjectMapper mapper = new ObjectMapper();
    try {
      T event = null;
      if (eventClass == null) {
        event = mapper.readValue(text, eventTypeReference);
      } else {
        event = mapper.readValue(text, eventClass);
      }
      callback.onResponse(event);
    } catch (IOException e) {
      throw new BinanceApiException(e);
    }
  }

  @Override
  public void onClosing(final WebSocket webSocket, final int code, final String reason) {
    closing = true;
  }

  @Override
  public void onFailure(WebSocket webSocket, Throwable t, Response response) {
    if (!closing) {
      callback.onFailure(t);
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy