org.telegram.telegrambots.meta.ApiContext Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of telegrambots-meta Show documentation
Show all versions of telegrambots-meta Show documentation
Easy to use library to create Telegram Bots
package org.telegram.telegrambots.meta;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import org.telegram.telegrambots.meta.logging.BotLogger;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
/**
* @author Ruben Bermudez
* @version 1.0
*/
public class ApiContext {
private static final Object lock = new Object();
private static Injector INJECTOR;
private static Map bindings = 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)) {
BotLogger.debug("ApiContext", MessageFormat.format("Class {0} already registered", type.getName()));
}
bindings.put(type, implementation);
}
public static void registerSingleton(Class type, Class implementation) {
if (singletonBindings.containsKey(type)) {
BotLogger.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;
}
@SuppressWarnings("unchecked")
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);
}
}
}
}