pro.zackpollard.telegrambot.api.extensions.Extensions Maven / Gradle / Ivy
package pro.zackpollard.telegrambot.api.extensions;
import pro.zackpollard.telegrambot.api.TelegramBot;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
/**
* @author DarkSeraphim.
*/
public enum Extensions {
INSTANCE;
private final Map, Extension.Provider extends Extension>> providers = new HashMap<>();
public static void register(Class cls, Extension.Provider provider) {
provider = CachedExtensionProvider.wrap(provider);
INSTANCE.providers.put(cls, provider);
}
public static T get(TelegramBot bot, Class cls) {
Extension.Provider extends Extension> provider = INSTANCE.providers.get(cls);
if (provider == null) {
Extension.DefaultProvider def = cls.getAnnotation(Extension.DefaultProvider.class);
if (def == null) {
throw new IllegalArgumentException("No extension found for type " + cls.getName() + ", and no default implementation was provided.");
}
Extension.Provider defaultProvider;
try {
Class extends Extension.Provider> extensionFactory = def.value();
defaultProvider = extensionFactory.newInstance();
} catch (ReflectiveOperationException ex) {
throw new IllegalStateException("No provider was found for extension " + cls.getName() +
", and the default implementation did not have a constructor which accepts a TelegramBot instance", ex);
}
provider = INSTANCE.providers.computeIfAbsent(cls, $ -> CachedExtensionProvider.wrap(defaultProvider));
}
return cls.cast(provider.create(bot));
}
private static class CachedExtensionProvider implements Extension.Provider {
private final Extension.Provider original;
private Map extension;
private CachedExtensionProvider(Extension.Provider original) {
this.original = original;
this.extension = new WeakHashMap<>();
}
@Override
public T create(TelegramBot bot) {
return this.extension.computeIfAbsent(bot, this.original::create);
}
private static CachedExtensionProvider wrap(Extension.Provider original) {
return original instanceof CachedExtensionProvider ? (CachedExtensionProvider) original : new CachedExtensionProvider<>(original);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy