Added Android code
[wl-app.git] / Android / app / src / main / java / com / moiseum / wolnelektury / connection / RestClientCallback.java
1 package com.moiseum.wolnelektury.connection;
2
3 import android.util.Log;
4
5 import retrofit2.Call;
6 import retrofit2.Response;
7
8 public abstract class RestClientCallback<T, S> implements retrofit2.Callback<T> {
9
10         private static final String TAG = RestClientCallback.class.getSimpleName();
11
12         @Override
13         public void onResponse(Call<T> call, Response<T> response) {
14                 if (response.isSuccessful()) {
15                         onSuccess(response.body());
16                 } else {
17                         try {
18                                 ErrorHandler<T> errorHandler = new ErrorHandler<>(response);
19                                 errorHandler.handle();
20                         } catch (Exception e) {
21                                 onFailure(e);
22                         }
23                 }
24         }
25
26         @Override
27         public void onFailure(Call<T> call, Throwable t) {
28                 Log.e(TAG, t.getMessage(), t);
29                 if (!call.isCanceled()) {
30                         onFailure(new Exception(t));
31                 } else {
32                         onCancel();
33                 }
34         }
35
36
37         public abstract void onSuccess(T data);
38
39         public abstract void onFailure(Exception e);
40
41         public abstract void onCancel();
42
43         public abstract Call<T> execute(S service);
44 }