Put channels in a component

Using the per-component AddCommand method
CommandComponent got removed, no need for that
Made channel properties configurable (DisplayName, Color)
Made configs testable, it will only use the cached value in that case
This was needed so channel registering continue to work during testing
Made channels possible to disable (WIP)
#48
This commit is contained in:
Norbi Peti 2019-01-12 00:27:55 +01:00
parent a6d1122f7f
commit 1b152d8b4e
No known key found for this signature in database
GPG key ID: DBA4C4549A927E56
21 changed files with 298 additions and 233 deletions

View file

@ -1,7 +1,7 @@
<component name="InspectionProjectProfileManager"> <component name="InspectionProjectProfileManager">
<profile version="1.0"> <profile version="1.0">
<option name="myName" value="Project Default" /> <option name="myName" value="Project Default" />
<inspection_tool class="WeakerAccess" enabled="true" level="WARNING" enabled_by_default="true"> <inspection_tool class="WeakerAccess" enabled="false" level="WARNING" enabled_by_default="false">
<option name="SUGGEST_PACKAGE_LOCAL_FOR_MEMBERS" value="false" /> <option name="SUGGEST_PACKAGE_LOCAL_FOR_MEMBERS" value="false" />
<option name="SUGGEST_PACKAGE_LOCAL_FOR_TOP_CLASSES" value="false" /> <option name="SUGGEST_PACKAGE_LOCAL_FOR_TOP_CLASSES" value="false" />
<option name="SUGGEST_PRIVATE_FOR_INNERS" value="false" /> <option name="SUGGEST_PRIVATE_FOR_INNERS" value="false" />

View file

@ -1,175 +1,212 @@
package buttondevteam.lib.chat; package buttondevteam.component.channel;
import buttondevteam.core.MainPlugin; import buttondevteam.core.ComponentManager;
import org.bukkit.Bukkit; import buttondevteam.core.MainPlugin;
import org.bukkit.command.CommandSender; import buttondevteam.lib.architecture.Component;
import org.bukkit.entity.Player; import buttondevteam.lib.architecture.ConfigData;
import buttondevteam.lib.chat.Color;
import javax.annotation.Nullable; import com.google.common.collect.Lists;
import java.util.ArrayList; import org.bukkit.Bukkit;
import java.util.List; import org.bukkit.command.CommandSender;
import java.util.function.BiFunction; import org.bukkit.entity.Player;
import java.util.function.BiPredicate;
import java.util.function.Function; import javax.annotation.Nullable;
import java.util.function.Predicate; import java.util.ArrayList;
import java.util.List;
public class Channel { import java.util.function.BiFunction;
/** import java.util.function.BiPredicate;
* 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} import java.util.function.Function;
*/ import java.util.function.Predicate;
public static final int SCORE_SEND_OK = 0;
/** public class Channel {
* Specifies a score that means the user doesn't have permission to see or send the message. Any negative value has the same effect. /**
*/ * 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}
public static final int SCORE_SEND_NOPE = -1; */
/** public static final int SCORE_SEND_OK = 0;
* Send the message to everyone <i>who has access to the channel</i> - this does not necessarily mean all players /**
*/ * Specifies a score that means the user doesn't have permission to see or send the message. Any negative value has the same effect.
public static final String GROUP_EVERYONE = "everyone"; */
public final String DisplayName; public static final int SCORE_SEND_NOPE = -1;
public final Color color; /**
public final String ID; * Send the message to everyone <i>who has access to the channel</i> - this does not necessarily mean all players
@Nullable */
public String[] IDs; public static final String GROUP_EVERYONE = "everyone";
/**
* Filters both the sender and the targets private static ChannelComponent component;
*/
private final Function<CommandSender, RecipientTestResult> filteranderrormsg; private String defDisplayName;
private Color defColor;
private static final List<Channel> channels = new ArrayList<>();
private void throwGame() {
/** if (component == null) throw new RuntimeException("Cannot access channel properties until registered!");
* Creates a channel. }
*
* @param displayname The name that should appear at the start of the message. <b>A chat color is expected at the beginning (§9).</b> public final ConfigData<Boolean> Enabled() { //TODO: Implement in all plugins
* @param color The default color of the messages sent in the channel throwGame();
* @param command The command to be used for the channel <i>without /</i>. For example "mod". It's also used for scoreboard objective names. return component.getConfig().getData(ID + ".enabled", true);
* @param filteranderrormsg Checks all senders against the criteria provided here and sends the message if the index matches the sender's - if no score at all, displays the error.<br> }
* May be null to send to everyone.
*/ public final ConfigData<String> DisplayName() {
public Channel(String displayname, Color color, String command, throwGame();
Function<CommandSender, RecipientTestResult> filteranderrormsg) { return component.getConfig().getData(ID + ".displayName", defDisplayName);
DisplayName = displayname; }
this.color = color;
ID = command; public final ConfigData<Color> Color() {
this.filteranderrormsg = filteranderrormsg; throwGame();
} return component.getConfig().getData(ID + ".color", defColor, c -> Color.valueOf((String) c), Enum::toString);
}
/** public final String ID;
* Must be only called from a subclass - otherwise it'll throw an exception.
* @SuppressWarnings("unchecked")
* @see Channel#Channel(String, Color, String, Function) public ConfigData<String[]> IDs() {
*/ throwGame();
@SuppressWarnings("unchecked") return component.getConfig().getData(ID + ".IDs", new String[0], l -> ((List<String>) l).toArray(new String[0]), Lists::newArrayList);
protected <T extends Channel> Channel(String displayname, Color color, String command, }
BiFunction<T, CommandSender, RecipientTestResult> filteranderrormsg) { /**
DisplayName = displayname; * Filters both the sender and the targets
this.color = color; */
ID = command; private final Function<CommandSender, RecipientTestResult> filteranderrormsg;
this.filteranderrormsg = s -> filteranderrormsg.apply((T) this, s);
} private static final List<Channel> channels = new ArrayList<>();
public boolean isGlobal() { /**
return filteranderrormsg == null; * Creates a channel.
} *
* @param displayname The name that should appear at the start of the message. <b>A chat color is expected at the beginning (§9).</b>
/** * @param color The default color of the messages sent in the channel
* Note: Errors are sent to the sender automatically * @param command The command to be used for the channel <i>without /</i>. For example "mod". It's also used for scoreboard objective names.
* * @param filteranderrormsg Checks all senders against the criteria provided here and sends the message if the index matches the sender's - if no score at all, displays the error.<br>
* @param sender The user we're sending to * May be null to send to everyone.
* @param score The (source) score to compare with the user's */
*/ public Channel(String displayname, Color color, String command,
public boolean shouldSendTo(CommandSender sender, int score) { Function<CommandSender, RecipientTestResult> filteranderrormsg) {
return score == getMCScore(sender); //If there's any error, the score won't be equal defDisplayName = displayname;
} defColor = color;
ID = command;
/** this.filteranderrormsg = filteranderrormsg;
* Note: Errors are sent to the sender automatically }
*/
public int getMCScore(CommandSender sender) { /**
return getRTR(sender).score; //No need to check if there was an error * Must be only called from a subclass - otherwise it'll throw an exception.
} *
* @see Channel#Channel(String, Color, String, Function)
/** */
* Note: Errors are sent to the sender automatically<br> @SuppressWarnings("unchecked")
* <p> protected <T extends Channel> Channel(String displayname, Color color, String command,
* Null means don't send BiFunction<T, CommandSender, RecipientTestResult> filteranderrormsg) {
*/ defDisplayName = displayname;
@Nullable defColor = color;
public String getGroupID(CommandSender sender) { ID = command;
return getRTR(sender).groupID; //No need to check if there was an error this.filteranderrormsg = s -> filteranderrormsg.apply((T) this, s);
} }
public RecipientTestResult getRTR(CommandSender sender) { public boolean isGlobal() {
if (filteranderrormsg == null) return filteranderrormsg == null;
return new RecipientTestResult(SCORE_SEND_OK, GROUP_EVERYONE); }
return filteranderrormsg.apply(sender);
} /**
* Note: Errors are sent to the sender automatically
public static List<Channel> getChannels() { *
return channels; * @param sender The user we're sending to
} * @param score The (source) score to compare with the user's
*/
/** public boolean shouldSendTo(CommandSender sender, int score) {
* Convenience method for the function parameter of {@link #Channel(String, Color, String, Function)}. It checks if the sender is OP or optionally has the specified group. The error message is return score == getMCScore(sender); //If there's any error, the score won't be equal
* generated automatically. }
*
* @param permgroup The group that can access the channel or <b>null</b> to only allow OPs. /**
* @return If has access * Note: Errors are sent to the sender automatically
*/ */
public static Function<CommandSender, RecipientTestResult> inGroupFilter(String permgroup) { public int getMCScore(CommandSender sender) {
return noScoreResult( return getRTR(sender).score; //No need to check if there was an error
s -> s.isOp() || (permgroup != null && (s instanceof Player && MainPlugin.permission != null && MainPlugin.permission.playerInGroup((Player) s, permgroup))), }
"You need to be a(n) " + (permgroup != null ? permgroup : "OP") + " to use this channel.");
} /**
* Note: Errors are sent to the sender automatically<br>
public static Function<CommandSender, RecipientTestResult> noScoreResult(Predicate<CommandSender> filter, * <p>
String errormsg) { * Null means don't send
return s -> filter.test(s) ? new RecipientTestResult(SCORE_SEND_OK, GROUP_EVERYONE) : new RecipientTestResult(errormsg); */
} @Nullable
public String getGroupID(CommandSender sender) {
public static <T extends Channel> BiFunction<T, CommandSender, RecipientTestResult> noScoreResult( return getRTR(sender).groupID; //No need to check if there was an error
BiPredicate<T, CommandSender> filter, String errormsg) { }
return (this_, s) -> filter.test(this_, s) ? new RecipientTestResult(SCORE_SEND_OK, GROUP_EVERYONE) : new RecipientTestResult(errormsg);
} public RecipientTestResult getRTR(CommandSender sender) {
if (filteranderrormsg == null)
public static Channel GlobalChat; return new RecipientTestResult(SCORE_SEND_OK, GROUP_EVERYONE);
public static Channel AdminChat; return filteranderrormsg.apply(sender);
public static Channel ModChat; }
static void RegisterChannel(Channel channel) { public static List<Channel> getChannels() {
channels.add(channel); return channels;
Bukkit.getScheduler().runTask(MainPlugin.Instance, () -> Bukkit.getPluginManager().callEvent(new ChatChannelRegisterEvent(channel))); // Wait for server start }
}
/**
public static class RecipientTestResult { * Convenience method for the function parameter of {@link #Channel(String, Color, String, Function)}. It checks if the sender is OP or optionally has the specified group. The error message is
public final String errormessage; * generated automatically.
public final int score; // Anything below 0 is "never send" *
public final String groupID; * @param permgroup The group that can access the channel or <b>null</b> to only allow OPs.
public static final RecipientTestResult ALL = new RecipientTestResult(SCORE_SEND_OK, GROUP_EVERYONE); * @return If has access
*/
/** public static Function<CommandSender, RecipientTestResult> inGroupFilter(String permgroup) {
* Creates a result that indicates an <b>error</b> return noScoreResult(
* s -> s.isOp() || (permgroup != null && (s instanceof Player && MainPlugin.permission != null && MainPlugin.permission.playerInGroup((Player) s, permgroup))),
* @param errormessage The error message to show the sender if they don't meet the criteria. "You need to be a(n) " + (permgroup != null ? permgroup : "OP") + " to use this channel.");
*/ }
public RecipientTestResult(String errormessage) {
this.errormessage = errormessage; public static Function<CommandSender, RecipientTestResult> noScoreResult(Predicate<CommandSender> filter,
this.score = SCORE_SEND_NOPE; String errormsg) {
this.groupID = null; return s -> filter.test(s) ? new RecipientTestResult(SCORE_SEND_OK, GROUP_EVERYONE) : new RecipientTestResult(errormsg);
} }
/** public static <T extends Channel> BiFunction<T, CommandSender, RecipientTestResult> noScoreResult(
* Creates a result that indicates a <b>success</b> BiPredicate<T, CommandSender> filter, String errormsg) {
* return (this_, s) -> filter.test(this_, s) ? new RecipientTestResult(SCORE_SEND_OK, GROUP_EVERYONE) : new RecipientTestResult(errormsg);
* @param score The score that identifies the target group. <b>Must be non-negative.</b> For example, the index of the town or nation to send to. }
* @param groupID The ID of the target group.
*/ public static Channel GlobalChat;
public RecipientTestResult(int score, String groupID) { public static Channel AdminChat;
if (score < 0) throw new IllegalArgumentException("Score must be non-negative!"); public static Channel ModChat;
this.score = score;
this.groupID = groupID; public static void RegisterChannel(Channel channel) {
this.errormessage = null; 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);
Bukkit.getScheduler().runTask(MainPlugin.Instance, () -> Bukkit.getPluginManager().callEvent(new ChatChannelRegisterEvent(channel))); // Wait for server start
}
public static class RecipientTestResult {
public final String errormessage;
public final int score; // Anything below 0 is "never send"
public final String groupID;
public static final RecipientTestResult ALL = new RecipientTestResult(SCORE_SEND_OK, GROUP_EVERYONE);
/**
* Creates a result that indicates an <b>error</b>
*
* @param errormessage The error message to show the sender if they don't meet the criteria.
*/
public RecipientTestResult(String errormessage) {
this.errormessage = errormessage;
this.score = SCORE_SEND_NOPE;
this.groupID = null;
}
/**
* Creates a result that indicates a <b>success</b>
*
* @param score The score that identifies the target group. <b>Must be non-negative.</b> For example, the index of the town or nation to send to.
* @param groupID The ID of the target group.
*/
public RecipientTestResult(int score, String groupID) {
if (score < 0) throw new IllegalArgumentException("Score must be non-negative!");
this.score = score;
this.groupID = groupID;
this.errormessage = null;
}
}
}

View file

@ -0,0 +1,26 @@
package buttondevteam.component.channel;
import buttondevteam.lib.architecture.Component;
import org.bukkit.plugin.java.JavaPlugin;
public class ChannelComponent extends Component {
@Override
protected void register(JavaPlugin plugin) {
super.register(plugin);
}
@Override
protected void unregister(JavaPlugin plugin) {
super.unregister(plugin);
}
@Override
protected void enable() {
}
@Override
protected void disable() {
}
}

View file

@ -1,4 +1,4 @@
package buttondevteam.lib.chat; package buttondevteam.component.channel;
import org.bukkit.event.Event; import org.bukkit.event.Event;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;

View file

@ -1,5 +1,7 @@
package buttondevteam.lib.chat; package buttondevteam.component.channel;
import buttondevteam.lib.chat.Color;
import buttondevteam.lib.chat.TBMCChatAPI;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import java.util.ArrayList; import java.util.ArrayList;

View file

@ -1,15 +0,0 @@
package buttondevteam.component.commands;
import buttondevteam.lib.architecture.Component;
public class CommandComponent extends Component { //TODO: Do we just move everything here?
@Override
public void enable() {
}
@Override
public void disable() {
}
}

View file

@ -9,8 +9,8 @@ public class RestartComponent extends Component {
@Override @Override
public void enable() { public void enable() {
//TODO: Permissions for the commands //TODO: Permissions for the commands
TBMCChatAPI.AddCommand(getPlugin(), ScheduledRestartCommand.class); TBMCChatAPI.AddCommand(this, new ScheduledRestartCommand());
TBMCChatAPI.AddCommand(getPlugin(), PrimeRestartCommand.class); TBMCChatAPI.AddCommand(this, new PrimeRestartCommand());
} }
@Override @Override

View file

@ -6,11 +6,11 @@ import buttondevteam.lib.chat.TBMCChatAPI;
public class PluginUpdaterComponent extends Component { public class PluginUpdaterComponent extends Component {
@Override @Override
public void enable() { public void enable() {
TBMCChatAPI.AddCommand(getPlugin(), UpdatePluginCommand.class); TBMCChatAPI.AddCommand(this, new UpdatePluginCommand());
} }
@Override @Override
public void disable() { //TODO: Unregister commands and such public void disable() { //Commands are automatically unregistered
} }
} }

View file

@ -1,12 +1,13 @@
package buttondevteam.core; package buttondevteam.core;
import buttondevteam.component.channel.Channel;
import buttondevteam.component.channel.ChannelComponent;
import buttondevteam.component.channel.ChatRoom;
import buttondevteam.component.restart.RestartComponent; import buttondevteam.component.restart.RestartComponent;
import buttondevteam.component.updater.PluginUpdater; import buttondevteam.component.updater.PluginUpdater;
import buttondevteam.component.updater.PluginUpdaterComponent; import buttondevteam.component.updater.PluginUpdaterComponent;
import buttondevteam.lib.TBMCCoreAPI; import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.architecture.Component; import buttondevteam.lib.architecture.Component;
import buttondevteam.lib.chat.Channel;
import buttondevteam.lib.chat.ChatRoom;
import buttondevteam.lib.chat.Color; import buttondevteam.lib.chat.Color;
import buttondevteam.lib.chat.TBMCChatAPI; import buttondevteam.lib.chat.TBMCChatAPI;
import buttondevteam.lib.player.ChromaGamerBase; import buttondevteam.lib.player.ChromaGamerBase;
@ -54,6 +55,7 @@ public class MainPlugin extends JavaPlugin {
saveConfig(); saveConfig();
Component.registerComponent(this, new PluginUpdaterComponent()); Component.registerComponent(this, new PluginUpdaterComponent());
Component.registerComponent(this, new RestartComponent()); Component.registerComponent(this, new RestartComponent());
Component.registerComponent(this, new ChannelComponent());
ComponentManager.enableComponents(); ComponentManager.enableComponents();
TBMCChatAPI.AddCommand(this, MemberCommand.class); TBMCChatAPI.AddCommand(this, MemberCommand.class);
TBMCCoreAPI.RegisterEventsForExceptions(new PlayerListener(), this); TBMCCoreAPI.RegisterEventsForExceptions(new PlayerListener(), this);
@ -62,8 +64,7 @@ public class MainPlugin extends JavaPlugin {
ChromaGamerBase.addConverter(sender -> Optional.ofNullable(sender instanceof Player ChromaGamerBase.addConverter(sender -> Optional.ofNullable(sender instanceof Player
? TBMCPlayer.getPlayer(((Player) sender).getUniqueId(), TBMCPlayer.class) : null)); //Players, has higher priority ? TBMCPlayer.getPlayer(((Player) sender).getUniqueId(), TBMCPlayer.class) : null)); //Players, has higher priority
TBMCCoreAPI.RegisterUserClass(TBMCPlayerBase.class); TBMCCoreAPI.RegisterUserClass(TBMCPlayerBase.class);
TBMCChatAPI.RegisterChatChannel(Channel.GlobalChat = new Channel("§fOOC§f", Color.White, "ooc", null)); TBMCChatAPI.RegisterChatChannel(Channel.GlobalChat = new Channel("§fOOC§f", Color.White, "g", null)); //The /ooc ID has moved to the config
Channel.GlobalChat.IDs = new String[]{"g"}; //Support /g as well
TBMCChatAPI.RegisterChatChannel( TBMCChatAPI.RegisterChatChannel(
Channel.AdminChat = new Channel("§cADMIN§f", Color.Red, "a", Channel.inGroupFilter(null))); Channel.AdminChat = new Channel("§cADMIN§f", Color.Red, "a", Channel.inGroupFilter(null)));
TBMCChatAPI.RegisterChatChannel( TBMCChatAPI.RegisterChatChannel(

View file

@ -59,6 +59,6 @@ public class PlayerListener implements Listener {
if (Arrays.stream(event.getExceptions()).anyMatch("Minecraft"::equalsIgnoreCase)) if (Arrays.stream(event.getExceptions()).anyMatch("Minecraft"::equalsIgnoreCase))
return; return;
Bukkit.getOnlinePlayers().stream().filter(event::shouldSendTo) Bukkit.getOnlinePlayers().stream().filter(event::shouldSendTo)
.forEach(p -> p.sendMessage(event.getChannel().DisplayName.substring(0, 2) + event.getMessage())); .forEach(p -> p.sendMessage(event.getChannel().DisplayName().get().substring(0, 2) + event.getMessage()));
} }
} }

View file

@ -1,6 +1,8 @@
package buttondevteam.core; package buttondevteam.core;
import buttondevteam.lib.chat.Channel; import buttondevteam.component.channel.Channel;
import buttondevteam.component.channel.ChannelComponent;
import buttondevteam.lib.architecture.Component;
import buttondevteam.lib.chat.Color; import buttondevteam.lib.chat.Color;
import buttondevteam.lib.chat.TBMCChatAPI; import buttondevteam.lib.chat.TBMCChatAPI;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@ -38,6 +40,7 @@ public class TestPrepare {
return cl.isAssignableFrom(invocation.getMethod().getReturnType()); return cl.isAssignableFrom(invocation.getMethod().getReturnType());
} }
})); }));
Component.registerComponent(Mockito.mock(MainPlugin.class), new ChannelComponent());
TBMCChatAPI.RegisterChatChannel(Channel.GlobalChat = new Channel("§fg§f", Color.White, "g", null)); TBMCChatAPI.RegisterChatChannel(Channel.GlobalChat = new Channel("§fg§f", Color.White, "g", null));
} }
} }

View file

@ -1,6 +1,6 @@
package buttondevteam.lib; package buttondevteam.lib;
import buttondevteam.lib.chat.Channel; import buttondevteam.component.channel.Channel;
import buttondevteam.lib.chat.ChatMessage; import buttondevteam.lib.chat.ChatMessage;
import lombok.Getter; import lombok.Getter;
import lombok.experimental.Delegate; import lombok.experimental.Delegate;

View file

@ -1,6 +1,6 @@
package buttondevteam.lib; package buttondevteam.lib;
import buttondevteam.lib.chat.Channel; import buttondevteam.component.channel.Channel;
import lombok.Getter; import lombok.Getter;
import lombok.NonNull; import lombok.NonNull;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;

View file

@ -1,6 +1,6 @@
package buttondevteam.lib; package buttondevteam.lib;
import buttondevteam.lib.chat.Channel; import buttondevteam.component.channel.Channel;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;

View file

@ -1,6 +1,6 @@
package buttondevteam.lib; package buttondevteam.lib;
import buttondevteam.lib.chat.Channel; import buttondevteam.component.channel.Channel;
import lombok.Getter; import lombok.Getter;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;

View file

@ -34,7 +34,7 @@ public abstract class Component {
private @Getter private @Getter
IHaveConfig config; IHaveConfig config;
public ConfigData<Boolean> shouldBeEnabled() { public final ConfigData<Boolean> shouldBeEnabled() {
return config.getData("enabled", true); return config.getData("enabled", true);
} }
@ -78,12 +78,15 @@ public abstract class Component {
} }
if (register) { if (register) {
component.plugin = plugin; component.plugin = plugin;
var compconf = plugin.getConfig().getConfigurationSection("components"); if (plugin.getConfig() != null) { //Production
if (compconf == null) compconf = plugin.getConfig().createSection("components"); var compconf = plugin.getConfig().getConfigurationSection("components");
component.configSect = compconf.getConfigurationSection(component.getClassName()); if (compconf == null) compconf = plugin.getConfig().createSection("components");
if (component.configSect == null) component.configSect = compconf.getConfigurationSection(component.getClassName());
component.configSect = compconf.createSection(component.getClassName()); if (component.configSect == null)
component.config = new IHaveConfig(component.configSect); component.configSect = compconf.createSection(component.getClassName());
component.config = new IHaveConfig(component.configSect);
} else //Testing
component.config = new IHaveConfig(null);
component.register(plugin); component.register(plugin);
components.put(component.getClass(), component); components.put(component.getClass(), component);
if (ComponentManager.areComponentsEnabled() && component.shouldBeEnabled().get()) { if (ComponentManager.areComponentsEnabled() && component.shouldBeEnabled().get()) {
@ -179,23 +182,21 @@ public abstract class Component {
protected abstract void disable(); protected abstract void disable();
/** /**
* Registers a TBMCCommand to the plugin. Make sure to add it to plugin.yml and use {@link buttondevteam.lib.chat.CommandClass}. * Registers a TBMCCommand to the component. Make sure to add it to plugin.yml and use {@link buttondevteam.lib.chat.CommandClass}.
* *
* @param plugin Main plugin responsible for stuff
* @param commandBase Custom coded command class * @param commandBase Custom coded command class
*/ */
protected void registerCommand(JavaPlugin plugin, TBMCCommandBase commandBase) { protected final void registerCommand(TBMCCommandBase commandBase) {
TBMCChatAPI.AddCommand(plugin, commandBase); TBMCChatAPI.AddCommand(this, commandBase);
} }
/** /**
* Registers a Listener to this plugin * Registers a Listener to this component
* *
* @param plugin Main plugin responsible for stuff
* @param listener The event listener to register * @param listener The event listener to register
* @return The provided listener * @return The provided listener
*/ */
protected Listener registerListener(JavaPlugin plugin, Listener listener) { protected final Listener registerListener(Listener listener) {
TBMCCoreAPI.RegisterEventsForExceptions(listener, plugin); TBMCCoreAPI.RegisterEventsForExceptions(listener, plugin);
return listener; return listener;
} }

View file

@ -15,6 +15,9 @@ import java.util.function.Function;
@RequiredArgsConstructor(access = AccessLevel.PACKAGE) @RequiredArgsConstructor(access = AccessLevel.PACKAGE)
//@AllArgsConstructor(access = AccessLevel.PACKAGE) //@AllArgsConstructor(access = AccessLevel.PACKAGE)
public class ConfigData<T> { //TODO: Save after a while public class ConfigData<T> { //TODO: Save after a while
/**
* May be null for testing
*/
private final ConfigurationSection config; private final ConfigurationSection config;
private final String path; private final String path;
private @Nullable final T def; private @Nullable final T def;
@ -46,14 +49,14 @@ public class ConfigData<T> { //TODO: Save after a while
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public T get() { public T get() {
if (value != null) return value; //Speed things up if (value != null) return value; //Speed things up
Object val = config.get(path); Object val = config == null ? null : config.get(path); //config==null: testing
if (val == null) { if (val == null) {
val = primitiveDef; val = primitiveDef;
} }
if (val == primitiveDef && !saved) { if (val == primitiveDef && !saved) {
if (def != null) if (def != null)
set(def); //Save default value set(def); //Save default value
else else if (config != null) //config==null: testing
config.set(path, primitiveDef); config.set(path, primitiveDef);
saved = true; saved = true;
} }
@ -70,7 +73,8 @@ public class ConfigData<T> { //TODO: Save after a while
if (setter != null) if (setter != null)
val = setter.apply(value); val = setter.apply(value);
else val = value; else val = value;
config.set(path, val); if (config != null)
this.value =value; config.set(path, val);
this.value = value;
} }
} }

View file

@ -12,6 +12,11 @@ public final class IHaveConfig {
private final HashMap<String, ConfigData<?>> datamap = new HashMap<>(); private final HashMap<String, ConfigData<?>> datamap = new HashMap<>();
private ConfigurationSection config; private ConfigurationSection config;
/**
* May be used in testing
*
* @param section May be null for testing
*/
IHaveConfig(ConfigurationSection section) { IHaveConfig(ConfigurationSection section) {
config = section; config = section;
} }

View file

@ -1,5 +1,7 @@
package buttondevteam.lib.chat; package buttondevteam.lib.chat;
import buttondevteam.component.channel.Channel;
import buttondevteam.component.channel.Channel.RecipientTestResult;
import buttondevteam.core.CommandCaller; import buttondevteam.core.CommandCaller;
import buttondevteam.core.MainPlugin; import buttondevteam.core.MainPlugin;
import buttondevteam.lib.TBMCChatEvent; import buttondevteam.lib.TBMCChatEvent;
@ -7,7 +9,6 @@ import buttondevteam.lib.TBMCChatPreprocessEvent;
import buttondevteam.lib.TBMCCoreAPI; import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.TBMCSystemChatEvent; import buttondevteam.lib.TBMCSystemChatEvent;
import buttondevteam.lib.architecture.Component; import buttondevteam.lib.architecture.Component;
import buttondevteam.lib.chat.Channel.RecipientTestResult;
import lombok.val; import lombok.val;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@ -130,7 +131,7 @@ public class TBMCChatAPI {
/** /**
* <p> * <p>
* This method adds a plugin's command to help and sets it's executor. * This method adds a plugin's command to help and sets it's executor. They will be automatically unregistered on plugin disable.
* </p> * </p>
* <p> * <p>
* The <u>command must be registered</u> in the caller plugin's plugin.yml. Otherwise the plugin will output a messsage to console. * The <u>command must be registered</u> in the caller plugin's plugin.yml. Otherwise the plugin will output a messsage to console.
@ -163,7 +164,7 @@ public class TBMCChatAPI {
/** /**
* <p> * <p>
* This method adds a plugin's command to help and sets its executor. * This method adds a plugin's command to help and sets its executor. They will be automatically unregistered on plugin disable.
* </p> * </p>
* <p> * <p>
* The <u>command must be registered</u> in the caller plugin's plugin.yml. Otherwise the plugin will output a message to console. * The <u>command must be registered</u> in the caller plugin's plugin.yml. Otherwise the plugin will output a message to console.
@ -191,7 +192,7 @@ public class TBMCChatAPI {
/** /**
* <p> * <p>
* This method adds a plugin's command to help and sets its executor. * This method adds a plugin's command to help and sets its executor. They will be automatically unregistered on component disable.
* </p> * </p>
* <p> * <p>
* The <u>command must be registered</u> in the caller plugin's plugin.yml. Otherwise the plugin will output a message to console. * The <u>command must be registered</u> in the caller plugin's plugin.yml. Otherwise the plugin will output a message to console.
@ -277,7 +278,7 @@ public class TBMCChatAPI {
*/ */
public static boolean SendChatMessage(ChatMessage cm, Channel channel) { public static boolean SendChatMessage(ChatMessage cm, Channel channel) {
if (!Channel.getChannels().contains(channel)) if (!Channel.getChannels().contains(channel))
throw new RuntimeException("Channel " + channel.DisplayName + " not registered!"); throw new RuntimeException("Channel " + channel.DisplayName().get() + " not registered!");
val permcheck = cm.getPermCheck(); val permcheck = cm.getPermCheck();
RecipientTestResult rtr = getScoreOrSendError(channel, permcheck); RecipientTestResult rtr = getScoreOrSendError(channel, permcheck);
int score = rtr.score; int score = rtr.score;
@ -308,7 +309,7 @@ public class TBMCChatAPI {
*/ */
public static boolean SendSystemMessage(Channel channel, RecipientTestResult rtr, String message, String... exceptions) { public static boolean SendSystemMessage(Channel channel, RecipientTestResult rtr, String message, String... exceptions) {
if (!Channel.getChannels().contains(channel)) if (!Channel.getChannels().contains(channel))
throw new RuntimeException("Channel " + channel.DisplayName + " not registered!"); throw new RuntimeException("Channel " + channel.DisplayName().get() + " not registered!");
TBMCSystemChatEvent event = new TBMCSystemChatEvent(channel, message, rtr.score, rtr.groupID, exceptions); TBMCSystemChatEvent event = new TBMCSystemChatEvent(channel, message, rtr.score, rtr.groupID, exceptions);
Bukkit.getPluginManager().callEvent(event); Bukkit.getPluginManager().callEvent(event);
return event.isCancelled(); return event.isCancelled();

View file

@ -1,6 +1,6 @@
package buttondevteam.lib.player; package buttondevteam.lib.player;
import buttondevteam.lib.chat.Channel; import buttondevteam.component.channel.Channel;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
public class ChannelPlayerData { //I just want this to work public class ChannelPlayerData { //I just want this to work

View file

@ -1,7 +1,7 @@
package buttondevteam.lib.player; package buttondevteam.lib.player;
import buttondevteam.component.channel.Channel;
import buttondevteam.lib.TBMCCoreAPI; import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.chat.Channel;
import com.google.common.collect.HashBiMap; import com.google.common.collect.HashBiMap;
import lombok.val; import lombok.val;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;