Merge branch 'feat_callback_support' into develop

This commit is contained in:
Nelson R. Pérez 2020-03-12 18:00:07 -05:00
commit 587250fccb
4 changed files with 86 additions and 2 deletions

View file

@ -23,7 +23,7 @@ buildscript {
jcenter() jcenter()
} }
dependencies { dependencies {
classpath 'com.android.tools.build:gradle:3.4.2' classpath 'com.android.tools.build:gradle:3.5.2'
classpath 'com.novoda:bintray-release:0.9.1' classpath 'com.novoda:bintray-release:0.9.1'
} }
} }

View file

@ -27,7 +27,7 @@ import cy.agorise.graphenej.interfaces.JsonSerializable;
/** /**
* Class used to represent a specific amount of a certain asset * Class used to represent a specific amount of a certain asset
*/ */
public class AssetAmount implements ByteSerializable, JsonSerializable { public class AssetAmount implements ByteSerializable, JsonSerializable, Comparable<AssetAmount> {
/** /**
* Constants used in the JSON serialization procedure. * Constants used in the JSON serialization procedure.
*/ */
@ -196,6 +196,14 @@ public class AssetAmount implements ByteSerializable, JsonSerializable {
return String.format("(asset=%s, amount=%s)", asset.getObjectId(), amount.toString(10)); return String.format("(asset=%s, amount=%s)", asset.getObjectId(), amount.toString(10));
} }
@Override
public int compareTo(AssetAmount other) {
if(!other.asset.equals(this.asset)) throw new AssertionError("Cannot compare amounts of different assets");
if(this.amount == null) throw new NullPointerException("Asset amount field is null");
if(other.amount == null) throw new NullPointerException("Asser amount field is null");
return amount.compareTo(other.amount);
}
/** /**
* Custom serializer used to translate this object into the JSON-formatted entry we need for a transaction. * Custom serializer used to translate this object into the JSON-formatted entry we need for a transaction.
*/ */

View file

@ -0,0 +1,28 @@
package cy.agorise.graphenej.api;
import javax.annotation.Nullable;
import cy.agorise.graphenej.models.JsonRpcResponse;
import okhttp3.Response;
/**
* Interface defining the basic contract an API request can expect.
*/
public interface ApiCallback {
/**
* Method called whenever we have a successful response from the node.
*
* @param response Parsed response
* @param text Raw text response
*/
<T> void onResponse(JsonRpcResponse<T> response, String text);
/**
* Method called whenever there was an error and the response could not be delivered.
*
* @param t Error Throwable, potentially with some details about the problem.
* @param response Node response, if any
*/
void onFailure(Throwable t, @Nullable Response response);
}

View file

@ -1,5 +1,7 @@
package cy.agorise.graphenej.api.android; package cy.agorise.graphenej.api.android;
import android.util.SparseArray;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken; import com.google.gson.reflect.TypeToken;
@ -22,6 +24,7 @@ import cy.agorise.graphenej.RPC;
import cy.agorise.graphenej.Transaction; import cy.agorise.graphenej.Transaction;
import cy.agorise.graphenej.UserAccount; import cy.agorise.graphenej.UserAccount;
import cy.agorise.graphenej.api.ApiAccess; import cy.agorise.graphenej.api.ApiAccess;
import cy.agorise.graphenej.api.ApiCallback;
import cy.agorise.graphenej.api.ConnectionStatusUpdate; import cy.agorise.graphenej.api.ConnectionStatusUpdate;
import cy.agorise.graphenej.api.calls.ApiCallable; import cy.agorise.graphenej.api.calls.ApiCallable;
import cy.agorise.graphenej.api.calls.GetAccountBalances; import cy.agorise.graphenej.api.calls.GetAccountBalances;
@ -117,6 +120,8 @@ public class NetworkService {
private CompositeDisposable mCompositeDisposable; private CompositeDisposable mCompositeDisposable;
private HashMap<Long, ApiCallback> mCallbackMap = new HashMap<Long, ApiCallback>();
private Gson gson = new GsonBuilder() private Gson gson = new GsonBuilder()
.registerTypeAdapter(Transaction.class, new Transaction.TransactionDeserializer()) .registerTypeAdapter(Transaction.class, new Transaction.TransactionDeserializer())
.registerTypeAdapter(TransferOperation.class, new TransferOperation.TransferDeserializer()) .registerTypeAdapter(TransferOperation.class, new TransferOperation.TransferDeserializer())
@ -228,6 +233,18 @@ public class NetworkService {
return -1; return -1;
} }
public synchronized long sendMessage(ApiCallable apiCallable, int requiredApi, ApiCallback callback){
long id = this.sendMessage(apiCallable, requiredApi);
if(callback != null){
if(id != -1){
mCallbackMap.put(id, callback);
}else{
callback.onFailure(new Exception("Message could not be sent"), null);
}
}
return id;
}
/** /**
* Method used to inform any external party a clue about the current connectivity status * Method used to inform any external party a clue about the current connectivity status
* @return True if the service is currently connected and logged in, false otherwise. * @return True if the service is currently connected and logged in, false otherwise.
@ -247,6 +264,7 @@ public class NetworkService {
nodeLatencyVerifier.stop(); nodeLatencyVerifier.stop();
mCompositeDisposable.dispose(); mCompositeDisposable.dispose();
mCallbackMap.clear();
} }
/** /**
@ -303,6 +321,7 @@ public class NetworkService {
FullNode fullNode = nodeProvider.getBestNode(); FullNode fullNode = nodeProvider.getBestNode();
if(fullNode != null){ if(fullNode != null){
System.out.println(String.format(Locale.ROOT, "Connected with %d latency results", latencyUpdateCounter)); System.out.println(String.format(Locale.ROOT, "Connected with %d latency results", latencyUpdateCounter));
mApiIds.clear();
connect(); connect();
}else{ }else{
Disposable d = Observable.timer(DEFAULT_INITIAL_DELAY, TimeUnit.MILLISECONDS).subscribe(this); Disposable d = Observable.timer(DEFAULT_INITIAL_DELAY, TimeUnit.MILLISECONDS).subscribe(this);
@ -334,6 +353,21 @@ public class NetworkService {
public void onComplete() { } public void onComplete() { }
}; };
/**
* Method used to execute every callback failure method and remove them from the SparseArray.
*
* @param throwable
* @param response
*/
private void resetCallbacks(Throwable throwable, Response response){
for(ApiCallback callback : mCallbackMap.values()) {
if(callback != null) {
callback.onFailure(throwable, response);
mCallbackMap.remove(callback);
}
}
}
private WebSocketListener mWebSocketListener = new WebSocketListener() { private WebSocketListener mWebSocketListener = new WebSocketListener() {
@Override @Override
@ -448,6 +482,7 @@ public class NetworkService {
*/ */
private void handleJsonRpcResponse(JsonRpcResponse response, String text){ private void handleJsonRpcResponse(JsonRpcResponse response, String text){
JsonRpcResponse parsedResponse = null; JsonRpcResponse parsedResponse = null;
Class requestClass = mRequestClassMap.get(response.id); Class requestClass = mRequestClassMap.get(response.id);
if(requestClass != null){ if(requestClass != null){
// Removing the class entry in the map // Removing the class entry in the map
@ -526,6 +561,17 @@ public class NetworkService {
if(parsedResponse == null){ if(parsedResponse == null){
parsedResponse = response; parsedResponse = response;
} }
// Executing callback, if present with the parsed response
if(mCallbackMap.containsKey(response.id)){
ApiCallback callback = mCallbackMap.get(response.id);
if(response.error == null)
callback.onResponse(parsedResponse, text);
else
callback.onFailure(new Exception("Exception while trying to parse node response. Message: " + response.error.message), null);
mCallbackMap.remove(response.id);
}
// Broadcasting the parsed response to all interested listeners // Broadcasting the parsed response to all interested listeners
RxBus.getBusInstance().send(parsedResponse); RxBus.getBusInstance().send(parsedResponse);
} }
@ -589,6 +635,7 @@ public class NetworkService {
@Override @Override
public void onClosed(WebSocket webSocket, int code, String reason) { public void onClosed(WebSocket webSocket, int code, String reason) {
super.onClosed(webSocket, code, reason); super.onClosed(webSocket, code, reason);
resetCallbacks(new Exception("Websocket closed. Reason: " + reason), null);
if(code == GOING_AWAY_STATUS) if(code == GOING_AWAY_STATUS)
handleWebSocketDisconnection(true, false); handleWebSocketDisconnection(true, false);
else else
@ -598,6 +645,7 @@ public class NetworkService {
@Override @Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) { public void onFailure(WebSocket webSocket, Throwable t, Response response) {
super.onFailure(webSocket, t, response); super.onFailure(webSocket, t, response);
resetCallbacks(t, response);
System.out.println("onFailure. Exception: "+t.getClass().getName()+", Msg: "+t.getMessage()); System.out.println("onFailure. Exception: "+t.getClass().getName()+", Msg: "+t.getMessage());
// Logging error stack trace // Logging error stack trace
for(StackTraceElement element : t.getStackTrace()){ for(StackTraceElement element : t.getStackTrace()){