103 lines
2.4 KiB
Java
103 lines
2.4 KiB
Java
package de.mrbesen.telegram;
|
|
|
|
import java.util.LinkedList;
|
|
import java.util.List;
|
|
|
|
import org.json.JSONObject;
|
|
|
|
public class AsyncHandler implements Runnable {
|
|
|
|
private List<Task> tasks = new LinkedList<>();
|
|
private Thread asynchandlerthread = null;
|
|
private TelegramAPI api;
|
|
|
|
public AsyncHandler(TelegramAPI api) {
|
|
this.api = api;
|
|
}
|
|
|
|
public void enque(Task t) {
|
|
synchronized (tasks) {
|
|
tasks.add(t);
|
|
}
|
|
|
|
//make sure its running
|
|
if(asynchandlerthread == null) {
|
|
asynchandlerthread = new Thread(this, "AsyncHandler");
|
|
asynchandlerthread.start();
|
|
} else if(!asynchandlerthread.isAlive()) {
|
|
asynchandlerthread = null;
|
|
}
|
|
}
|
|
|
|
public void enque(String request, String parameters) {
|
|
enque(new Task(request, parameters));
|
|
}
|
|
|
|
@Override
|
|
public void run() {
|
|
while(!tasks.isEmpty()) {
|
|
Task current;
|
|
|
|
synchronized (tasks) {
|
|
current = tasks.remove(0);
|
|
}
|
|
|
|
if(current == null)
|
|
continue;
|
|
|
|
//run task
|
|
try {
|
|
try {
|
|
Object obj = api.request(current.apimethod, current.parameters);
|
|
Callback<?, ?> callb = current.callback;
|
|
while(callb != null) {
|
|
obj = (Object) callb.callObj(obj);
|
|
callb = callb.next;
|
|
// throw new Exception("Callbacktype missmatch! Got " + obj.getClass().getSimpleName() + " Wanted: " + wanted.getSimpleName() );
|
|
}
|
|
} catch(Throwable t) {
|
|
if(current.exceptionhandl == null)
|
|
throw t;
|
|
current.exceptionhandl.call(t);
|
|
}
|
|
} catch(Throwable t) {
|
|
System.out.println("Error executing Task: ");
|
|
t.printStackTrace();
|
|
}
|
|
}
|
|
asynchandlerthread = null;
|
|
}
|
|
|
|
public static class Task {
|
|
String apimethod;
|
|
String parameters;
|
|
Callback<JSONObject, ?> callback = null;
|
|
Callback<Throwable, ?> exceptionhandl = null;
|
|
|
|
public Task(String apimethod, String parameters) {
|
|
this.apimethod = apimethod;
|
|
this.parameters = parameters;
|
|
}
|
|
|
|
public Task(String apimethod, String parameters, Callback<JSONObject, ?> callback) {
|
|
this.apimethod = apimethod;
|
|
this.parameters = parameters;
|
|
this.callback = callback;
|
|
}
|
|
|
|
public Task setExceptionhandl(Callback<Throwable, ?> exceptionhandl) {
|
|
this.exceptionhandl = exceptionhandl;
|
|
return this;
|
|
}
|
|
}
|
|
|
|
public static abstract class Callback<T extends Object, K extends Object> {
|
|
public Callback<K, ?> next = null;
|
|
public abstract K call(T j) throws Throwable;
|
|
@SuppressWarnings("unchecked")
|
|
public K callObj(Object j) throws Throwable {
|
|
return call((T) j);
|
|
}
|
|
}
|
|
}
|