package de.mrbesen.telegram; import java.net.UnknownHostException; 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) { enque(t, false); } public void enque(Task t, boolean priority) { if(priority) { synchronized (tasks) { tasks.add(0, t); } } else { 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() { int failed = 0; 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() ); } failed = 0; } catch(UnknownHostException ex) {//host(api.telegram.org) is good -> bad inet failed ++; if(failed > 10) try { Thread.yield(); Thread.sleep(1000);//wait 1 second } catch(InterruptedException ignored) {} //reenque enque(current); } 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); } } }