Stop using methods for configs

This commit is contained in:
Norbi Peti 2020-10-26 17:44:11 +01:00
parent 267a350473
commit 51e0ca4f4c
No known key found for this signature in database
GPG key ID: DBA4C4549A927E56
17 changed files with 213 additions and 233 deletions

View file

@ -80,7 +80,7 @@ public class ComponentCommand extends ICommand2MC {
return true;
Component.setComponentEnabled(oc.get(), enable);
if (permanent)
oc.get().shouldBeEnabled().set(enable);
oc.get().shouldBeEnabled.set(enable);
sender.sendMessage(oc.get().getClass().getSimpleName() + " " + (enable ? "en" : "dis") + "abled " + (permanent ? "permanently" : "temporarily") + ".");
} catch (Exception e) {
TBMCCoreAPI.SendException("Couldn't " + (enable ? "en" : "dis") + "able component " + component + "!", e, (JavaPlugin) plugin);

View file

@ -21,7 +21,7 @@ public final class ComponentManager {
*/
public static void enableComponents() {
//Component.getComponents().values().stream().filter(c->cs.getConfigurationSection(c.getClass().getSimpleName()).getBoolean("enabled")).forEach(c-> {
Component.getComponents().values().stream().filter(c -> c.shouldBeEnabled().get()).forEach(c -> {
Component.getComponents().values().stream().filter(c -> c.shouldBeEnabled.get()).forEach(c -> {
try {
Component.setComponentEnabled(c, true);
} catch (Exception | NoClassDefFoundError e) {

View file

@ -65,31 +65,23 @@ public class MainPlugin extends ButtonPlugin {
* Sets whether the plugin should write a list of installed plugins in a txt file.
* It can be useful if some other software needs to know the plugins.
*/
private ConfigData<Boolean> writePluginList() {
return getIConfig().getData("writePluginList", false);
}
private final ConfigData<Boolean> writePluginList = getIConfig().getData("writePluginList", false);
/**
* The chat format to use for messages from other platforms if Chroma-Chat is not installed.
*/
ConfigData<String> chatFormat() {
return getIConfig().getData("chatFormat", "[{origin}|" +
ConfigData<String> chatFormat = getIConfig().getData("chatFormat", "[{origin}|" +
"{channel}] <{name}> {message}");
}
/**
* Print some debug information.
*/
public ConfigData<Boolean> test() {
return getIConfig().getData("test", false);
}
public final ConfigData<Boolean> test = getIConfig().getData("test", false);
/**
* If a Chroma command clashes with another plugin's command, this setting determines whether the Chroma command should be executed or the other plugin's.
*/
public ConfigData<Boolean> prioritizeCustomCommands() {
return getIConfig().getData("prioritizeCustomCommands", false);
}
public final ConfigData<Boolean> prioritizeCustomCommands = getIConfig().getData("prioritizeCustomCommands", false);
@Override
public void pluginEnable() {
@ -103,7 +95,6 @@ public class MainPlugin extends ButtonPlugin {
getLogger().warning("No economy plugin found! Components using economy will not be registered.");
saveConfig();
Component.registerComponent(this, new RestartComponent());
//noinspection unchecked - needed for testing
Component.registerComponent(this, new ChannelComponent());
Component.registerComponent(this, new RandomTPComponent());
Component.registerComponent(this, new MemberComponent());
@ -138,7 +129,7 @@ public class MainPlugin extends ButtonPlugin {
Supplier<Iterable<String>> playerSupplier = () -> Bukkit.getOnlinePlayers().stream().map(HumanEntity::getName)::iterator;
getCommand2MC().addParamConverter(OfflinePlayer.class, Bukkit::getOfflinePlayer, "Player not found!", playerSupplier);
getCommand2MC().addParamConverter(Player.class, Bukkit::getPlayer, "Online player not found!", playerSupplier);
if (writePluginList().get()) {
if (writePluginList.get()) {
try {
Files.write(new File("plugins", "plugins.txt").toPath(), Arrays.stream(Bukkit.getPluginManager().getPlugins()).map(p -> (CharSequence) p.getDataFolder().getName())::iterator);
} catch (IOException e) {
@ -147,7 +138,7 @@ public class MainPlugin extends ButtonPlugin {
}
if (getServer().getPluginManager().isPluginEnabled("Essentials"))
ess = Essentials.getPlugin(Essentials.class);
logger.info(pdf.getName() + " has been Enabled (V." + pdf.getVersion() + ") Test: " + test().get() + ".");
logger.info(pdf.getName() + " has been Enabled (V." + pdf.getVersion() + ") Test: " + test.get() + ".");
}
@Override

View file

@ -31,13 +31,13 @@ public class PlayerListener implements Listener {
public void OnPlayerJoin(PlayerJoinEvent event) {
var p = event.getPlayer();
TBMCPlayer player = TBMCPlayerBase.getPlayer(p.getUniqueId(), TBMCPlayer.class);
if (player.PlayerName().get() == null) {
player.PlayerName().set(p.getName());
MainPlugin.Instance.getLogger().info("Player name saved: " + player.PlayerName().get());
} else if (!p.getName().equals(player.PlayerName().get())) {
TownyComponent.renameInTowny(player.PlayerName().get(), p.getName());
MainPlugin.Instance.getLogger().info(player.PlayerName().get() + " renamed to " + p.getName());
player.PlayerName().set(p.getName());
if (player.PlayerName.get() == null) {
player.PlayerName.set(p.getName());
MainPlugin.Instance.getLogger().info("Player name saved: " + player.PlayerName.get());
} else if (!p.getName().equals(player.PlayerName.get())) {
TownyComponent.renameInTowny(player.PlayerName.get(), p.getName());
MainPlugin.Instance.getLogger().info(player.PlayerName.get() + " renamed to " + p.getName());
player.PlayerName.set(p.getName());
}
}
@ -53,7 +53,7 @@ public class PlayerListener implements Listener {
if (Arrays.stream(event.getExceptions()).anyMatch("Minecraft"::equalsIgnoreCase))
return;
Bukkit.getOnlinePlayers().stream().filter(event::shouldSendTo)
.forEach(p -> p.sendMessage(event.getChannel().DisplayName().get().substring(0, 2) + event.getMessage()));
.forEach(p -> p.sendMessage(event.getChannel().DisplayName.get().substring(0, 2) + event.getMessage()));
}
@EventHandler
@ -108,11 +108,11 @@ public class PlayerListener implements Listener {
if (!MainPlugin.Instance.isChatHandlerEnabled()) return;
if (event.getOrigin().equals("Minecraft")) return; //Let other plugins handle MC messages
var channel = event.getChannel();
String msg = MainPlugin.Instance.chatFormat().get()
.replace("{channel}", channel.DisplayName().get())
String msg = MainPlugin.Instance.chatFormat.get()
.replace("{channel}", channel.DisplayName.get())
.replace("{origin}", event.getOrigin().substring(0, 1))
.replace("{name}", ChromaUtils.getDisplayName(event.getSender()))
.replace("{message}", String.format("§%x%s", channel.Color().get().ordinal(), event.getMessage()));
.replace("{message}", String.format("§%x%s", channel.Color.get().ordinal(), event.getMessage()));
for (Player player : Bukkit.getOnlinePlayers())
if (event.shouldSendTo(player))
player.sendMessage(msg);

View file

@ -44,7 +44,6 @@ public class TestPrepare {
return cl.isAssignableFrom(invocation.getMethod().getReturnType());
}
}));
//noinspection unchecked
Component.registerComponent(Mockito.mock(JavaPlugin.class), new ChannelComponent());
TBMCChatAPI.RegisterChatChannel(Channel.GlobalChat = new Channel("§fg§f", Color.White, "g", null));
}

View file

@ -4,6 +4,7 @@ import buttondevteam.core.ComponentManager;
import buttondevteam.core.MainPlugin;
import buttondevteam.lib.architecture.Component;
import buttondevteam.lib.architecture.ConfigData;
import buttondevteam.lib.architecture.IHaveConfig;
import buttondevteam.lib.chat.Color;
import com.google.common.collect.Lists;
import org.bukkit.Bukkit;
@ -20,6 +21,9 @@ import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
/**
* Represents a chat channel. May only be instantiated after the channel component is registered.
*/
public class Channel {
/**
* Specifies a score that means it's OK to send - but it does not define any groups, only send or not send. See {@link #GROUP_EVERYONE}
@ -39,34 +43,20 @@ public class Channel {
private String defDisplayName;
private Color defColor;
private void throwGame() {
if (component == null) throw new RuntimeException("Cannot access channel properties until registered!");
}
private IHaveConfig config;
public final ConfigData<Boolean> Enabled() {
throwGame();
return component.getConfig().getData(ID + ".enabled", true);
}
public final ConfigData<Boolean> Enabled;
/**
* Must start with a color code
*/
public final ConfigData<String> DisplayName() {
throwGame();
return component.getConfig().getData(ID + ".displayName", defDisplayName); //TODO: Use config map
}
public final ConfigData<String> DisplayName;
public final ConfigData<Color> Color() {
throwGame();
return component.getConfig().getData(ID + ".color", defColor, c -> Color.valueOf((String) c), Enum::toString);
}
public final ConfigData<Color> Color;
public final String ID;
@SuppressWarnings("unchecked")
public ConfigData<String[]> IDs() {
throwGame();
return component.getConfig().getData(ID + ".IDs", new String[0], l -> ((List<String>) l).toArray(new String[0]), Lists::newArrayList);
}
public ConfigData<String[]> IDs;
/**
* Filters both the sender and the targets
*/
@ -89,6 +79,12 @@ public class Channel {
defColor = color;
ID = command;
this.filteranderrormsg = filteranderrormsg;
init();
Enabled = component.getConfig().getData(ID + ".enabled", true);
DisplayName = component.getConfig().getData(ID + ".displayName", defDisplayName);
Color = component.getConfig().getData(ID + ".color", defColor, c -> buttondevteam.lib.chat.Color.valueOf((String) c), Enum::toString);
//noinspection unchecked
IDs = component.getConfig().getData(ID + ".IDs", new String[0], l -> ((List<String>) l).toArray(new String[0]), Lists::newArrayList);
}
/**
@ -103,6 +99,19 @@ public class Channel {
defColor = color;
ID = command;
this.filteranderrormsg = s -> filteranderrormsg.apply((T) this, s);
init();
Enabled = component.getConfig().getData(ID + ".enabled", true);
DisplayName = component.getConfig().getData(ID + ".displayName", defDisplayName);
Color = component.getConfig().getData(ID + ".color", defColor, c -> buttondevteam.lib.chat.Color.valueOf((String) c), Enum::toString);
//noinspection unchecked
IDs = component.getConfig().getData(ID + ".IDs", new String[0], l -> ((List<String>) l).toArray(new String[0]), Lists::newArrayList);
}
private static void init() {
if (component == null)
component = (ChannelComponent) Component.getComponents().get(ChannelComponent.class);
if (component == null)
throw new RuntimeException("Attempting to create a channel before the component is registered!");
}
public boolean isGlobal() {
@ -148,7 +157,7 @@ public class Channel {
* @return Only the enabled channels
*/
public static Stream<Channel> getChannels() {
return channels.stream().filter(ch -> ch.Enabled().get());
return channels.stream().filter(ch -> ch.Enabled.get());
}
/**
@ -190,10 +199,6 @@ public class Channel {
public static void RegisterChannel(Channel channel) {
if (!channel.isGlobal() && !ComponentManager.isEnabled(ChannelComponent.class))
return; //Allow registering the global chat (and I guess other chats like the RP chat)
if (component == null)
component = (ChannelComponent) Component.getComponents().get(ChannelComponent.class);
if (component == null)
throw new RuntimeException("Attempting to register a channel before the component is registered!");
channels.add(channel);
component.registerChannelCommand(channel);
Bukkit.getScheduler().runTask(MainPlugin.Instance, () -> Bukkit.getPluginManager().callEvent(new ChatChannelRegisterEvent(channel))); // Wait for server start

View file

@ -11,7 +11,7 @@ import org.bukkit.plugin.java.JavaPlugin;
/**
* Manages chat channels. If disabled, only global channels will be registered.
*/
public class ChannelComponent extends Component {
public class ChannelComponent extends Component<JavaPlugin> {
static TBMCSystemChatEvent.BroadcastTarget roomJoinLeave;
@Override
@ -69,7 +69,7 @@ public class ChannelComponent extends Component {
if (channel instanceof ChatRoom)
((ChatRoom) channel).joinRoom(sender);
}
sender.sendMessage("§6You are now talking in: §b" + user.channel.get().DisplayName().get());
sender.sendMessage("§6You are now talking in: §b" + user.channel.get().DisplayName.get());
} else
TBMCChatAPI.SendChatMessage(ChatMessage.builder(sender, user, message).fromCommand(true)
.permCheck(senderMC.getPermCheck()).build(), channel);

View file

@ -38,8 +38,8 @@ public class MemberCommand extends ICommand2MC {
sender.sendMessage("§cCannot find player or haven't played before.");
return;
}
if (add ? MainPlugin.permission.playerAddGroup(null, op, component.memberGroup().get())
: MainPlugin.permission.playerRemoveGroup(null, op, component.memberGroup().get()))
if (add ? MainPlugin.permission.playerAddGroup(null, op, component.memberGroup.get())
: MainPlugin.permission.playerRemoveGroup(null, op, component.memberGroup.get()))
sender.sendMessage("§b" + op.getName() + " " + (add ? "added" : "removed") + " as a member!");
else
sender.sendMessage("§cFailed to " + (add ? "add" : "remove") + " " + op.getName() + " as a member!");

View file

@ -25,23 +25,17 @@ public class MemberComponent extends Component<MainPlugin> implements Listener {
/**
* The permission group to give to the player
*/
ConfigData<String> memberGroup() {
return getConfig().getData("memberGroup", "member");
}
final ConfigData<String> memberGroup = getConfig().getData("memberGroup", "member");
/**
* The amount of hours needed to play before promotion
*/
private ConfigData<Integer> playedHours() {
return getConfig().getData("playedHours", 12);
}
private final ConfigData<Integer> playedHours = getConfig().getData("playedHours", 12);
/**
* The amount of days passed since first login
*/
private ConfigData<Integer> registeredForDays() {
return getConfig().getData("registeredForDays", 7);
}
private final ConfigData<Integer> registeredForDays = getConfig().getData("registeredForDays", 7);
private AbstractMap.SimpleEntry<Statistic, Integer> playtime;
@ -69,7 +63,7 @@ public class MemberComponent extends Component<MainPlugin> implements Listener {
public Boolean addPlayerAsMember(Player player) {
try {
if (permission.playerAddGroup(null, player, memberGroup().get())) {
if (permission.playerAddGroup(null, player, memberGroup.get())) {
player.sendMessage("§bYou are a member now!");
log("Added " + player.getName() + " as a member.");
return true;
@ -84,7 +78,7 @@ public class MemberComponent extends Component<MainPlugin> implements Listener {
}
public boolean checkNotMember(Player player) {
return permission != null && !permission.playerInGroup(player, memberGroup().get());
return permission != null && !permission.playerInGroup(player, memberGroup.get());
}
public boolean checkRegTime(Player player) {
@ -92,14 +86,14 @@ public class MemberComponent extends Component<MainPlugin> implements Listener {
}
public boolean checkPlayTime(Player player) {
return getPlayTime(player) > playtime.getValue() * playedHours().get();
return getPlayTime(player) > playtime.getValue() * playedHours.get();
}
/**
* Returns milliseconds
*/
public long getRegTime(Player player) {
Instant date = new Date(player.getFirstPlayed()).toInstant().plus(registeredForDays().get(), ChronoUnit.DAYS);
Instant date = new Date(player.getFirstPlayed()).toInstant().plus(registeredForDays.get(), ChronoUnit.DAYS);
if (date.isAfter(Instant.now()))
return date.toEpochMilli() - Instant.now().toEpochMilli();
return -1;
@ -113,7 +107,7 @@ public class MemberComponent extends Component<MainPlugin> implements Listener {
* Returns hours
*/
public double getPlayTime(Player player) {
double pt = playedHours().get() - (double) getPlayTimeTotal(player) / playtime.getValue();
double pt = playedHours.get() - (double) getPlayTimeTotal(player) / playtime.getValue();
if (pt < 0) return -1;
return pt;
}

View file

@ -33,7 +33,7 @@ public class RestartComponent extends Component<MainPlugin> implements Listener
registerListener(this);
restartBroadcast = TBMCSystemChatEvent.BroadcastTarget.add("restartCountdown");
int restartAt = restartAt().get();
int restartAt = this.restartAt.get();
if (restartAt < 0) return;
int restart = syncStart(restartAt);
log("Scheduled restart " + (restart / 3600. / 20.) + " hours from now");
@ -48,9 +48,7 @@ public class RestartComponent extends Component<MainPlugin> implements Listener
/**
* Specifies the hour of day when the server should be restarted. Set to -1 to disable.
*/
private ConfigData<Integer> restartAt() {
return getConfig().getData("restartAt", 12);
}
private final ConfigData<Integer> restartAt = getConfig().getData("restartAt", 12);
private long lasttime = 0;
@Getter

View file

@ -29,7 +29,7 @@ public class SpawnComponent extends Component<MainPlugin> implements PluginMessa
@Override
protected void enable() {
registerCommand(new SpawnCommand());
if (targetServer().get().length() == 0) {
if (targetServer.get().length() == 0) {
spawnloc = MultiverseCore.getPlugin(MultiverseCore.class).getMVWorldManager().getFirstSpawnWorld()
.getSpawnLocation();
}
@ -49,7 +49,7 @@ public class SpawnComponent extends Component<MainPlugin> implements PluginMessa
if (!channel.equals("BungeeCord")) {
return;
}
if (targetServer().get().length() != 0)
if (targetServer.get().length() != 0)
return;
ByteArrayDataInput in = ByteStreams.newDataInput(message);
String subchannel = in.readUTF();
@ -78,9 +78,7 @@ public class SpawnComponent extends Component<MainPlugin> implements PluginMessa
/**
* The BungeeCord server that has the spawn. Set to empty if this server is the target.
*/
private ConfigData<String> targetServer() {
return getConfig().getData("targetServer", "");
}
private final ConfigData<String> targetServer = getConfig().getData("targetServer", "");
private Location spawnloc;
@ -92,7 +90,7 @@ public class SpawnComponent extends Component<MainPlugin> implements PluginMessa
@SuppressWarnings("UnstableApiUsage")
@Command2.Subcommand
public void def(Player player) {
if (targetServer().get().length() == 0) {
if (targetServer.get().length() == 0) {
player.sendMessage("§bTeleporting to spawn...");
try {
if (MainPlugin.ess != null)
@ -107,7 +105,7 @@ public class SpawnComponent extends Component<MainPlugin> implements PluginMessa
}
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("Connect");
out.writeUTF(targetServer().get());
out.writeUTF(targetServer.get());
player.sendPluginMessage(getPlugin(), "BungeeCord", out.toByteArray());

View file

@ -20,9 +20,7 @@ import org.bukkit.event.EventHandler;
public class VotifierComponent extends Component<MainPlugin> {
private final Economy economy;
private ConfigData<Double> rewardAmount() {
return getConfig().getData("rewardAmount", 0.0);
}
private final ConfigData<Double> rewardAmount = getConfig().getData("rewardAmount", 0.0);
@Override
protected void enable() {

View file

@ -171,6 +171,6 @@ public class TBMCCoreAPI {
public static boolean IsTestServer() {
if (MainPlugin.Instance == null) return true;
return MainPlugin.Instance.test().get();
return MainPlugin.Instance.test.get();
}
}

View file

@ -34,9 +34,8 @@ public abstract class Component<TP extends JavaPlugin> {
private @Getter final IHaveConfig config = new IHaveConfig(null);
private @Getter IHaveConfig data; //TODO
public final ConfigData<Boolean> shouldBeEnabled() {
return config.getData("enabled", Optional.ofNullable(getClass().getAnnotation(ComponentMetadata.class)).map(ComponentMetadata::enabledByDefault).orElse(true));
}
public final ConfigData<Boolean> shouldBeEnabled = config.getData("enabled",
Optional.ofNullable(getClass().getAnnotation(ComponentMetadata.class)).map(ComponentMetadata::enabledByDefault).orElse(true));
/**
* Registers a component checking it's dependencies and calling {@link #register(JavaPlugin)}.<br>
@ -87,7 +86,7 @@ public abstract class Component<TP extends JavaPlugin> {
components.put(component.getClass(), component);
if (plugin instanceof ButtonPlugin)
((ButtonPlugin) plugin).getComponentStack().push(component);
if (ComponentManager.areComponentsEnabled() && component.shouldBeEnabled().get()) {
if (ComponentManager.areComponentsEnabled() && component.shouldBeEnabled.get()) {
try { //Enable components registered after the previous ones getting enabled
setComponentEnabled(component, true);
return true;

View file

@ -199,7 +199,7 @@ public class Command2MC extends Command2<ICommand2MC, Command2MCSender> implemen
if (pcmd != null)
System.out.println("ButtonPlugin: " + (pcmd.getPlugin() instanceof ButtonPlugin));*/
if (!checkPlugin
|| MainPlugin.Instance.prioritizeCustomCommands().get()
|| MainPlugin.Instance.prioritizeCustomCommands.get()
|| (pcmd = Bukkit.getPluginCommand(mainpath)) == null //Our commands aren't PluginCommands
|| pcmd.getPlugin() instanceof ButtonPlugin) //Unless it's specified in the plugin.yml
return super.handleCommand(sender, commandline);

View file

@ -35,9 +35,9 @@ public class TBMCChatAPI {
*/
public static boolean SendChatMessage(ChatMessage cm, Channel channel) {
if (!Channel.getChannelList().contains(channel))
throw new RuntimeException("Channel " + channel.DisplayName().get() + " not registered!");
if (!channel.Enabled().get()) {
cm.getSender().sendMessage("§cThe channel '" + channel.DisplayName().get() + "' is disabled!");
throw new RuntimeException("Channel " + channel.DisplayName.get() + " not registered!");
if (!channel.Enabled.get()) {
cm.getSender().sendMessage("§cThe channel '" + channel.DisplayName.get() + "' is disabled!");
return true; //Cancel sending if channel is disabled
}
Supplier<Boolean> task = () -> {
@ -70,11 +70,11 @@ public class TBMCChatAPI {
*/
public static boolean SendSystemMessage(Channel channel, RecipientTestResult rtr, String message, TBMCSystemChatEvent.BroadcastTarget target, String... exceptions) {
if (!Channel.getChannelList().contains(channel))
throw new RuntimeException("Channel " + channel.DisplayName().get() + " not registered!");
if (!channel.Enabled().get())
throw new RuntimeException("Channel " + channel.DisplayName.get() + " not registered!");
if (!channel.Enabled.get())
return true; //Cancel sending
if (!Arrays.asList(exceptions).contains("Minecraft"))
Bukkit.getConsoleSender().sendMessage("[" + channel.DisplayName().get() + "] " + message);
Bukkit.getConsoleSender().sendMessage("[" + channel.DisplayName.get() + "] " + message);
TBMCSystemChatEvent event = new TBMCSystemChatEvent(channel, message, rtr.score, rtr.groupID, exceptions, target);
return ChromaUtils.callEventAsync(event);
}

View file

@ -23,9 +23,7 @@ public abstract class TBMCPlayerBase extends ChromaGamerBase {
return uuid;
}
public ConfigData<String> PlayerName() {
return super.config.getData("PlayerName", "");
}
public final ConfigData<String> PlayerName = super.config.getData("PlayerName", "");
/**
* Get player as a plugin player.