about summary refs log tree commit diff stats
path: root/org.fox.ttrss/src/main/java/org/fox/ttrss/ApiRequest.java
blob: 1851f6b3c05c42a5780479b4838f4f286bd035e2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package org.fox.ttrss;

import static org.fox.ttrss.ApiCommon.ApiError;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;

import com.google.gson.JsonElement;

import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class ApiRequest implements ApiCommon.ApiCaller {

    private static final ExecutorService EXECUTOR = Executors.newSingleThreadExecutor(new ThreadFactory() {
        private final AtomicInteger m_count = new AtomicInteger(1);
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "ApiRequest-" + m_count.getAndIncrement());
            t.setDaemon(true);
            return t;
        }
    });
    private final Handler m_mainHandler = new Handler(Looper.getMainLooper());

    protected final Context m_context;
    protected int m_apiStatusCode = 0;
    protected String m_lastErrorMessage;
    protected ApiError m_lastError;
    protected Throwable m_lastException;

    public ApiRequest(Context context) {
        m_context = context;
        m_lastError = ApiError.UNKNOWN_ERROR;
    }

    /**
     * Callback interface for API request completion.
     * Both onSuccess and onError are invoked on the main thread before onApiFinished().
     */
    public interface ApiCallback {
        void onSuccess(JsonElement result);
        void onError(ApiError error, String message, int statusCode);
    }

    /**
     * Execute the API request with a callback for the result.
     * Called on the main thread; work is dispatched to a background executor.
     * Callback is invoked on the main thread upon completion.
     */
    public void execute(HashMap<String, Object> map, ApiCallback callback) {
        EXECUTOR.execute(() -> {
            JsonElement result = ApiCommon.performRequest(m_context, map, this);
            m_mainHandler.post(() -> {
                if (result != null && m_lastError == ApiError.SUCCESS) {
                    callback.onSuccess(result);

                    onApiFinished(result);
                } else {
                    callback.onError(m_lastError, m_lastErrorMessage, m_apiStatusCode);
                }
            });
        });
    }

    /**
     * Hook for subclasses to handle the result on the main thread.
     * Override this instead of onPostExecute. Called only on success.
     * For error handling, use the ApiCallback.onError() method.
     *
     * This is invoked after ApiCallback onSuccess().
     */
    protected void onApiFinished(JsonElement result) {
        // no-op by default
    }

    @Override
    public void setStatusCode(int statusCode) {
        m_apiStatusCode = statusCode;
    }

    @Override
    public void setLastError(ApiError lastError) {
        m_lastError = lastError;
    }

    @Override
    public void setLastErrorMessage(String message) {
        m_lastErrorMessage = message;
    }

    @Override
    public void setLastException(Throwable e) {
        m_lastException = e;
    }

    @Override
    public void notifyProgress(int progress) {
        // Progress is no longer tracked via AsyncTask's publishProgress.
        // Subclasses can override if they need progress notifications.
    }

    @Override
    public ApiError getLastError() {
        return m_lastError;
    }

    @Override
    public Throwable getLastException() {
        return m_lastException;
    }

    /**
     * Shut down the shared executor. Call once when the application is terminating.
     */
    public static void shutdownExecutor() {
        EXECUTOR.shutdownNow();
    }
}