// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
package test;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.enterprise.inject.spi.Bean;
import javax.enterprise.context.spi.Context;
import javax.enterprise.context.spi.Contextual;
import javax.enterprise.context.spi.CreationalContext;

public class MyContext implements Context {
    private Map<String,Object> objcache = new HashMap<String,Object>();
    private List<CreationalContext> ctxcache = new ArrayList<CreationalContext>();
    public <T> T get(Contextual<T> ctx) {
        return null;
    }
    public <T> T get(Contextual<T> ctx, CreationalContext<T> crectx) {
        String clz = ((Bean<T>)ctx).getBeanClass().getName();
        @SuppressWarnings("unchecked")
        T o;
        synchronized(objcache) {
            o = (T)objcache.get(clz);
            if(o == null) {
                o = ctx.create(crectx);
                objcache.put(clz, o);
            }
            ctxcache.add(crectx);
        }
        return o;
    }
    public Class<? extends Annotation> getScope() {
        return MyScoped.class;
    }
    public boolean isActive() {
        return true;
    }
    public void reset() {
        synchronized(objcache) {
            objcache.clear();
            for(CreationalContext crectx : ctxcache) {
                crectx.release();
            }
        }
    }
}
