package de.mrbesen.telegram; import java.util.LinkedList; import java.util.List; import org.json.JSONObject; public class AsyncHandler implements Runnable { private List tasks = new LinkedList<>(); private Thread asynchandlerthread = null; private TelegramAPI api; public AsyncHandler(TelegramAPI api) { this.api = api; } public void enque(Task t) { tasks.add(t); //make sure its running if(asynchandlerthread == null) { asynchandlerthread = new Thread(this, "AsyncHandler"); asynchandlerthread.start(); } } public void enque(String request, String parameters) { enque(new Task(request, parameters)); } @Override public void run() { while(!tasks.isEmpty()) { Task current = tasks.remove(0); //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 callback = null; Callback exceptionhandl = null; public Task(String apimethod, String parameters) { this.apimethod = apimethod; this.parameters = parameters; } public Task(String apimethod, String parameters, Callback callback) { this.apimethod = apimethod; this.parameters = parameters; this.callback = callback; } public Task setExceptionhandl(Callback exceptionhandl) { this.exceptionhandl = exceptionhandl; return this; } } public static abstract class Callback { public Callback next = null; public abstract K call(T j) throws Throwable; @SuppressWarnings("unchecked") public K callObj(Object j) throws Throwable { return call((T) j); } } }