// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package jcademo.domain;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.AsyncContext;

// singleton to handle the id to async servlet response mapping
public class AsyncHelper {
	private static AsyncHelper instance = new AsyncHelper();
	public static AsyncHelper getInstance() {
		return instance;
	}
	private Map<String,AsyncContext> ctxstore = new HashMap<String,AsyncContext>();
	// save mapping
    public void save(String id, AsyncContext ac) {
    	synchronized(ctxstore) {
            ctxstore.put(id, ac);
    	}
    }
    // use mapping to send response and remove mapping
    public void complete(String id, ABC o) {
		try {
			AsyncContext ctx = ctxstore.get(id);
			ctx.getResponse().setContentType("text/plain");
			ctx.getResponse().getWriter().println(o.getC());
			ctx.complete();
	    	synchronized(ctxstore) {
	    		ctxstore.remove(id);
	    	}
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
}
