All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.contextfw.web.application.internal.scope.WebApplicationScope Maven / Gradle / Ivy

package net.contextfw.web.application.internal.scope;

import java.util.Map;

import com.google.inject.Key;
import com.google.inject.OutOfScopeException;
import com.google.inject.Provider;
import com.google.inject.Scope;

public class WebApplicationScope implements Scope {

    private static final Provider SEEDED_KEY_PROVIDER = new Provider() {
        public Object get() {
            throw new IllegalStateException("If you got here then it means that"
                    + " your code asked for scoped object which should have been"
                    + " explicitly seeded in this scope by calling" + " SimpleScope.seed(), but was not.");
        }
    };

    public void enter() {
    }

    public void exit() {
        getScopedBeans().clear();
    }

    public  void seed(Key key, T value) {
        getScopedBeans().put(key, value);
    }

    public  void seed(Class clazz, T value) {
        seed(Key.get(clazz), value);
    }

    public  Provider scope(final Key key, final Provider unscoped) {
        return new Provider() {
            public T get() {
                Map, Object> scopedBeans = getScopedBeans();

                @SuppressWarnings("unchecked")
                T current = (T) scopedBeans.get(key);
                if (current == null && !scopedBeans.containsKey(key)) {
                    current = unscoped.get();
                    scopedBeans.put(key, current);
                }
                return current;
            }
        };
    }

    private  Map, Object> getScopedBeans() {
        try {
            Map, Object> scopedObjects = WebApplicationScopedBeans.getCurrentInstance().getBeans();
            if (scopedObjects == null) {
                throw new OutOfScopeException("WebApplicationScope does not exist");
            }
            return scopedObjects;
        }
        catch (Exception e) {
            throw new OutOfScopeException("WebApplicationScope does not exist", e);
        }
    }

    /**
     * Returns a provider that always throws exception complaining that the
     * object in question must be seeded before it can be injected.
     * 
     * @return typed provider
     */
    @SuppressWarnings( { "unchecked" })
    public static  Provider seededKeyProvider() {
        return (Provider) SEEDED_KEY_PROVIDER;
    }
}