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

org.telegram.telegraph.TelegraphContext Maven / Gradle / Ivy

The newest version!
package org.telegram.telegraph;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Singleton;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by rubenlagus on 15/12/2016.
 */
public class TelegraphContext {
    private static final Object lock = new Object();
    private static Injector INJECTOR;
    private static Map bindings = new HashMap<>();
    private static Map instanceBindings = new HashMap<>();
    private static Map singletonBindings = new HashMap<>();

    public static  T getInstance(Class type) {
        return getInjector().getInstance(type);
    }

    public static  void register(Class type, Class implementation) {
        if (bindings.containsKey(type)) {
            TelegraphLogger.debug("ApiContext", MessageFormat.format("Class {0} already registered", type.getName()));
        }
        bindings.put(type, implementation);
    }

    public static  void registerInstance(Class type, S instance) {
        if (instanceBindings.containsKey(type)) {
            TelegraphLogger.debug("ApiContext", MessageFormat.format("Class {0} already registered", type.getName()));
        }
        instanceBindings.put(type, instance);
    }

    public static  void registerSingleton(Class type, Class implementation) {
        if (singletonBindings.containsKey(type)) {
            TelegraphLogger.debug("ApiContext", MessageFormat.format("Class {0} already registered", type.getName()));
        }
        singletonBindings.put(type, implementation);
    }

    private static Injector getInjector() {
        if (INJECTOR == null) {
            synchronized (lock) {
                if (INJECTOR == null) {
                    INJECTOR = Guice.createInjector(new ApiModule());
                }
            }
        }
        return INJECTOR;
    }

    private static class ApiModule extends AbstractModule {
        @Override
        protected void configure() {
            for (Map.Entry binding : bindings.entrySet()) {
                bind(binding.getKey()).to(binding.getValue());
            }
            for (Map.Entry binding : singletonBindings.entrySet()) {
                bind(binding.getKey()).to(binding.getValue()).in(Singleton.class);
            }
            for (Map.Entry binding : instanceBindings.entrySet()) {
                bind(binding.getKey()).toInstance(binding.getValue());
            }
        }
    }
}