Finish style fixes

This commit is contained in:
Draycia committed 2020-09-10 02:30:34 -07:00
1 parent 9f496be5f3
commit c68b92dc62
44 files changed
+623 -620

No files matched your search

+1 -1
View File
@@ -28,5 +28,5 @@
<suppressions> <suppressions>
<!-- add any necessary suppressions here --> <!-- add any necessary suppressions here -->
<suppress files="src[\\/]test[\\/]java[\\/].*" checks="RequireExplicitVisibilityModifier"/> <suppress files="src[\\/]test[\\/]java[\\/].*" checks="RequireExplicitVisibilityModifier"/>
<suppress files=".*[\\/]nbt[\\/](List|Compound)BinaryTag.java" checks="MethodName"/> <suppress files="Metrics\.java" checks="[a-zA-Z0-9]*"/>
</suppressions> </suppressions>
-1
View File
@@ -8,7 +8,6 @@ plugins {
id 'net.minecrell.plugin-yml.bukkit' version '0.3.0' id 'net.minecrell.plugin-yml.bukkit' version '0.3.0'
id 'com.palantir.git-version' version '0.12.3' id 'com.palantir.git-version' version '0.12.3'
id 'org.checkerframework' version '0.5.9' id 'org.checkerframework' version '0.5.9'
id 'com.github.sherter.google-java-format' version '0.8'
} }
// Gets the git commit hash of the latest commit, used for version string // Gets the git commit hash of the latest commit, used for version string
@@ -80,72 +80,72 @@ public final class CarbonChat extends JavaPlugin {
@Override @Override
public void onEnable() { public void onEnable() {
checkForBungee(); this.checkForBungee();
CommandAPI.onEnable(this); CommandAPI.onEnable(this);
Metrics metrics = new Metrics(this, BSTATS_PLUGIN_ID); final Metrics metrics = new Metrics(this, BSTATS_PLUGIN_ID);
// Ensure config is present to be modified by the user // Ensure config is present to be modified by the user
if (!(new File(getDataFolder(), "config.yml").exists())) { if (!(new File(this.getDataFolder(), "config.yml").exists())) {
saveDefaultConfig(); this.saveDefaultConfig();
} }
if (!(new File(getDataFolder(), "moderation.yml").exists())) { if (!(new File(this.getDataFolder(), "moderation.yml").exists())) {
saveResource("moderation.yml", false); this.saveResource("moderation.yml", false);
} }
if (!(new File(getDataFolder(), "language.yml").exists())) { if (!(new File(this.getDataFolder(), "language.yml").exists())) {
saveResource("language.yml", false); this.saveResource("language.yml", false);
} }
if (!(new File(getDataFolder(), "commands.yml").exists())) { if (!(new File(this.getDataFolder(), "commands.yml").exists())) {
saveResource("commands.yml", false); this.saveResource("commands.yml", false);
} }
loadModConfig(); this.loadModConfig();
loadLanguage(); this.loadLanguage();
// Setup Adventure // Setup Adventure
adventureManager = new AdventureManager(this); this.adventureManager = new AdventureManager(this);
// Setup vault and permissions // Setup vault and permissions
permission = getServer().getServicesManager().getRegistration(Permission.class).getProvider(); this.permission = this.getServer().getServicesManager().getRegistration(Permission.class).getProvider();
// Initialize managers // Initialize managers
channelManager = new ChannelManager(this); this.channelManager = new ChannelManager(this);
contextManager = new ContextManager(); this.contextManager = new ContextManager();
messageManager = new MessageManager(this); this.messageManager = new MessageManager(this);
commandManager = new CommandManager(this); this.commandManager = new CommandManager(this);
String storageType = getConfig().getString("storage.type"); final String storageType = this.getConfig().getString("storage.type");
if (storageType.equalsIgnoreCase("mysql")) { if (storageType.equalsIgnoreCase("mysql")) {
getLogger().info("Enabling MySQL storage!"); this.getLogger().info("Enabling MySQL storage!");
userService = new MySQLUserService(this); this.userService = new MySQLUserService(this);
} else if (storageType.equalsIgnoreCase("json")) { } else if (storageType.equalsIgnoreCase("json")) {
getLogger().info("Enabling JSON storage!"); this.getLogger().info("Enabling JSON storage!");
userService = new JSONUserService(this); this.userService = new JSONUserService(this);
} else { } else {
getLogger().warning("Invalid storage type selected! Falling back to JSON."); this.getLogger().warning("Invalid storage type selected! Falling back to JSON.");
userService = new JSONUserService(this); this.userService = new JSONUserService(this);
} }
// Setup listeners // Setup listeners
setupListeners(); this.setupListeners();
registerContexts(); this.registerContexts();
new CarbonPlaceholders(this).register(); new CarbonPlaceholders(this).register();
if (Bukkit.getPluginManager().isPluginEnabled("Towny")) { if (Bukkit.getPluginManager().isPluginEnabled("Towny")) {
getServer().getPluginManager().registerEvents(new TownyContext(this), this); this.getServer().getPluginManager().registerEvents(new TownyContext(this), this);
} }
if (Bukkit.getPluginManager().isPluginEnabled("mcMMO")) { if (Bukkit.getPluginManager().isPluginEnabled("mcMMO")) {
getServer().getPluginManager().registerEvents(new mcMMOContext(this), this); this.getServer().getPluginManager().registerEvents(new mcMMOContext(this), this);
} }
if (Bukkit.getPluginManager().isPluginEnabled("WorldGuard")) { if (Bukkit.getPluginManager().isPluginEnabled("WorldGuard")) {
getServer().getPluginManager().registerEvents(new WorldGuardContext(this), this); this.getServer().getPluginManager().registerEvents(new WorldGuardContext(this), this);
} }
if (Bukkit.getServicesManager().isProvidedFor(Economy.class)) { if (Bukkit.getServicesManager().isProvidedFor(Economy.class)) {
@@ -153,25 +153,25 @@ public final class CarbonChat extends JavaPlugin {
} }
if (!FunctionalityConstants.HAS_HOVER_EVENT_METHOD) { if (!FunctionalityConstants.HAS_HOVER_EVENT_METHOD) {
getLogger().warning("Item linking disabled! Please use Paper 1.16.2 #172 or newer."); this.getLogger().warning("Item linking disabled! Please use Paper 1.16.2 #172 or newer.");
} }
} }
@Override @Override
public void onDisable() { public void onDisable() {
userService.onDisable(); this.userService.onDisable();
} }
private void setupListeners() { private void setupListeners() {
PluginManager pluginManager = getServer().getPluginManager(); final PluginManager pluginManager = this.getServer().getPluginManager();
filterHandler = new FilterHandler(this); this.filterHandler = new FilterHandler(this);
// Register chat listeners // Register chat listeners
pluginManager.registerEvents(new BukkitChatListener(this), this); pluginManager.registerEvents(new BukkitChatListener(this), this);
pluginManager.registerEvents(new CapsHandler(this), this); pluginManager.registerEvents(new CapsHandler(this), this);
pluginManager.registerEvents(new CustomPlaceholderHandler(this), this); pluginManager.registerEvents(new CustomPlaceholderHandler(this), this);
pluginManager.registerEvents(filterHandler, this); pluginManager.registerEvents(this.filterHandler, this);
pluginManager.registerEvents(new IgnoredPlayerHandler(), this); pluginManager.registerEvents(new IgnoredPlayerHandler(), this);
pluginManager.registerEvents(new ItemLinkHandler(), this); pluginManager.registerEvents(new ItemLinkHandler(), this);
pluginManager.registerEvents(new LegacyFormatHandler(), this); pluginManager.registerEvents(new LegacyFormatHandler(), this);
@@ -191,93 +191,93 @@ public final class CarbonChat extends JavaPlugin {
public void reloadConfig() { public void reloadConfig() {
super.reloadConfig(); super.reloadConfig();
loadModConfig(); this.loadModConfig();
loadLanguage(); this.loadLanguage();
loadCommandsConfig(); this.loadCommandsConfig();
} }
public void reloadFilters() { public void reloadFilters() {
filterHandler.reloadFilters(); this.filterHandler.reloadFilters();
} }
private boolean bungeeEnabled = false; private boolean bungeeEnabled = false;
private void checkForBungee() { private void checkForBungee() {
try { try {
Class<?> spigotConfig = Class.forName("org.spigotmc.Spigotconfig"); final Class<?> spigotConfig = Class.forName("org.spigotmc.Spigotconfig");
Field bungee = spigotConfig.getField("bungee"); final Field bungee = spigotConfig.getField("bungee");
bungeeEnabled = bungee.getBoolean(null); this.bungeeEnabled = bungee.getBoolean(null);
} catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException ignored) { } catch (final ClassNotFoundException | NoSuchFieldException | IllegalAccessException ignored) {
} }
} }
public boolean isBungeeEnabled() { public boolean bungeeEnabled() {
return bungeeEnabled; return this.bungeeEnabled;
} }
private void loadModConfig() { private void loadModConfig() {
modConfig = YamlConfiguration.loadConfiguration(new File(getDataFolder(), "moderation.yml")); this.modConfig = YamlConfiguration.loadConfiguration(new File(this.getDataFolder(), "moderation.yml"));
} }
private void loadLanguage() { private void loadLanguage() {
languageConfig = YamlConfiguration.loadConfiguration(new File(getDataFolder(), "language.yml")); this.languageConfig = YamlConfiguration.loadConfiguration(new File(this.getDataFolder(), "language.yml"));
} }
private void loadCommandsConfig() { private void loadCommandsConfig() {
commandsConfig = YamlConfiguration.loadConfiguration(new File(getDataFolder(), "commands.yml")); this.commandsConfig = YamlConfiguration.loadConfiguration(new File(this.getDataFolder(), "commands.yml"));
} }
private void registerContexts() { private void registerContexts() {
getContextManager().register("distance", new DistanceContext()); this.contextManager().register("distance", new DistanceContext());
} }
@NonNull @NonNull
public YamlConfiguration getModConfig() { public YamlConfiguration moderationConfig() {
return modConfig; return this.modConfig;
} }
@NonNull @NonNull
public YamlConfiguration getCommandsConfig() { public YamlConfiguration commandsConfig() {
return commandsConfig; return this.commandsConfig;
} }
@NonNull @NonNull
public YamlConfiguration getLanguage() { public YamlConfiguration language() {
return languageConfig; return this.languageConfig;
} }
@NonNull @NonNull
public Permission getPermission() { public Permission permission() {
return permission; return this.permission;
} }
@NonNull @NonNull
public CommandManager getCommandManager() { public CommandManager commandManager() {
return commandManager; return this.commandManager;
} }
@NonNull @NonNull
public ChannelManager getChannelManager() { public ChannelManager channelManager() {
return channelManager; return this.channelManager;
} }
@NonNull @NonNull
public MessageManager getMessageManager() { public MessageManager messageManager() {
return messageManager; return this.messageManager;
} }
@NonNull @NonNull
public UserService getUserService() { public UserService userService() {
return userService; return this.userService;
} }
@NonNull @NonNull
public AdventureManager getAdventureManager() { public AdventureManager adventureManager() {
return adventureManager; return this.adventureManager;
} }
@NonNull @NonNull
public ContextManager getContextManager() { public ContextManager contextManager() {
return contextManager; return this.contextManager;
} }
} }
@@ -43,7 +43,7 @@ public class EconomyContext implements Listener {
if (!this.economy.has(player, requiredBal)) { if (!this.economy.has(player, requiredBal)) {
event.setCancelled(true); event.setCancelled(true);
event.user().sendMessage(this.carbonChat.getAdventureManager() event.user().sendMessage(this.carbonChat.adventureManager()
.processMessageWithPapi(player, event.channel().cannotUseMessage())); .processMessageWithPapi(player, event.channel().cannotUseMessage()));
} }
@@ -72,7 +72,7 @@ public class EconomyContext implements Listener {
if (!this.economy.has(player, cost)) { if (!this.economy.has(player, cost)) {
event.setCancelled(true); event.setCancelled(true);
event.user().sendMessage(this.carbonChat.getAdventureManager() event.user().sendMessage(this.carbonChat.adventureManager()
.processMessageWithPapi(player, event.channel().cannotUseMessage())); .processMessageWithPapi(player, event.channel().cannotUseMessage()));
return; return;
@@ -24,7 +24,7 @@ public final class TownyContext implements Listener {
public TownyContext(@NonNull final CarbonChat carbonChat) { public TownyContext(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
this.carbonChat.getContextManager().register(KEY, context -> { this.carbonChat.contextManager().register(KEY, context -> {
if ((context.value() instanceof Boolean) && ((Boolean) context.value())) { if ((context.value() instanceof Boolean) && ((Boolean) context.value())) {
return this.isInSameTown(context.sender(), context.target()); return this.isInSameTown(context.sender(), context.target());
} }
@@ -60,7 +60,7 @@ public final class TownyContext implements Listener {
@EventHandler @EventHandler
public void onResidentRemove(final TownRemoveResidentEvent event) { public void onResidentRemove(final TownRemoveResidentEvent event) {
final String name = event.getResident().getName(); final String name = event.getResident().getName();
final ChatUser user = this.carbonChat.getUserService().wrap(name); final ChatUser user = this.carbonChat.userService().wrap(name);
final Object town = user.selectedChannel().context(KEY); final Object town = user.selectedChannel().context(KEY);
if ((town instanceof Boolean) && ((Boolean) town)) { if ((town instanceof Boolean) && ((Boolean) town)) {
@@ -70,7 +70,7 @@ public final class TownyContext implements Listener {
@EventHandler @EventHandler
public void onPlayerJoin(final PlayerJoinEvent event) { public void onPlayerJoin(final PlayerJoinEvent event) {
final ChatUser user = this.carbonChat.getUserService().wrap(event.getPlayer()); final ChatUser user = this.carbonChat.userService().wrap(event.getPlayer());
final Object town = user.selectedChannel().context(KEY); final Object town = user.selectedChannel().context(KEY);
if ((town instanceof Boolean) && ((Boolean) town) && !this.isInTown(user)) { if ((town instanceof Boolean) && ((Boolean) town) && !this.isInTown(user)) {
@@ -25,7 +25,7 @@ public final class WorldGuardContext implements Listener {
private static final String KEY = "worldguard-region"; private static final String KEY = "worldguard-region";
public WorldGuardContext(@NonNull final CarbonChat carbonChat) { public WorldGuardContext(@NonNull final CarbonChat carbonChat) {
carbonChat.getContextManager().register(KEY, context -> { carbonChat.contextManager().register(KEY, context -> {
return this.testContext(context.sender(), context.target(), context.value()); return this.testContext(context.sender(), context.target(), context.value());
}); });
} }
@@ -19,7 +19,7 @@ public final class mcMMOContext implements Listener {
public mcMMOContext(@NonNull final CarbonChat carbonChat) { public mcMMOContext(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
this.carbonChat.getContextManager().register("mcmmo-party", context -> { this.carbonChat.contextManager().register("mcmmo-party", context -> {
if ((context.value() instanceof Boolean) && ((Boolean) context.value())) { if ((context.value() instanceof Boolean) && ((Boolean) context.value())) {
return this.isInSameParty(context.sender(), context.target()); return this.isInSameParty(context.sender(), context.target());
} }
@@ -60,7 +60,7 @@ public final class mcMMOContext implements Listener {
return; return;
} }
final ChatUser user = this.carbonChat.getUserService().wrap(event.getPlayer()); final ChatUser user = this.carbonChat.userService().wrap(event.getPlayer());
final Object party = user.selectedChannel().context("mcmmo-party"); final Object party = user.selectedChannel().context("mcmmo-party");
if ((party instanceof Boolean) && ((Boolean) party)) { if ((party instanceof Boolean) && ((Boolean) party)) {
@@ -70,7 +70,7 @@ public final class mcMMOContext implements Listener {
@EventHandler @EventHandler
public void onPlayerJoin(final PlayerJoinEvent event) { public void onPlayerJoin(final PlayerJoinEvent event) {
final ChatUser user = this.carbonChat.getUserService().wrap(event.getPlayer()); final ChatUser user = this.carbonChat.userService().wrap(event.getPlayer());
final Object party = user.selectedChannel().context("mcmmo-party"); final Object party = user.selectedChannel().context("mcmmo-party");
if ((party instanceof Boolean) && ((Boolean) party) && !this.isInParty(user)) { if ((party instanceof Boolean) && ((Boolean) party) && !this.isInParty(user)) {
@@ -45,29 +45,29 @@ public class CarbonChatChannel extends ChatChannel {
} }
@NonNull @NonNull
public CarbonChat getCarbonChat() { public CarbonChat carbonChat() {
return carbonChat; return this.carbonChat;
} }
@Override @Override
public boolean testContext(@NonNull final ChatUser sender, @NonNull final ChatUser target) { public boolean testContext(@NonNull final ChatUser sender, @NonNull final ChatUser target) {
return this.carbonChat.getContextManager().testContext(sender, target, this); return this.carbonChat.contextManager().testContext(sender, target, this);
} }
@Override @Override
public boolean canPlayerUse(@NonNull final ChatUser user) { public boolean canPlayerUse(@NonNull final ChatUser user) {
return user.player().hasPermission("carbonchat.channels." + name() + ".use"); return user.player().hasPermission("carbonchat.channels." + this.name() + ".use");
} }
@Override @Override
@NonNull @NonNull
public List<@NonNull ChatUser> audiences() { public List<@NonNull ChatUser> audiences() {
List<ChatUser> audience = new ArrayList<>(); final List<ChatUser> audience = new ArrayList<>();
for (Player player : Bukkit.getOnlinePlayers()) { for (final Player player : Bukkit.getOnlinePlayers()) {
ChatUser playerUser = this.carbonChat.getUserService().wrap(player); final ChatUser playerUser = this.carbonChat.userService().wrap(player);
if (canPlayerSee(playerUser, true)) { if (this.canPlayerSee(playerUser, true)) {
audience.add(playerUser); audience.add(playerUser);
} }
} }
@@ -75,17 +75,17 @@ public class CarbonChatChannel extends ChatChannel {
return audience; return audience;
} }
private void updateUserNickname(@NonNull ChatUser user) { private void updateUserNickname(@NonNull final ChatUser user) {
if (user.online()) { if (user.online()) {
String nickname = user.nickname(); String nickname = user.nickname();
if (nickname != null) { if (nickname != null) {
Component component = this.carbonChat.getAdventureManager().processMessage(nickname); final Component component = this.carbonChat.adventureManager().processMessage(nickname);
nickname = CarbonChat.LEGACY.serialize(component); nickname = CarbonChat.LEGACY.serialize(component);
user.player().setDisplayName(nickname); user.player().setDisplayName(nickname);
if (carbonChat.getConfig().getBoolean("nicknames-set-tab-name")) { if (this.carbonChat.getConfig().getBoolean("nicknames-set-tab-name")) {
user.player().setPlayerListName(nickname); user.player().setPlayerListName(nickname);
} }
} }
@@ -94,14 +94,14 @@ public class CarbonChatChannel extends ChatChannel {
@Override @Override
@NonNull @NonNull
public Component sendMessage(@NonNull ChatUser user, @NonNull Collection<@NonNull ChatUser> recipients, @NonNull String message, boolean fromRemote) { public Component sendMessage(@NonNull final ChatUser user, @NonNull final Collection<@NonNull ChatUser> recipients, @NonNull final String message, final boolean fromRemote) {
updateUserNickname(user); this.updateUserNickname(user);
// Get player's formatting // Get player's formatting
String messageFormat = getFormat(user); final String messageFormat = this.format(user);
// Call custom chat event // Call custom chat event
PreChatFormatEvent preFormatEvent = new PreChatFormatEvent(user, this, messageFormat, message); final PreChatFormatEvent preFormatEvent = new PreChatFormatEvent(user, this, messageFormat, message);
Bukkit.getPluginManager().callEvent(preFormatEvent); Bukkit.getPluginManager().callEvent(preFormatEvent);
// Return if cancelled or message is emptied // Return if cancelled or message is emptied
@@ -110,7 +110,7 @@ public class CarbonChatChannel extends ChatChannel {
return TextComponent.empty(); return TextComponent.empty();
} }
String displayName; final String displayName;
if (user.nickname() != null) { if (user.nickname() != null) {
displayName = user.nickname(); displayName = user.nickname();
@@ -123,9 +123,9 @@ public class CarbonChatChannel extends ChatChannel {
} }
// Iterate through players who should receive messages in this channel // Iterate through players who should receive messages in this channel
for (ChatUser target : recipients) { for (final ChatUser target : recipients) {
// Call second format event. Used for relational stuff (placeholders etc) // Call second format event. Used for relational stuff (placeholders etc)
ChatFormatEvent formatEvent = new ChatFormatEvent(user, target, this, preFormatEvent.format(), preFormatEvent.message()); final ChatFormatEvent formatEvent = new ChatFormatEvent(user, target, this, preFormatEvent.format(), preFormatEvent.message());
Bukkit.getPluginManager().callEvent(formatEvent); Bukkit.getPluginManager().callEvent(formatEvent);
// Again, return if cancelled or message is emptied // Again, return if cancelled or message is emptied
@@ -133,9 +133,9 @@ public class CarbonChatChannel extends ChatChannel {
continue; continue;
} }
TextColor targetColor = channelColor(target); final TextColor targetColor = this.channelColor(target);
TextComponent formatComponent = (TextComponent) this.carbonChat.getAdventureManager().processMessage(formatEvent.format(), TextComponent formatComponent = (TextComponent) this.carbonChat.adventureManager().processMessage(formatEvent.format(),
"br", "\n", "br", "\n",
"displayname", displayName, "displayname", displayName,
"color", "<" + targetColor.asHexString() + ">", "color", "<" + targetColor.asHexString() + ">",
@@ -143,14 +143,14 @@ public class CarbonChatChannel extends ChatChannel {
"server", this.carbonChat.getConfig().getString("server-name", "Server"), "server", this.carbonChat.getConfig().getString("server-name", "Server"),
"message", formatEvent.message()); "message", formatEvent.message());
if (isUserSpying(user, target)) { if (this.isUserSpying(user, target)) {
String prefix = processPlaceholders(user, this.carbonChat.getConfig().getString("spy-prefix")); final String prefix = this.processPlaceholders(user, this.carbonChat.getConfig().getString("spy-prefix"));
formatComponent = (TextComponent) MiniMessage.get().parse(prefix, "color", formatComponent = (TextComponent) MiniMessage.get().parse(prefix, "color",
targetColor.asHexString()).append(formatComponent); targetColor.asHexString()).append(formatComponent);
} }
ChatComponentEvent newEvent = new ChatComponentEvent(user, target, this, formatComponent, final ChatComponentEvent newEvent = new ChatComponentEvent(user, target, this, formatComponent,
formatEvent.message()); formatEvent.message());
Bukkit.getPluginManager().callEvent(newEvent); Bukkit.getPluginManager().callEvent(newEvent);
@@ -158,14 +158,14 @@ public class CarbonChatChannel extends ChatChannel {
target.sendMessage(newEvent.component()); target.sendMessage(newEvent.component());
} }
ChatFormatEvent consoleFormatEvent = new ChatFormatEvent(user, null, this, preFormatEvent.format(), final ChatFormatEvent consoleFormatEvent = new ChatFormatEvent(user, null, this, preFormatEvent.format(),
preFormatEvent.message()); preFormatEvent.message());
Bukkit.getPluginManager().callEvent(consoleFormatEvent); Bukkit.getPluginManager().callEvent(consoleFormatEvent);
TextColor targetColor = channelColor(user); final TextColor targetColor = this.channelColor(user);
TextComponent consoleFormat = (TextComponent) this.carbonChat.getAdventureManager().processMessage(consoleFormatEvent.format(), final TextComponent consoleFormat = (TextComponent) this.carbonChat.adventureManager().processMessage(consoleFormatEvent.format(),
"br", "\n", "br", "\n",
"displayname", displayName, "displayname", displayName,
"color", "<" + targetColor.asHexString() + ">", "color", "<" + targetColor.asHexString() + ">",
@@ -173,7 +173,7 @@ public class CarbonChatChannel extends ChatChannel {
"server", this.carbonChat.getConfig().getString("server-name", "Server"), "server", this.carbonChat.getConfig().getString("server-name", "Server"),
"message", consoleFormatEvent.message()); "message", consoleFormatEvent.message());
ChatComponentEvent consoleEvent = new ChatComponentEvent(user, null, this, consoleFormat, final ChatComponentEvent consoleEvent = new ChatComponentEvent(user, null, this, consoleFormat,
consoleFormatEvent.message()); consoleFormatEvent.message());
Bukkit.getPluginManager().callEvent(consoleEvent); Bukkit.getPluginManager().callEvent(consoleEvent);
@@ -181,8 +181,8 @@ public class CarbonChatChannel extends ChatChannel {
// Route message to bungee / discord (if message originates from this server) // Route message to bungee / discord (if message originates from this server)
// Use instanceof and not isOnline, if this message originates from another then the instanceof will // Use instanceof and not isOnline, if this message originates from another then the instanceof will
// fail, but isOnline may succeed if the player is online on both servers (somehow). // fail, but isOnline may succeed if the player is online on both servers (somehow).
if (user.online() && !fromRemote && (bungee() || crossServer())) { if (user.online() && !fromRemote && (this.bungee() || this.crossServer())) {
sendMessageToBungee(user.player(), consoleEvent.component()); this.sendMessageToBungee(user.player(), consoleEvent.component());
} }
return consoleEvent.component(); return consoleEvent.component();
@@ -190,15 +190,15 @@ public class CarbonChatChannel extends ChatChannel {
@Override @Override
@NonNull @NonNull
public Component sendMessage(@NonNull ChatUser user, @NonNull String message, boolean fromRemote) { public Component sendMessage(@NonNull final ChatUser user, @NonNull final String message, final boolean fromRemote) {
return this.sendMessage(user, this.audiences(), message, fromRemote); return this.sendMessage(user, this.audiences(), message, fromRemote);
} }
@Nullable @Nullable
public String getFormat(@NonNull ChatUser user) { public String format(@NonNull final ChatUser user) {
for (String group : this.groupOverrides()) { for (final String group : this.groupOverrides()) {
if (userHasGroup(user, group)) { if (this.userHasGroup(user, group)) {
String format = format(group); final String format = this.format(group);
if (format != null) { if (format != null) {
return format; return format;
@@ -206,20 +206,20 @@ public class CarbonChatChannel extends ChatChannel {
} }
} }
if (primaryGroupOnly()) { if (this.primaryGroupOnly()) {
return getPrimaryGroupFormat(user); return this.primaryGroupFormat(user);
} else { } else {
return getFirstFoundUserFormat(user); return this.firstFoundUserFormat(user);
} }
} }
private boolean userHasGroup(@NonNull ChatUser user, @NonNull String group) { private boolean userHasGroup(@NonNull final ChatUser user, @NonNull final String group) {
if (user.online()) { if (user.online()) {
if (carbonChat.getPermission().playerInGroup(user.player(), group)) { if (this.carbonChat.permission().playerInGroup(user.player(), group)) {
return true; return true;
} }
} else { } else {
if (carbonChat.getPermission().playerInGroup(null, user.offlinePlayer(), group)) { if (this.carbonChat.permission().playerInGroup(null, user.offlinePlayer(), group)) {
return true; return true;
} }
} }
@@ -232,58 +232,58 @@ public class CarbonChatChannel extends ChatChannel {
} }
@Nullable @Nullable
private String getFirstFoundUserFormat(@NonNull ChatUser user) { private String firstFoundUserFormat(@NonNull final ChatUser user) {
String[] playerGroups; final String[] playerGroups;
if (user.online()) { if (user.online()) {
playerGroups = this.carbonChat.getPermission().getPlayerGroups(user.player()); playerGroups = this.carbonChat.permission().getPlayerGroups(user.player());
} else { } else {
playerGroups = this.carbonChat.getPermission().getPlayerGroups(null, user.offlinePlayer()); playerGroups = this.carbonChat.permission().getPlayerGroups(null, user.offlinePlayer());
} }
for (String group : playerGroups) { for (final String group : playerGroups) {
String groupFormat = format(group); final String groupFormat = this.format(group);
if (groupFormat != null) { if (groupFormat != null) {
return groupFormat; return groupFormat;
} }
} }
return getDefaultFormat(); return this.defaultFormat();
} }
@Nullable @Nullable
private String getPrimaryGroupFormat(@NonNull ChatUser user) { private String primaryGroupFormat(@NonNull final ChatUser user) {
String primaryGroup; final String primaryGroup;
if (user.online()) { if (user.online()) {
primaryGroup = this.carbonChat.getPermission().getPrimaryGroup(user.player()); primaryGroup = this.carbonChat.permission().getPrimaryGroup(user.player());
} else { } else {
primaryGroup = this.carbonChat.getPermission().getPrimaryGroup(null, user.offlinePlayer()); primaryGroup = this.carbonChat.permission().getPrimaryGroup(null, user.offlinePlayer());
} }
String primaryGroupFormat = format(primaryGroup); final String primaryGroupFormat = this.format(primaryGroup);
if (primaryGroupFormat != null) { if (primaryGroupFormat != null) {
return primaryGroupFormat; return primaryGroupFormat;
} }
return getDefaultFormat(); return this.defaultFormat();
} }
@Nullable @Nullable
private String getDefaultFormat() { private String defaultFormat() {
return format(getDefaultFormatName()); return this.format(this.defaultFormatName());
} }
@Override @Override
@Nullable @Nullable
public String format(@NonNull String group) { public String format(@NonNull final String group) {
return getString("formats." + group); return this.getString("formats." + group);
} }
private boolean isUserSpying(@NonNull ChatUser sender, @NonNull ChatUser target) { private boolean isUserSpying(@NonNull final ChatUser sender, @NonNull final ChatUser target) {
if (!canPlayerSee(sender, target, false)) { if (!this.canPlayerSee(sender, target, false)) {
return target.channelSettings(this).spying(); return target.channelSettings(this).spying();
} }
@@ -291,50 +291,50 @@ public class CarbonChatChannel extends ChatChannel {
} }
@Override @Override
public void sendComponent(@NonNull ChatUser player, @NonNull Component component) { public void sendComponent(@NonNull final ChatUser player, @NonNull final Component component) {
for (ChatUser user : audiences()) { for (final ChatUser user : this.audiences()) {
if (!user.ignoringUser(player)) { if (!user.ignoringUser(player)) {
user.sendMessage(component); user.sendMessage(component);
} }
} }
} }
public void sendMessageToBungee(@NonNull Player player, @NonNull Component component) { public void sendMessageToBungee(@NonNull final Player player, @NonNull final Component component) {
this.carbonChat.getMessageManager().sendMessage("channel-component", player.getUniqueId(), (byteArray) -> { this.carbonChat.messageManager().sendMessage("channel-component", player.getUniqueId(), byteArray -> {
byteArray.writeUTF(this.key()); byteArray.writeUTF(this.key());
byteArray.writeUTF(carbonChat.getAdventureManager().audiences().gsonSerializer().serialize(component)); byteArray.writeUTF(this.carbonChat.adventureManager().audiences().gsonSerializer().serialize(component));
}); });
} }
@Override @Override
public boolean canPlayerSee(@NonNull ChatUser target, boolean checkSpying) { public boolean canPlayerSee(@NonNull final ChatUser target, final boolean checkSpying) {
Player targetPlayer = target.player(); final Player targetPlayer = target.player();
if (checkSpying && targetPlayer.hasPermission("carbonchat.spy." + name())) { if (checkSpying && targetPlayer.hasPermission("carbonchat.spy." + this.name())) {
if (target.channelSettings(this).spying()) { if (target.channelSettings(this).spying()) {
return true; return true;
} }
} }
if (!targetPlayer.hasPermission("carbonchat.channels." + name() + ".see")) { if (!targetPlayer.hasPermission("carbonchat.channels." + this.name() + ".see")) {
return false; return false;
} }
if (ignorable()) { if (this.ignorable()) {
return !target.channelSettings(this).ignored(); return !target.channelSettings(this).ignored();
} }
return true; return true;
} }
public boolean canPlayerSee(@NonNull ChatUser sender, @NonNull ChatUser target, boolean checkSpying) { public boolean canPlayerSee(@NonNull final ChatUser sender, @NonNull final ChatUser target, final boolean checkSpying) {
Player targetPlayer = target.player(); final Player targetPlayer = target.player();
if (!canPlayerSee(target, checkSpying)) { if (!this.canPlayerSee(target, checkSpying)) {
return false; return false;
} }
if (ignorable()) { if (this.ignorable()) {
return !target.ignoringUser(sender) || targetPlayer.hasPermission("carbonchat.ignore.exempt"); return !target.ignoringUser(sender) || targetPlayer.hasPermission("carbonchat.ignore.exempt");
} }
@@ -343,17 +343,17 @@ public class CarbonChatChannel extends ChatChannel {
@Override @Override
@Nullable @Nullable
public TextColor channelColor(@NonNull ChatUser user) { public TextColor channelColor(@NonNull final ChatUser user) {
TextColor userColor = user.channelSettings(this).color(); final TextColor userColor = user.channelSettings(this).color();
if (userColor != null) { if (userColor != null) {
System.out.println("user color found!"); System.out.println("user color found!");
return userColor; return userColor;
} }
String input = getString("color"); final String input = this.getString("color");
TextColor color = CarbonUtils.parseColor(user, input); final TextColor color = CarbonUtils.parseColor(user, input);
if (color == null && this.carbonChat.getConfig().getBoolean("show-tips")) { if (color == null && this.carbonChat.getConfig().getBoolean("show-tips")) {
this.carbonChat.getLogger().warning("Tip: Channel color found (" + color + ") is invalid!"); this.carbonChat.getLogger().warning("Tip: Channel color found (" + color + ") is invalid!");
@@ -366,14 +366,14 @@ public class CarbonChatChannel extends ChatChannel {
} }
@Nullable @Nullable
private String getDefaultFormatName() { private String defaultFormatName() {
return getString("default-group"); return this.getString("default-group");
} }
@Override @Override
public boolean isDefault() { public boolean isDefault() {
if (config != null && config.contains("default")) { if (this.config != null && this.config.contains("default")) {
return config.getBoolean("default"); return this.config.getBoolean("default");
} }
return false; return false;
@@ -381,48 +381,48 @@ public class CarbonChatChannel extends ChatChannel {
@Override @Override
public boolean ignorable() { public boolean ignorable() {
return getBoolean("ignorable"); return this.getBoolean("ignorable");
} }
@Override @Override
@Deprecated @Deprecated
public boolean bungee() { public boolean bungee() {
return getBoolean("should-bungee"); return this.getBoolean("should-bungee");
} }
@Override @Override
public boolean crossServer() { public boolean crossServer() {
return getBoolean("is-cross-server"); return this.getBoolean("is-cross-server");
} }
@Override @Override
public boolean honorsRecipientList() { public boolean honorsRecipientList() {
return getBoolean("honors-recipient-list"); return this.getBoolean("honors-recipient-list");
} }
@Override @Override
public boolean permissionGroupMatching() { public boolean permissionGroupMatching() {
return getBoolean("permission-group-matching"); return this.getBoolean("permission-group-matching");
} }
@Override @Override
@NonNull @NonNull
public List<@NonNull String> groupOverrides() { public List<@NonNull String> groupOverrides() {
return getStringList("group-overrides"); return this.getStringList("group-overrides");
} }
@Override @Override
@NonNull @NonNull
public String name() { public String name() {
String name = getString("name"); final String name = this.getString("name");
return name == null ? key : name; return name == null ? this.key : name;
} }
@Override @Override
@Nullable @Nullable
public String messagePrefix() { public String messagePrefix() {
if (config != null && config.contains("message-prefix")) { if (this.config != null && this.config.contains("message-prefix")) {
return config.getString("message-prefix"); return this.config.getString("message-prefix");
} }
return null; return null;
@@ -431,68 +431,73 @@ public class CarbonChatChannel extends ChatChannel {
@Override @Override
@Nullable @Nullable
public String switchMessage() { public String switchMessage() {
return getString("switch-message"); return this.getString("switch-message");
} }
@Override @Override
@Nullable @Nullable
public String switchOtherMessage() { public String switchOtherMessage() {
return getString("switch-other-message"); return this.getString("switch-other-message");
} }
@Override @Override
@Nullable @Nullable
public String switchFailureMessage() { public String switchFailureMessage() {
return getString("switch-failure-message"); return this.getString("switch-failure-message");
} }
@Override @Override
@Nullable @Nullable
public String cannotIgnoreMessage() { public String cannotIgnoreMessage() {
return getString("cannot-ignore-message"); return this.getString("cannot-ignore-message");
} }
@Override @Override
@Nullable @Nullable
public String toggleOffMessage() { public String toggleOffMessage() {
return getString("toggle-off-message"); return this.getString("toggle-off-message");
} }
@Override @Override
@Nullable @Nullable
public String toggleOnMessage() { public String toggleOnMessage() {
return getString("toggle-on-message"); return this.getString("toggle-on-message");
} }
@Override @Override
@Nullable @Nullable
public String toggleOtherOnMessage() { public String toggleOtherOnMessage() {
return getString("toggle-other-on"); return this.getString("toggle-other-on");
} }
@Override @Override
@Nullable @Nullable
public String toggleOtherOffMessage() { public String toggleOtherOffMessage() {
return getString("toggle-other-off"); return this.getString("toggle-other-off");
} }
@Override @Override
@Nullable @Nullable
public String cannotUseMessage() { public String cannotUseMessage() {
return getString("cannot-use-channel"); return this.getString("cannot-use-channel");
} }
@Override @Override
public boolean primaryGroupOnly() { public boolean primaryGroupOnly() {
return getBoolean("primary-group-only"); return this.getBoolean("primary-group-only");
}
@Override
public boolean shouldCancelChatEvent() {
return this.getBoolean("cancel-message-event");
} }
@Override @Override
@NonNull @NonNull
public List<@NonNull Pattern> itemLinkPatterns() { public List<@NonNull Pattern> itemLinkPatterns() {
ArrayList<Pattern> itemPatterns = new ArrayList<>(); final ArrayList<Pattern> itemPatterns = new ArrayList<>();
for (String entry : this.carbonChat.getConfig().getStringList("item-link-placeholders")) { for (final String entry : this.carbonChat.getConfig().getStringList("item-link-placeholders")) {
itemPatterns.add(Pattern.compile(Pattern.quote(entry))); itemPatterns.add(Pattern.compile(Pattern.quote(entry)));
} }
@@ -501,17 +506,17 @@ public class CarbonChatChannel extends ChatChannel {
@Override @Override
@Nullable @Nullable
public Object context(@NonNull String key) { public Object context(@NonNull final String key) {
ConfigurationSection section = config == null ? null : config.getConfigurationSection("contexts"); final ConfigurationSection section = this.config == null ? null : this.config.getConfigurationSection("contexts");
if (section == null) { if (section == null) {
ConfigurationSection defaultSection = this.carbonChat.getConfig().getConfigurationSection("default"); final ConfigurationSection defaultSection = this.carbonChat.getConfig().getConfigurationSection("default");
if (defaultSection == null) { if (defaultSection == null) {
return null; return null;
} }
ConfigurationSection defaultContexts = defaultSection.getConfigurationSection("contexts"); final ConfigurationSection defaultContexts = defaultSection.getConfigurationSection("contexts");
if (defaultContexts == null) { if (defaultContexts == null) {
return null; return null;
@@ -524,12 +529,13 @@ public class CarbonChatChannel extends ChatChannel {
} }
@Nullable @Nullable
private String getString(@NonNull String key) { @SuppressWarnings("checkstyle:MethodName")
if (config != null && config.contains(key)) { private String getString(@NonNull final String key) {
return config.getString(key); if (this.config != null && this.config.contains(key)) {
return this.config.getString(key);
} }
ConfigurationSection defaultSection = this.carbonChat.getConfig().getConfigurationSection("default"); final ConfigurationSection defaultSection = this.carbonChat.getConfig().getConfigurationSection("default");
if (defaultSection != null && defaultSection.contains(key)) { if (defaultSection != null && defaultSection.contains(key)) {
return defaultSection.getString(key); return defaultSection.getString(key);
@@ -539,12 +545,13 @@ public class CarbonChatChannel extends ChatChannel {
} }
@NonNull @NonNull
private List<@NonNull String> getStringList(@NonNull String key) { @SuppressWarnings("checkstyle:MethodName")
if (config != null && config.contains(key)) { private List<@NonNull String> getStringList(@NonNull final String key) {
return config.getStringList(key); if (this.config != null && this.config.contains(key)) {
return this.config.getStringList(key);
} }
ConfigurationSection defaultSection = this.carbonChat.getConfig().getConfigurationSection("default"); final ConfigurationSection defaultSection = this.carbonChat.getConfig().getConfigurationSection("default");
if (defaultSection != null && defaultSection.contains(key)) { if (defaultSection != null && defaultSection.contains(key)) {
return defaultSection.getStringList(key); return defaultSection.getStringList(key);
@@ -553,12 +560,13 @@ public class CarbonChatChannel extends ChatChannel {
return Collections.emptyList(); return Collections.emptyList();
} }
private boolean getBoolean(@NonNull String key) { @SuppressWarnings("checkstyle:MethodName")
if (config != null && config.contains(key)) { private boolean getBoolean(@NonNull final String key) {
return config.getBoolean(key); if (this.config != null && this.config.contains(key)) {
return this.config.getBoolean(key);
} }
ConfigurationSection defaultSection = this.carbonChat.getConfig().getConfigurationSection("default"); final ConfigurationSection defaultSection = this.carbonChat.getConfig().getConfigurationSection("default");
if (defaultSection != null && defaultSection.contains(key)) { if (defaultSection != null && defaultSection.contains(key)) {
return defaultSection.getBoolean(key); return defaultSection.getBoolean(key);
@@ -567,12 +575,13 @@ public class CarbonChatChannel extends ChatChannel {
return false; return false;
} }
private double getDouble(@NonNull String key) { @SuppressWarnings("checkstyle:MethodName")
if (config != null && config.contains(key)) { private double getDouble(@NonNull final String key) {
return config.getDouble(key); if (this.config != null && this.config.contains(key)) {
return this.config.getDouble(key);
} }
ConfigurationSection defaultSection = this.carbonChat.getConfig().getConfigurationSection("default"); final ConfigurationSection defaultSection = this.carbonChat.getConfig().getConfigurationSection("default");
if (defaultSection != null && defaultSection.contains(key)) { if (defaultSection != null && defaultSection.contains(key)) {
return defaultSection.getDouble(key); return defaultSection.getDouble(key);
@@ -584,23 +593,18 @@ public class CarbonChatChannel extends ChatChannel {
@Override @Override
@NonNull @NonNull
public String key() { public String key() {
return key; return this.key;
} }
@Override @Override
@Nullable @Nullable
public String aliases() { public String aliases() {
String aliases = getString("aliases"); final String aliases = this.getString("aliases");
if (aliases == null) { if (aliases == null) {
return key(); return this.key();
} }
return aliases; return aliases;
} }
@Override
public boolean shouldCancelChatEvent() {
return getBoolean("cancel-message-event");
}
} }
@@ -49,10 +49,10 @@ public class AliasedChannelCommand {
} }
private void channel(@NonNull final Player player, @NonNull final Object @NonNull [] args) { private void channel(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
final ChatUser user = this.carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
if (user.channelSettings(this.chatChannel()).ignored()) { if (user.channelSettings(this.chatChannel()).ignored()) {
user.sendMessage(this.carbonChat.getAdventureManager().processMessageWithPapi(player, this.chatChannel().cannotUseMessage(), user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player, this.chatChannel().cannotUseMessage(),
"br", "\n", "br", "\n",
"color", "<" + this.chatChannel().channelColor(user).toString() + ">", "color", "<" + this.chatChannel().channelColor(user).toString() + ">",
"channel", this.chatChannel().name())); "channel", this.chatChannel().name()));
@@ -62,19 +62,19 @@ public class AliasedChannelCommand {
user.selectedChannel(this.chatChannel()); user.selectedChannel(this.chatChannel());
user.sendMessage(this.carbonChat.getAdventureManager().processMessageWithPapi(player, this.chatChannel().switchMessage(), user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player, this.chatChannel().switchMessage(),
"br", "\n", "br", "\n",
"color", "<" + this.chatChannel().channelColor(user).toString() + ">", "color", "<" + this.chatChannel().channelColor(user).toString() + ">",
"channel", this.chatChannel().name())); "channel", this.chatChannel().name()));
} }
private void sendMessage(@NonNull final Player player, @NonNull final Object @NonNull [] args) { private void sendMessage(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
final ChatUser user = this.carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
final String message = (String) args[0]; final String message = (String) args[0];
final Component component = this.chatChannel().sendMessage(user, message, false); final Component component = this.chatChannel().sendMessage(user, message, false);
this.carbonChat.getAdventureManager().audiences().console().sendMessage(component); this.carbonChat.adventureManager().audiences().console().sendMessage(component);
} }
@NonNull @NonNull
@@ -53,11 +53,11 @@ public class ChannelCommand {
} }
private void channel(@NonNull final Player player, @NonNull final Object @NonNull [] args) { private void channel(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
final ChatUser user = this.carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
final ChatChannel channel = (ChatChannel) args[0]; final ChatChannel channel = (ChatChannel) args[0];
if (user.channelSettings(channel).ignored()) { if (user.channelSettings(channel).ignored()) {
user.sendMessage(this.carbonChat.getAdventureManager().processMessageWithPapi(player, channel.cannotUseMessage(), user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player, channel.cannotUseMessage(),
"br", "\n", "br", "\n",
"color", "<" + channel.channelColor(user).toString() + ">", "color", "<" + channel.channelColor(user).toString() + ">",
"channel", channel.name())); "channel", channel.name()));
@@ -67,20 +67,20 @@ public class ChannelCommand {
user.selectedChannel(channel); user.selectedChannel(channel);
user.sendMessage(this.carbonChat.getAdventureManager().processMessageWithPapi(player, channel.switchMessage(), user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player, channel.switchMessage(),
"br", "\n", "br", "\n",
"color", "<" + channel.channelColor(user).toString() + ">", "color", "<" + channel.channelColor(user).toString() + ">",
"channel", channel.name())); "channel", channel.name()));
} }
private void sendMessage(@NonNull final Player player, @NonNull final Object @NonNull [] args) { private void sendMessage(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
final ChatUser user = this.carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
final ChatChannel channel = (ChatChannel) args[0]; final ChatChannel channel = (ChatChannel) args[0];
final String message = (String) args[1]; final String message = (String) args[1];
final Component component = channel.sendMessage(user, message, false); final Component component = channel.sendMessage(user, message, false);
this.carbonChat.getAdventureManager().audiences().console().sendMessage(component); this.carbonChat.adventureManager().audiences().console().sendMessage(component);
} }
} }
@@ -57,23 +57,23 @@ public class ChannelListCommand {
} }
public void executeSelf(@NonNull final Player player, @NonNull final Object @NonNull [] args) { public void executeSelf(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
final Iterator<ChatChannel> allChannels = this.carbonChat.getChannelManager().registry().values().iterator(); final Iterator<ChatChannel> allChannels = this.carbonChat.channelManager().registry().values().iterator();
final ChatUser user = this.carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
this.listAndSend(player, user, allChannels); this.listAndSend(player, user, allChannels);
} }
public void executeOther(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) { public void executeOther(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) {
final Audience cmdSender = this.carbonChat.getAdventureManager().audiences().audience(sender); final Audience cmdSender = this.carbonChat.adventureManager().audiences().audience(sender);
final ChatUser user = (ChatUser) args[0]; final ChatUser user = (ChatUser) args[0];
if (!user.online()) { if (!user.online()) {
final String mustBeOnline = this.carbonChat.getLanguage().getString("user-must-be-online"); final String mustBeOnline = this.carbonChat.language().getString("user-must-be-online");
cmdSender.sendMessage(this.carbonChat.getAdventureManager().processMessage(mustBeOnline, "br", "\n", "player", user.offlinePlayer().getName())); cmdSender.sendMessage(this.carbonChat.adventureManager().processMessage(mustBeOnline, "br", "\n", "player", user.offlinePlayer().getName()));
return; return;
} }
final Iterator<ChatChannel> allChannels = this.carbonChat.getChannelManager().registry().values().iterator(); final Iterator<ChatChannel> allChannels = this.carbonChat.channelManager().registry().values().iterator();
this.listAndSend(sender, user, allChannels); this.listAndSend(sender, user, allChannels);
} }
@@ -98,11 +98,11 @@ public class ChannelListCommand {
this.makeList(visibleChannels, availableList); this.makeList(visibleChannels, availableList);
final String availableFormat = this.carbonChat.getLanguage().getString("available-channels-list"); final String availableFormat = this.carbonChat.language().getString("available-channels-list");
Component availableComponent = this.carbonChat.getAdventureManager().processMessage(availableFormat, "br", "\n"); Component availableComponent = this.carbonChat.adventureManager().processMessage(availableFormat, "br", "\n");
availableComponent = availableComponent.replaceFirstText(Pattern.compile(Pattern.quote("<list>")), ac -> availableList); availableComponent = availableComponent.replaceFirstText(Pattern.compile(Pattern.quote("<list>")), ac -> availableList);
final Audience audience = this.carbonChat.getAdventureManager().audiences().audience(sender); final Audience audience = this.carbonChat.adventureManager().audiences().audience(sender);
audience.sendMessage(availableComponent); audience.sendMessage(availableComponent);
@@ -112,8 +112,8 @@ public class ChannelListCommand {
this.makeList(invisibleChannels, unavailableList); this.makeList(invisibleChannels, unavailableList);
final String unavailableFormat = this.carbonChat.getLanguage().getString("unavailable-channels-list"); final String unavailableFormat = this.carbonChat.language().getString("unavailable-channels-list");
Component unavailableComponent = this.carbonChat.getAdventureManager().processMessage(unavailableFormat, "br", "\n"); Component unavailableComponent = this.carbonChat.adventureManager().processMessage(unavailableFormat, "br", "\n");
unavailableComponent = unavailableComponent.replaceFirstText(Pattern.compile(Pattern.quote("<list>")), uac -> unavailableList); unavailableComponent = unavailableComponent.replaceFirstText(Pattern.compile(Pattern.quote("<list>")), uac -> unavailableList);
audience.sendMessage(unavailableComponent); audience.sendMessage(unavailableComponent);
@@ -121,7 +121,7 @@ public class ChannelListCommand {
} }
private void makeList(@NonNull final Iterator<@NonNull ChatChannel> iterator, final TextComponent.@NonNull Builder list) { private void makeList(@NonNull final Iterator<@NonNull ChatChannel> iterator, final TextComponent.@NonNull Builder list) {
final String listSeparator = this.carbonChat.getLanguage().getString("channel-list-separator", ", "); final String listSeparator = this.carbonChat.language().getString("channel-list-separator", ", ");
// TODO: Larry, why did you double assign the listSeparatorComponent? // TODO: Larry, why did you double assign the listSeparatorComponent?
final Component listSeparatorComponent = TextComponent.of(listSeparator); final Component listSeparatorComponent = TextComponent.of(listSeparator);
@@ -34,10 +34,10 @@ public class ChatReloadCommand {
this.carbonChat.reloadConfig(); this.carbonChat.reloadConfig();
this.carbonChat.reloadFilters(); this.carbonChat.reloadFilters();
final Component message = this.carbonChat.getAdventureManager() final Component message = this.carbonChat.adventureManager()
.processMessage(this.carbonChat.getLanguage().getString("reloaded"), "br", "\n"); .processMessage(this.carbonChat.language().getString("reloaded"), "br", "\n");
this.carbonChat.getAdventureManager().audiences().audience(sender).sendMessage(message); this.carbonChat.adventureManager().audiences().audience(sender).sendMessage(message);
} }
} }
@@ -34,24 +34,24 @@ public class ClearChatCommand {
} }
private void execute(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) { private void execute(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) {
final String format = this.carbonChat.getModConfig().getString("clear-chat.message", ""); final String format = this.carbonChat.moderationConfig().getString("clear-chat.message", "");
final Component component = this.carbonChat.getAdventureManager().processMessage(format, "br", "\n"); final Component component = this.carbonChat.adventureManager().processMessage(format, "br", "\n");
for (final Player player : Bukkit.getOnlinePlayers()) { for (final Player player : Bukkit.getOnlinePlayers()) {
final ChatUser audience = this.carbonChat.getUserService().wrap(player); final ChatUser audience = this.carbonChat.userService().wrap(player);
if (player.hasPermission("carbonchat.clearchat.exempt")) { if (player.hasPermission("carbonchat.clearchat.exempt")) {
final String message = this.carbonChat.getLanguage().getString("clear-exempt"); final String message = this.carbonChat.language().getString("clear-exempt");
audience.sendMessage(this.carbonChat.getAdventureManager().processMessage(message, "player", sender.getName())); audience.sendMessage(this.carbonChat.adventureManager().processMessage(message, "player", sender.getName()));
} else { } else {
for (int i = 0; i < this.carbonChat.getModConfig().getInt("clear-chat.message-count", 100); i++) { for (int i = 0; i < this.carbonChat.moderationConfig().getInt("clear-chat.message-count", 100); i++) {
audience.sendMessage(component); audience.sendMessage(component);
} }
} }
if (player.hasPermission("carbonchat.clearchat.notify")) { if (player.hasPermission("carbonchat.clearchat.notify")) {
final String message = this.carbonChat.getLanguage().getString("clear-notify"); final String message = this.carbonChat.language().getString("clear-notify");
audience.sendMessage(this.carbonChat.getAdventureManager().processMessage(message, "player", sender.getName())); audience.sendMessage(this.carbonChat.adventureManager().processMessage(message, "player", sender.getName()));
} }
} }
} }
@@ -43,26 +43,26 @@ public class IgnoreCommand {
private void execute(@NonNull final Player player, @NonNull final Object @NonNull [] args) { private void execute(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
final ChatUser targetUser = (ChatUser) args[0]; final ChatUser targetUser = (ChatUser) args[0];
final ChatUser user = this.carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
if (user.ignoringUser(targetUser)) { if (user.ignoringUser(targetUser)) {
user.ignoringUser(targetUser, false); user.ignoringUser(targetUser, false);
user.sendMessage(this.carbonChat.getAdventureManager().processMessageWithPapi(player, user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player,
this.carbonChat.getLanguage().getString("not-ignoring-user"), this.carbonChat.language().getString("not-ignoring-user"),
"br", "\n", "player", targetUser.offlinePlayer().getName())); "br", "\n", "player", targetUser.offlinePlayer().getName()));
} else { } else {
Bukkit.getScheduler().runTaskAsynchronously(this.carbonChat, () -> { Bukkit.getScheduler().runTaskAsynchronously(this.carbonChat, () -> {
final Permission permission = this.carbonChat.getPermission(); final Permission permission = this.carbonChat.permission();
final String format; final String format;
if (permission.playerHas(null, targetUser.offlinePlayer(), "carbonchat.ignore.exempt")) { if (permission.playerHas(null, targetUser.offlinePlayer(), "carbonchat.ignore.exempt")) {
format = this.carbonChat.getLanguage().getString("ignore-exempt"); format = this.carbonChat.language().getString("ignore-exempt");
} else { } else {
user.ignoringUser(targetUser, true); user.ignoringUser(targetUser, true);
format = this.carbonChat.getLanguage().getString("ignoring-user"); format = this.carbonChat.language().getString("ignoring-user");
} }
final Component message = this.carbonChat.getAdventureManager().processMessageWithPapi(player, format, final Component message = this.carbonChat.adventureManager().processMessageWithPapi(player, format,
"br", "\n", "sender", player.getDisplayName(), "player", "br", "\n", "sender", player.getDisplayName(), "player",
targetUser.offlinePlayer().getName()); targetUser.offlinePlayer().getName());
@@ -43,26 +43,26 @@ public class MeCommand {
private void execute(@NonNull final Player player, @NonNull final Object @NonNull [] args) { private void execute(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
final String message = ((String) args[0]).replace("</pre>", ""); final String message = ((String) args[0]).replace("</pre>", "");
String format = PlaceholderAPI.setPlaceholders(player, this.carbonChat.getLanguage().getString("me")); String format = PlaceholderAPI.setPlaceholders(player, this.carbonChat.language().getString("me"));
if (!player.hasPermission("carbonchat.me.formatting")) { if (!player.hasPermission("carbonchat.me.formatting")) {
format = format.replace("<message>", "<pre><message></pre>"); format = format.replace("<message>", "<pre><message></pre>");
} }
final Component component = this.carbonChat.getAdventureManager().processMessage(format, "br", "\n", final Component component = this.carbonChat.adventureManager().processMessage(format, "br", "\n",
"displayname", player.getDisplayName(), "message", message); "displayname", player.getDisplayName(), "message", message);
final ChatUser user = this.carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
if (user.shadowMuted()) { if (user.shadowMuted()) {
user.sendMessage(component); user.sendMessage(component);
} else { } else {
for (final Player onlinePlayer : Bukkit.getOnlinePlayers()) { for (final Player onlinePlayer : Bukkit.getOnlinePlayers()) {
if (this.carbonChat.getUserService().wrap(onlinePlayer).ignoringUser(user)) { if (this.carbonChat.userService().wrap(onlinePlayer).ignoringUser(user)) {
continue; continue;
} }
this.carbonChat.getAdventureManager().audiences().player(onlinePlayer).sendMessage(component); this.carbonChat.adventureManager().audiences().player(onlinePlayer).sendMessage(component);
} }
} }
} }
@@ -44,7 +44,7 @@ public class MessageCommand {
final ChatUser targetUser = (ChatUser) args[0]; final ChatUser targetUser = (ChatUser) args[0];
final String message = (String) args[1]; final String message = (String) args[1];
final ChatUser sender = this.carbonChat.getUserService().wrap(player); final ChatUser sender = this.carbonChat.userService().wrap(player);
targetUser.sendMessage(sender, message); targetUser.sendMessage(sender, message);
} }
@@ -44,29 +44,29 @@ public class MuteCommand {
private void execute(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) { private void execute(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) {
final ChatUser user = (ChatUser) args[0]; final ChatUser user = (ChatUser) args[0];
final Audience audience = this.carbonChat.getAdventureManager().audiences().audience(sender); final Audience audience = this.carbonChat.adventureManager().audiences().audience(sender);
if (user.shadowMuted()) { if (user.shadowMuted()) {
user.muted(false); user.muted(false);
final String format = this.carbonChat.getLanguage().getString("no-longer-muted"); final String format = this.carbonChat.language().getString("no-longer-muted");
final Component message = this.carbonChat.getAdventureManager().processMessage(format, "br", "\n", final Component message = this.carbonChat.adventureManager().processMessage(format, "br", "\n",
"player", user.offlinePlayer().getName()); "player", user.offlinePlayer().getName());
audience.sendMessage(message); audience.sendMessage(message);
} else { } else {
Bukkit.getScheduler().runTaskAsynchronously(this.carbonChat, () -> { Bukkit.getScheduler().runTaskAsynchronously(this.carbonChat, () -> {
final Permission permission = this.carbonChat.getPermission(); final Permission permission = this.carbonChat.permission();
final String format; final String format;
if (permission.playerHas(null, user.offlinePlayer(), "carbonchat.mute.exempt")) { if (permission.playerHas(null, user.offlinePlayer(), "carbonchat.mute.exempt")) {
format = this.carbonChat.getLanguage().getString("mute-exempt"); format = this.carbonChat.language().getString("mute-exempt");
} else { } else {
user.muted(true); user.muted(true);
format = this.carbonChat.getLanguage().getString("is-now-muted"); format = this.carbonChat.language().getString("is-now-muted");
} }
final Component message = this.carbonChat.getAdventureManager().processMessage(format, "br", "\n", final Component message = this.carbonChat.adventureManager().processMessage(format, "br", "\n",
"player", user.offlinePlayer().getName()); "player", user.offlinePlayer().getName());
audience.sendMessage(message); audience.sendMessage(message);
@@ -54,7 +54,7 @@ public class NicknameCommand {
private void executeSelf(@NonNull final Player player, @NonNull final Object @NonNull [] args) { private void executeSelf(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
String nickname = (String) args[0]; String nickname = (String) args[0];
final ChatUser sender = this.carbonChat.getUserService().wrap(player); final ChatUser sender = this.carbonChat.userService().wrap(player);
if (nickname.equalsIgnoreCase("off") || nickname.equalsIgnoreCase(player.getName())) { if (nickname.equalsIgnoreCase("off") || nickname.equalsIgnoreCase(player.getName())) {
nickname = null; nickname = null;
@@ -65,18 +65,18 @@ public class NicknameCommand {
final String message; final String message;
if (nickname == null) { if (nickname == null) {
message = this.carbonChat.getLanguage().getString("nickname-reset"); message = this.carbonChat.language().getString("nickname-reset");
} else { } else {
message = this.carbonChat.getLanguage().getString("nickname-set"); message = this.carbonChat.language().getString("nickname-set");
} }
sender.sendMessage(this.carbonChat.getAdventureManager().processMessage( sender.sendMessage(this.carbonChat.adventureManager().processMessage(
message, "nickname", nickname == null ? "" : nickname, message, "nickname", nickname == null ? "" : nickname,
"user", sender.offlinePlayer().getName())); "user", sender.offlinePlayer().getName()));
} }
private void executeOther(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) { private void executeOther(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) {
final Audience user = this.carbonChat.getAdventureManager().audiences().audience(sender); final Audience user = this.carbonChat.adventureManager().audiences().audience(sender);
final ChatUser target = (ChatUser) args[0]; final ChatUser target = (ChatUser) args[0];
String nickname = (String) args[1]; String nickname = (String) args[1];
@@ -90,12 +90,12 @@ public class NicknameCommand {
final String message; final String message;
if (nickname == null) { if (nickname == null) {
message = this.carbonChat.getLanguage().getString("other-nickname-reset"); message = this.carbonChat.language().getString("other-nickname-reset");
} else { } else {
message = this.carbonChat.getLanguage().getString("other-nickname-set"); message = this.carbonChat.language().getString("other-nickname-set");
} }
user.sendMessage(this.carbonChat.getAdventureManager().processMessage( user.sendMessage(this.carbonChat.adventureManager().processMessage(
message, "nickname", nickname == null ? "" : nickname, message, "nickname", nickname == null ? "" : nickname,
"user", target.offlinePlayer().getName())); "user", target.offlinePlayer().getName()));
} }
@@ -42,11 +42,11 @@ public class ReplyCommand {
private void execute(@NonNull final Player player, @NonNull final Object @NonNull [] args) { private void execute(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
final String input = (String) args[0]; final String input = (String) args[0];
final ChatUser user = this.carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
if (input.isEmpty()) { if (input.isEmpty()) {
final String message = this.carbonChat.getLanguage().getString("reply-message-blank"); final String message = this.carbonChat.language().getString("reply-message-blank");
final Component component = this.carbonChat.getAdventureManager().processMessage(message, "br", "\n"); final Component component = this.carbonChat.adventureManager().processMessage(message, "br", "\n");
user.sendMessage(component); user.sendMessage(component);
@@ -54,15 +54,15 @@ public class ReplyCommand {
} }
if (user.replyTarget() == null) { if (user.replyTarget() == null) {
final String message = this.carbonChat.getLanguage().getString("no-reply-target"); final String message = this.carbonChat.language().getString("no-reply-target");
final Component component = this.carbonChat.getAdventureManager().processMessage(message, "br", "\n"); final Component component = this.carbonChat.adventureManager().processMessage(message, "br", "\n");
user.sendMessage(component); user.sendMessage(component);
return; return;
} }
final ChatUser targetUser = this.carbonChat.getUserService().wrap(user.replyTarget()); final ChatUser targetUser = this.carbonChat.userService().wrap(user.replyTarget());
targetUser.sendMessage(user, input); targetUser.sendMessage(user, input);
} }
@@ -30,7 +30,7 @@ public class SetColorCommand {
CommandUtils.handleDuplicateCommands(commandSettings); CommandUtils.handleDuplicateCommands(commandSettings);
for (final ChatChannel channel : this.carbonChat.getChannelManager().registry().values()) { for (final ChatChannel channel : this.carbonChat.channelManager().registry().values()) {
final LinkedHashMap<String, Argument> arguments = new LinkedHashMap<>(); final LinkedHashMap<String, Argument> arguments = new LinkedHashMap<>();
arguments.put("channel", new LiteralArgument(channel.key())); arguments.put("channel", new LiteralArgument(channel.key()));
arguments.put("color", CarbonUtils.textColorArgument()); arguments.put("color", CarbonUtils.textColorArgument());
@@ -41,11 +41,11 @@ public class SetColorCommand {
.withPermission(CommandPermission.fromString("carbonchat.setcolor")) .withPermission(CommandPermission.fromString("carbonchat.setcolor"))
.executesPlayer((player, args) -> { .executesPlayer((player, args) -> {
final TextColor color = (TextColor) args[0]; final TextColor color = (TextColor) args[0];
final ChatUser user = this.carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
if (!player.hasPermission("carbonchat.setcolor." + channel.key())) { if (!player.hasPermission("carbonchat.setcolor." + channel.key())) {
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(player, user.sendMessage(carbonChat.adventureManager().processMessageWithPapi(player,
this.carbonChat.getLanguage().getString("cannot-set-color"), this.carbonChat.language().getString("cannot-set-color"),
"br", "\n", "input", color.asHexString(), "br", "\n", "input", color.asHexString(),
"channel", channel.name())); "channel", channel.name()));
@@ -56,8 +56,8 @@ public class SetColorCommand {
settings.color(color); settings.color(color);
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(player, user.sendMessage(carbonChat.adventureManager().processMessageWithPapi(player,
this.carbonChat.getLanguage().getString("channel-color-set"), this.carbonChat.language().getString("channel-color-set"),
"br", "\n", "color", "<color:" + color.asHexString() + ">", "channel", "br", "\n", "color", "<color:" + color.asHexString() + ">", "channel",
channel.name(), "hex", color.asHexString())); channel.name(), "hex", color.asHexString()));
}) })
@@ -44,29 +44,29 @@ public class ShadowMuteCommand {
private void execute(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) { private void execute(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) {
final ChatUser user = (ChatUser) args[0]; final ChatUser user = (ChatUser) args[0];
final Audience audience = this.carbonChat.getAdventureManager().audiences().audience(sender); final Audience audience = this.carbonChat.adventureManager().audiences().audience(sender);
if (user.shadowMuted()) { if (user.shadowMuted()) {
user.shadowMuted(false); user.shadowMuted(false);
final String format = this.carbonChat.getLanguage().getString("no-longer-shadow-muted"); final String format = this.carbonChat.language().getString("no-longer-shadow-muted");
final Component message = this.carbonChat.getAdventureManager().processMessage(format, "br", "\n", final Component message = this.carbonChat.adventureManager().processMessage(format, "br", "\n",
"player", user.offlinePlayer().getName()); "player", user.offlinePlayer().getName());
audience.sendMessage(message); audience.sendMessage(message);
} else { } else {
Bukkit.getScheduler().runTaskAsynchronously(this.carbonChat, () -> { Bukkit.getScheduler().runTaskAsynchronously(this.carbonChat, () -> {
final Permission permission = this.carbonChat.getPermission(); final Permission permission = this.carbonChat.permission();
final String format; final String format;
if (permission.playerHas(null, user.offlinePlayer(), "carbonchat.shadowmute.exempt")) { if (permission.playerHas(null, user.offlinePlayer(), "carbonchat.shadowmute.exempt")) {
format = this.carbonChat.getLanguage().getString("shadow-mute-exempt"); format = this.carbonChat.language().getString("shadow-mute-exempt");
} else { } else {
user.shadowMuted(true); user.shadowMuted(true);
format = this.carbonChat.getLanguage().getString("is-now-shadow-muted"); format = this.carbonChat.language().getString("is-now-shadow-muted");
} }
final Component message = this.carbonChat.getAdventureManager().processMessage(format, "br", "\n", final Component message = this.carbonChat.adventureManager().processMessage(format, "br", "\n",
"player", user.offlinePlayer().getName()); "player", user.offlinePlayer().getName());
audience.sendMessage(message); audience.sendMessage(message);
@@ -65,7 +65,7 @@ public class SpyChannelCommand {
private void execute(@NonNull final Player player, @NonNull final Object @NonNull [] args) { private void execute(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
final ChatChannel chatChannel = (ChatChannel) args[0]; final ChatChannel chatChannel = (ChatChannel) args[0];
final ChatUser user = this.carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
final String message; final String message;
@@ -73,58 +73,58 @@ public class SpyChannelCommand {
if (settings.spying()) { if (settings.spying()) {
settings.spying(false); settings.spying(false);
message = this.carbonChat.getLanguage().getString("spy-toggled-off"); message = this.carbonChat.language().getString("spy-toggled-off");
} else { } else {
settings.spying(true); settings.spying(true);
message = this.carbonChat.getLanguage().getString("spy-toggled-on"); message = this.carbonChat.language().getString("spy-toggled-on");
} }
user.sendMessage(this.carbonChat.getAdventureManager().processMessageWithPapi(player, message, "br", "\n", user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player, message, "br", "\n",
"color", "<color:" + chatChannel.channelColor(user).toString() + ">", "channel", chatChannel.name())); "color", "<color:" + chatChannel.channelColor(user).toString() + ">", "channel", chatChannel.name()));
} }
private void executeWhispers(@NonNull final Player player, @NonNull final Object @NonNull [] args) { private void executeWhispers(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
final ChatUser user = this.carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
final String message; final String message;
if (user.spyingwhispers()) { if (user.spyingwhispers()) {
user.spyingWhispers(false); user.spyingWhispers(false);
message = this.carbonChat.getLanguage().getString("spy-whispers-off"); message = this.carbonChat.language().getString("spy-whispers-off");
} else { } else {
user.spyingWhispers(true); user.spyingWhispers(true);
message = this.carbonChat.getLanguage().getString("spy-whispers-on"); message = this.carbonChat.language().getString("spy-whispers-on");
} }
user.sendMessage(this.carbonChat.getAdventureManager().processMessageWithPapi(player, message, "br", "\n")); user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player, message, "br", "\n"));
} }
private void executeEverything(@NonNull final Player player, @NonNull final Object @NonNull [] args) { private void executeEverything(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
final Boolean shouldSpy = (Boolean) args[0]; final Boolean shouldSpy = (Boolean) args[0];
final ChatUser user = this.carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
final String message; final String message;
if (shouldSpy) { if (shouldSpy) {
user.spyingWhispers(true); user.spyingWhispers(true);
for (final ChatChannel channel : this.carbonChat.getChannelManager().registry().values()) { for (final ChatChannel channel : this.carbonChat.channelManager().registry().values()) {
user.channelSettings(channel).spying(true); user.channelSettings(channel).spying(true);
} }
message = this.carbonChat.getLanguage().getString("spy-everything-off"); message = this.carbonChat.language().getString("spy-everything-off");
} else { } else {
user.spyingWhispers(false); user.spyingWhispers(false);
for (final ChatChannel channel : this.carbonChat.getChannelManager().registry().values()) { for (final ChatChannel channel : this.carbonChat.channelManager().registry().values()) {
user.channelSettings(channel).spying(false); user.channelSettings(channel).spying(false);
} }
message = this.carbonChat.getLanguage().getString("spy-everything-on"); message = this.carbonChat.language().getString("spy-everything-on");
} }
user.sendMessage(this.carbonChat.getAdventureManager().processMessageWithPapi(player, message, "br", "\n")); user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player, message, "br", "\n"));
} }
} }
@@ -64,11 +64,11 @@ public class SudoChannelCommand {
final String message = channel.switchMessage(); final String message = channel.switchMessage();
final String otherMessage = channel.switchOtherMessage(); final String otherMessage = channel.switchOtherMessage();
user.sendMessage(this.carbonChat.getAdventureManager().processMessage(message, "br", "\n", user.sendMessage(this.carbonChat.adventureManager().processMessage(message, "br", "\n",
"color", "<color:" + channel.channelColor(user).toString() + ">", "channel", channel.name())); "color", "<color:" + channel.channelColor(user).toString() + ">", "channel", channel.name()));
this.carbonChat.getAdventureManager().audiences().audience(sender).sendMessage( this.carbonChat.adventureManager().audiences().audience(sender).sendMessage(
this.carbonChat.getAdventureManager().processMessage(otherMessage, "br", "\n", this.carbonChat.adventureManager().processMessage(otherMessage, "br", "\n",
"color", "<color:" + channel.channelColor(user).toString() + ">", "channel", channel.name(), "color", "<color:" + channel.channelColor(user).toString() + ">", "channel", channel.name(),
"player", user.offlinePlayer().getName())); "player", user.offlinePlayer().getName()));
} }
@@ -77,7 +77,7 @@ public class SudoChannelCommand {
@NonNull final ChatChannel channel, @NonNull final String message) { @NonNull final ChatChannel channel, @NonNull final String message) {
final Component component = channel.sendMessage(user, message, false); final Component component = channel.sendMessage(user, message, false);
this.carbonChat.getAdventureManager().audiences().console().sendMessage(component); this.carbonChat.adventureManager().audiences().console().sendMessage(component);
} }
} }
@@ -53,7 +53,7 @@ public class ToggleCommand {
} }
private void executeSelf(@NonNull final Player player, @NonNull final Object @NonNull [] args) { private void executeSelf(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
final ChatUser user = this.carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
final ChatChannel channel = (ChatChannel) args[0]; final ChatChannel channel = (ChatChannel) args[0];
final String message; final String message;
@@ -70,7 +70,7 @@ public class ToggleCommand {
message = channel.toggleOnMessage(); message = channel.toggleOnMessage();
} }
user.sendMessage(this.carbonChat.getAdventureManager().processMessageWithPapi(player, message, "br", "\n", user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player, message, "br", "\n",
"color", "<color:" + channel.channelColor(user).toString() + ">", "channel", channel.name())); "color", "<color:" + channel.channelColor(user).toString() + ">", "channel", channel.name()));
} }
@@ -93,11 +93,11 @@ public class ToggleCommand {
otherMessage = channel.toggleOtherOnMessage(); otherMessage = channel.toggleOtherOnMessage();
} }
user.sendMessage(this.carbonChat.getAdventureManager().processMessage(message, "br", "\n", user.sendMessage(this.carbonChat.adventureManager().processMessage(message, "br", "\n",
"color", "<color:" + channel.channelColor(user).toString() + ">", "channel", channel.name())); "color", "<color:" + channel.channelColor(user).toString() + ">", "channel", channel.name()));
this.carbonChat.getAdventureManager().audiences().audience(sender).sendMessage( this.carbonChat.adventureManager().audiences().audience(sender).sendMessage(
this.carbonChat.getAdventureManager().processMessage(otherMessage, this.carbonChat.adventureManager().processMessage(otherMessage,
"br", "\n", "color", "<color:" + channel.channelColor(user).toString() + ">", "br", "\n", "color", "<color:" + channel.channelColor(user).toString() + ">",
"channel", channel.name(), "player", user.offlinePlayer().getName())); "channel", channel.name(), "player", user.offlinePlayer().getName()));
} }
@@ -27,14 +27,14 @@ public class BukkitChatListener implements Listener {
// Chat messages // Chat messages
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerchat(@NonNull final AsyncPlayerChatEvent event) { public void onPlayerchat(@NonNull final AsyncPlayerChatEvent event) {
final ChatUser user = this.carbonChat.getUserService().wrap(event.getPlayer()); final ChatUser user = this.carbonChat.userService().wrap(event.getPlayer());
ChatChannel channel = user.selectedChannel(); ChatChannel channel = user.selectedChannel();
if (channel.shouldCancelChatEvent()) { if (channel.shouldCancelChatEvent()) {
event.setCancelled(true); event.setCancelled(true);
} }
for (final ChatChannel entry : this.carbonChat.getChannelManager().registry().values()) { for (final ChatChannel entry : this.carbonChat.channelManager().registry().values()) {
if (entry.messagePrefix() == null || entry.messagePrefix().isEmpty()) { if (entry.messagePrefix() == null || entry.messagePrefix().isEmpty()) {
continue; continue;
} }
@@ -60,7 +60,7 @@ public class BukkitChatListener implements Listener {
recipients = new HashSet<>(); recipients = new HashSet<>();
for (final Player recipient : event.getRecipients()) { for (final Player recipient : event.getRecipients()) {
recipients.add(this.carbonChat.getUserService().wrap(recipient)); recipients.add(this.carbonChat.userService().wrap(recipient));
} }
} else { } else {
recipients = selectedChannel.audiences(); recipients = selectedChannel.audiences();
@@ -77,7 +77,7 @@ public class BukkitChatListener implements Listener {
Bukkit.getScheduler().runTaskAsynchronously(this.carbonChat, () -> { Bukkit.getScheduler().runTaskAsynchronously(this.carbonChat, () -> {
final Component component = selectedChannel.sendMessage(user, recipients, event.getMessage(), false); final Component component = selectedChannel.sendMessage(user, recipients, event.getMessage(), false);
this.carbonChat.getAdventureManager().audiences().console().sendMessage(component); this.carbonChat.adventureManager().audiences().console().sendMessage(component);
if (this.carbonChat.getConfig().getBoolean("show-tips")) { if (this.carbonChat.getConfig().getBoolean("show-tips")) {
this.carbonChat.getLogger().info("Tip: Sync chat event! I cannot set the message format due to this. :("); this.carbonChat.getLogger().info("Tip: Sync chat event! I cannot set the message format due to this. :(");
@@ -18,11 +18,11 @@ public class CapsHandler implements Listener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onMessage(final PreChatFormatEvent event) { public void onMessage(final PreChatFormatEvent event) {
if (!this.carbonChat.getModConfig().getBoolean("caps-protection.enabled")) { if (!this.carbonChat.moderationConfig().getBoolean("caps-protection.enabled")) {
return; return;
} }
if (!(event.message().length() >= this.carbonChat.getModConfig().getInt("caps-protection.minimum-length"))) { if (!(event.message().length() >= this.carbonChat.moderationConfig().getInt("caps-protection.minimum-length"))) {
return; return;
} }
@@ -36,11 +36,11 @@ public class CapsHandler implements Listener {
final double capsPercentage = (amountOfCaps * 100.0) / event.message().length(); final double capsPercentage = (amountOfCaps * 100.0) / event.message().length();
if (!(capsPercentage >= this.carbonChat.getModConfig().getDouble("caps-protection.percent-caps"))) { if (!(capsPercentage >= this.carbonChat.moderationConfig().getDouble("caps-protection.percent-caps"))) {
return; return;
} }
if (this.carbonChat.getModConfig().getBoolean("block-message")) { if (this.carbonChat.moderationConfig().getBoolean("block-message")) {
event.setCancelled(true); event.setCancelled(true);
} else { } else {
event.message(event.message().toLowerCase()); event.message(event.message().toLowerCase());
@@ -37,7 +37,7 @@ public class FilterHandler implements Listener {
this.patternReplacements.clear(); this.patternReplacements.clear();
this.blockedWords.clear(); this.blockedWords.clear();
final FileConfiguration config = this.carbonChat.getModConfig(); final FileConfiguration config = this.carbonChat.moderationConfig();
final ConfigurationSection filters = config.getConfigurationSection("filters.filters"); final ConfigurationSection filters = config.getConfigurationSection("filters.filters");
if (filters != null) { if (filters != null) {
@@ -45,7 +45,7 @@ public class FilterHandler implements Listener {
final List<Pattern> patterns = new ArrayList<>(); final List<Pattern> patterns = new ArrayList<>();
for (final String word : filters.getStringList(replacement)) { for (final String word : filters.getStringList(replacement)) {
if (this.carbonChat.getModConfig().getBoolean("filters.case-sensitive")) { if (this.carbonChat.moderationConfig().getBoolean("filters.case-sensitive")) {
patterns.add(Pattern.compile(word)); patterns.add(Pattern.compile(word));
} else { } else {
patterns.add(Pattern.compile(word, Pattern.CASE_INSENSITIVE)); patterns.add(Pattern.compile(word, Pattern.CASE_INSENSITIVE));
@@ -57,7 +57,7 @@ public class FilterHandler implements Listener {
} }
for (final String replacement : config.getStringList("filters.blocked-words")) { for (final String replacement : config.getStringList("filters.blocked-words")) {
if (this.carbonChat.getModConfig().getBoolean("filters.case-sensitive")) { if (this.carbonChat.moderationConfig().getBoolean("filters.case-sensitive")) {
this.blockedWords.add(Pattern.compile(replacement)); this.blockedWords.add(Pattern.compile(replacement));
} else { } else {
this.blockedWords.add(Pattern.compile(replacement, Pattern.CASE_INSENSITIVE)); this.blockedWords.add(Pattern.compile(replacement, Pattern.CASE_INSENSITIVE));
@@ -67,7 +67,7 @@ public class FilterHandler implements Listener {
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onFilter(final PreChatFormatEvent event) { public void onFilter(final PreChatFormatEvent event) {
if (!this.carbonChat.getModConfig().getBoolean("filters.enabled")) { if (!this.carbonChat.moderationConfig().getBoolean("filters.enabled")) {
return; return;
} }
@@ -20,9 +20,9 @@ public class PlayerJoinListener implements Listener {
@EventHandler @EventHandler
public void onPlayerJoin(final PlayerJoinEvent event) { public void onPlayerJoin(final PlayerJoinEvent event) {
final ChatUser user = this.carbonChat.getUserService().wrap(event.getPlayer()); final ChatUser user = this.carbonChat.userService().wrap(event.getPlayer());
this.carbonChat.getUserService().validate(user); this.carbonChat.userService().validate(user);
if (user.nickname() != null) { if (user.nickname() != null) {
user.nickname(user.nickname()); user.nickname(user.nickname());
@@ -35,11 +35,11 @@ public class PlayerJoinListener implements Listener {
} }
if (channel.equals("DEFAULT")) { if (channel.equals("DEFAULT")) {
user.selectedChannel(this.carbonChat.getChannelManager().defaultChannel()); user.selectedChannel(this.carbonChat.channelManager().defaultChannel());
return; return;
} }
final ChatChannel chatChannel = this.carbonChat.getChannelManager().registry().channel(channel); final ChatChannel chatChannel = this.carbonChat.channelManager().registry().channel(channel);
if (chatChannel != null) { if (chatChannel != null) {
user.selectedChannel(chatChannel); user.selectedChannel(chatChannel);
@@ -48,10 +48,10 @@ public class PlayerJoinListener implements Listener {
@EventHandler @EventHandler
public void onPlayerQuit(final PlayerQuitEvent event) { public void onPlayerQuit(final PlayerQuitEvent event) {
final ChatUser user = this.carbonChat.getUserService().wrapIfLoaded(event.getPlayer()); final ChatUser user = this.carbonChat.userService().wrapIfLoaded(event.getPlayer());
if (user != null) { if (user != null) {
this.carbonChat.getUserService().invalidate(user); this.carbonChat.userService().invalidate(user);
} }
} }
@@ -36,7 +36,7 @@ public class ShadowMuteHandler implements Listener {
return; return;
} }
final String prefix = this.carbonChat.getModConfig().getString("shadow-mute-prefix", "[SM] "); final String prefix = this.carbonChat.moderationConfig().getString("shadow-mute-prefix", "[SM] ");
event.format(prefix + event.format()); event.format(prefix + event.format());
} }
@@ -40,7 +40,7 @@ public class AdventureManager {
return TextComponent.empty(); return TextComponent.empty();
} }
switch (this.carbonChat.getLanguage().getString("formatting.type", "minimessage").toLowerCase()) { switch (this.carbonChat.language().getString("formatting.type", "minimessage").toLowerCase()) {
case "minedown": case "minedown":
return MineDown.parse(input, placeholders); return MineDown.parse(input, placeholders);
case "mojang": case "mojang":
@@ -51,7 +51,7 @@ public class CommandManager {
@NonNull @NonNull
private CommandSettings commandSettings(@NonNull final String command) { private CommandSettings commandSettings(@NonNull final String command) {
final ConfigurationSection section = this.carbonChat.getCommandsConfig().getConfigurationSection(command); final ConfigurationSection section = this.carbonChat.commandsConfig().getConfigurationSection(command);
return new CommandSettings(section.getBoolean("enabled"), section.getString("name"), return new CommandSettings(section.getBoolean("enabled"), section.getString("name"),
section.getStringList("aliases")); section.getStringList("aliases"));
@@ -28,7 +28,7 @@ public class MessageManager {
public MessageManager(@NonNull final CarbonChat carbonChat) { public MessageManager(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
this.gsonSerializer = this.carbonChat.getAdventureManager().audiences().gsonSerializer(); this.gsonSerializer = this.carbonChat.adventureManager().audiences().gsonSerializer();
String messageSystem = this.carbonChat.getConfig().getString("message-system", "none"); String messageSystem = this.carbonChat.getConfig().getString("message-system", "none");
@@ -64,9 +64,9 @@ public class MessageManager {
user.nickname(nickname, true); user.nickname(nickname, true);
if (user.online()) { if (user.online()) {
final String message = this.carbonChat.getLanguage().getString("nickname-set"); final String message = this.carbonChat.language().getString("nickname-set");
user.sendMessage(this.carbonChat.getAdventureManager().processMessageWithPapi(user.player(), user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(user.player(),
message, "nickname", nickname)); message, "nickname", nickname));
} }
}); });
@@ -75,14 +75,14 @@ public class MessageManager {
user.nickname(null, true); user.nickname(null, true);
if (user.online()) { if (user.online()) {
final String message = this.carbonChat.getLanguage().getString("nickname-reset"); final String message = this.carbonChat.language().getString("nickname-reset");
user.sendMessage(this.carbonChat.getAdventureManager().processMessageWithPapi(user.player(), message)); user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(user.player(), message));
} }
}); });
this.messageService().registerUserMessageListener("selected-channel", (user, byteArray) -> { this.messageService().registerUserMessageListener("selected-channel", (user, byteArray) -> {
user.selectedChannel(this.carbonChat.getChannelManager().registry().channel(byteArray.readUTF()), true); user.selectedChannel(this.carbonChat.channelManager().registry().channel(byteArray.readUTF()), true);
}); });
this.messageService().registerUserMessageListener("spying-whispers", (user, byteArray) -> { this.messageService().registerUserMessageListener("spying-whispers", (user, byteArray) -> {
@@ -106,42 +106,42 @@ public class MessageManager {
}); });
this.messageService().registerUserMessageListener("ignoring-channel", (user, byteArray) -> { this.messageService().registerUserMessageListener("ignoring-channel", (user, byteArray) -> {
user.channelSettings(this.carbonChat.getChannelManager().registry().channel(byteArray.readUTF())) user.channelSettings(this.carbonChat.channelManager().registry().channel(byteArray.readUTF()))
.ignoring(byteArray.readBoolean(), true); .ignoring(byteArray.readBoolean(), true);
}); });
this.messageService().registerUserMessageListener("spying-channel", (user, byteArray) -> { this.messageService().registerUserMessageListener("spying-channel", (user, byteArray) -> {
user.channelSettings(this.carbonChat.getChannelManager().registry().channel(byteArray.readUTF())) user.channelSettings(this.carbonChat.channelManager().registry().channel(byteArray.readUTF()))
.spying(byteArray.readBoolean(), true); .spying(byteArray.readBoolean(), true);
}); });
this.messageService().registerUserMessageListener("channel-color", (user, byteArray) -> { this.messageService().registerUserMessageListener("channel-color", (user, byteArray) -> {
user.channelSettings(this.carbonChat.getChannelManager().registry().channel(byteArray.readUTF())) user.channelSettings(this.carbonChat.channelManager().registry().channel(byteArray.readUTF()))
.color(TextColor.fromHexString(byteArray.readUTF()), true); .color(TextColor.fromHexString(byteArray.readUTF()), true);
}); });
this.messageService().registerUserMessageListener("channel-color-reset", (user, byteArray) -> { this.messageService().registerUserMessageListener("channel-color-reset", (user, byteArray) -> {
user.channelSettings(this.carbonChat.getChannelManager().registry().channel(byteArray.readUTF())) user.channelSettings(this.carbonChat.channelManager().registry().channel(byteArray.readUTF()))
.color(null, true); .color(null, true);
}); });
this.messageService().registerUUIDMessageListener("channel-component", (uuid, byteArray) -> { this.messageService().registerUUIDMessageListener("channel-component", (uuid, byteArray) -> {
final ChatChannel channel = this.carbonChat.getChannelManager().registry().channel(byteArray.readUTF()); final ChatChannel channel = this.carbonChat.channelManager().registry().channel(byteArray.readUTF());
final ChatUser user = this.carbonChat.getUserService().wrap(uuid); final ChatUser user = this.carbonChat.userService().wrap(uuid);
if (channel != null) { if (channel != null) {
final Component component = this.gsonSerializer.deserialize(byteArray.readUTF()); final Component component = this.gsonSerializer.deserialize(byteArray.readUTF());
channel.sendComponent(user, component); channel.sendComponent(user, component);
this.carbonChat.getAdventureManager().audiences().console().sendMessage(component); this.carbonChat.adventureManager().audiences().console().sendMessage(component);
} }
}); });
this.messageService().registerUUIDMessageListener("whisper-component", (uuid, byteArray) -> { this.messageService().registerUUIDMessageListener("whisper-component", (uuid, byteArray) -> {
final UUID recipient = new UUID(byteArray.readLong(), byteArray.readLong()); final UUID recipient = new UUID(byteArray.readLong(), byteArray.readLong());
final ChatUser target = this.carbonChat.getUserService().wrap(recipient); final ChatUser target = this.carbonChat.userService().wrap(recipient);
final String message = byteArray.readUTF(); final String message = byteArray.readUTF();
if (!target.ignoringUser(uuid)) { if (!target.ignoringUser(uuid)) {
@@ -33,50 +33,50 @@ public class BungeeMessageService implements MessageService {
@NonNull @NonNull
private final UUID serverUUID = UUID.randomUUID(); private final UUID serverUUID = UUID.randomUUID();
public BungeeMessageService(@NonNull CarbonChat carbonChat) { public BungeeMessageService(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
this.carbonChat.getServer().getMessenger().registerOutgoingPluginChannel(carbonChat, "BungeeCord"); this.carbonChat.getServer().getMessenger().registerOutgoingPluginChannel(carbonChat, "BungeeCord");
api = BungeeChannelApi.of(carbonChat); this.api = BungeeChannelApi.of(carbonChat);
api.registerForwardListener((String channel, Player player, byte[] bytes) -> { this.api.registerForwardListener((String channel, Player player, byte[] bytes) -> {
try { try {
ByteArrayDataInput input = ByteStreams.newDataInput(bytes); final ByteArrayDataInput input = ByteStreams.newDataInput(bytes);
// Separated out for ease of debugging. // Separated out for ease of debugging.
long mostServer = input.readLong(); final long mostServer = input.readLong();
long leastServer = input.readLong(); final long leastServer = input.readLong();
UUID messageUUID = new UUID(mostServer, leastServer); final UUID messageUUID = new UUID(mostServer, leastServer);
if (messageUUID.equals(serverUUID)) { if (messageUUID.equals(this.serverUUID)) {
return; return;
} }
long mostUser = input.readLong(); final long mostUser = input.readLong();
long leastUser = input.readLong(); final long leastUser = input.readLong();
UUID userUUID = new UUID(mostUser, leastUser); final UUID userUUID = new UUID(mostUser, leastUser);
this.receiveMessage(userUUID, channel, input); this.receiveMessage(userUUID, channel, input);
} catch (IllegalStateException ignored) { } catch (final IllegalStateException ignored) {
} }
}); });
} }
private void receiveMessage(@NonNull UUID uuid, @NonNull String key, @NonNull ByteArrayDataInput value) { private void receiveMessage(@NonNull final UUID uuid, @NonNull final String key, @NonNull final ByteArrayDataInput value) {
ChatUser user = this.carbonChat.getUserService().wrapIfLoaded(uuid); final ChatUser user = this.carbonChat.userService().wrapIfLoaded(uuid);
if (user != null) { if (user != null) {
for (Map.Entry<String, BiConsumer<ChatUser, ByteArrayDataInput>> listener : userLoadedListeners.entrySet()) { for (final Map.Entry<String, BiConsumer<ChatUser, ByteArrayDataInput>> listener : this.userLoadedListeners.entrySet()) {
if (key.equals(listener.getKey())) { if (key.equals(listener.getKey())) {
listener.getValue().accept(user, value); listener.getValue().accept(user, value);
} }
} }
} }
for (Map.Entry<String, BiConsumer<UUID, ByteArrayDataInput>> listener : userNotLoadedListeners.entrySet()) { for (final Map.Entry<String, BiConsumer<UUID, ByteArrayDataInput>> listener : this.userNotLoadedListeners.entrySet()) {
if (key.equals(listener.getKey())) { if (key.equals(listener.getKey())) {
listener.getValue().accept(uuid, value); listener.getValue().accept(uuid, value);
} }
@@ -84,33 +84,33 @@ public class BungeeMessageService implements MessageService {
} }
@Override @Override
public void registerUserMessageListener(@NonNull String key, @NonNull BiConsumer<@NonNull ChatUser, @NonNull ByteArrayDataInput> listener) { public void registerUserMessageListener(@NonNull final String key, @NonNull final BiConsumer<@NonNull ChatUser, @NonNull ByteArrayDataInput> listener) {
userLoadedListeners.put(key, listener); this.userLoadedListeners.put(key, listener);
} }
@Override @Override
public void registerUUIDMessageListener(@NonNull String key, @NonNull BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput> listener) { public void registerUUIDMessageListener(@NonNull final String key, @NonNull final BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput> listener) {
userNotLoadedListeners.put(key, listener); this.userNotLoadedListeners.put(key, listener);
} }
@Override @Override
public void unregisterMessageListener(@NonNull String key) { public void unregisterMessageListener(@NonNull final String key) {
userLoadedListeners.remove(key); this.userLoadedListeners.remove(key);
userNotLoadedListeners.remove(key); this.userNotLoadedListeners.remove(key);
} }
@Override @Override
public void sendMessage(@NonNull String key, @NonNull UUID uuid, @NonNull Consumer<ByteArrayDataOutput> consumer) { public void sendMessage(@NonNull final String key, @NonNull final UUID uuid, @NonNull final Consumer<ByteArrayDataOutput> consumer) {
ByteArrayDataOutput msg = ByteStreams.newDataOutput(); final ByteArrayDataOutput msg = ByteStreams.newDataOutput();
msg.writeLong(serverUUID.getMostSignificantBits()); msg.writeLong(this.serverUUID.getMostSignificantBits());
msg.writeLong(serverUUID.getLeastSignificantBits()); msg.writeLong(this.serverUUID.getLeastSignificantBits());
msg.writeLong(uuid.getMostSignificantBits()); msg.writeLong(uuid.getMostSignificantBits());
msg.writeLong(uuid.getLeastSignificantBits()); msg.writeLong(uuid.getLeastSignificantBits());
consumer.accept(msg); consumer.accept(msg);
api.forward("ALL", key, msg.toByteArray()); this.api.forward("ALL", key, msg.toByteArray());
} }
} }
@@ -40,56 +40,56 @@ public class RedisMessageService implements MessageService {
@NonNull @NonNull
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
public RedisMessageService(@NonNull CarbonChat carbonChat) { public RedisMessageService(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
String host = this.carbonChat.getConfig().getString("redis.host"); final String host = this.carbonChat.getConfig().getString("redis.host");
String password = this.carbonChat.getConfig().getString("redis.password"); final String password = this.carbonChat.getConfig().getString("redis.password");
int port = this.carbonChat.getConfig().getInt("redis.port"); final int port = this.carbonChat.getConfig().getInt("redis.port");
int database = this.carbonChat.getConfig().getInt("redis.database"); final int database = this.carbonChat.getConfig().getInt("redis.database");
RedisURI.Builder builder = RedisURI.Builder.redis(host, port) final RedisURI.Builder builder = RedisURI.Builder.redis(host, port)
.withDatabase(database); .withDatabase(database);
if (password != null) { if (password != null) {
builder.withPassword(password.toCharArray()); builder.withPassword(password.toCharArray());
} }
RedisClient client = RedisClient.create(builder.build()); final RedisClient client = RedisClient.create(builder.build());
StatefulRedisPubSubConnection<String, String> subscribeConnection = client.connectPubSub(); final StatefulRedisPubSubConnection<String, String> subscribeConnection = client.connectPubSub();
this.subscribeSync = subscribeConnection.sync(); this.subscribeSync = subscribeConnection.sync();
StatefulRedisPubSubConnection<String, String> publishConnection = client.connectPubSub(); final StatefulRedisPubSubConnection<String, String> publishConnection = client.connectPubSub();
this.publishSync = publishConnection.sync(); this.publishSync = publishConnection.sync();
subscribeConnection.addListener((RedisListener) (channel, message) -> { subscribeConnection.addListener((RedisListener) (channel, message) -> {
ByteArrayDataInput input = ByteStreams.newDataInput(Base64.getDecoder().decode(message)); final ByteArrayDataInput input = ByteStreams.newDataInput(Base64.getDecoder().decode(message));
UUID messageUUID = new UUID(input.readLong(), input.readLong()); final UUID messageUUID = new UUID(input.readLong(), input.readLong());
if (messageUUID.equals(serverUUID)) { if (messageUUID.equals(this.serverUUID)) {
return; return;
} }
UUID uuid = new UUID(input.readLong(), input.readLong()); final UUID uuid = new UUID(input.readLong(), input.readLong());
this.receiveMessage(uuid, channel, input); this.receiveMessage(uuid, channel, input);
}); });
} }
private void receiveMessage(@NonNull UUID uuid, @NonNull String key, @NonNull ByteArrayDataInput value) { private void receiveMessage(@NonNull final UUID uuid, @NonNull final String key, @NonNull final ByteArrayDataInput value) {
ChatUser user = this.carbonChat.getUserService().wrapIfLoaded(uuid); final ChatUser user = this.carbonChat.userService().wrapIfLoaded(uuid);
if (user != null) { if (user != null) {
for (Map.Entry<String, BiConsumer<ChatUser, ByteArrayDataInput>> listener : userLoadedListeners.entrySet()) { for (final Map.Entry<String, BiConsumer<ChatUser, ByteArrayDataInput>> listener : this.userLoadedListeners.entrySet()) {
if (key.equals(listener.getKey())) { if (key.equals(listener.getKey())) {
listener.getValue().accept(user, value); listener.getValue().accept(user, value);
} }
} }
} }
for (Map.Entry<String, BiConsumer<UUID, ByteArrayDataInput>> listener : userNotLoadedListeners.entrySet()) { for (final Map.Entry<String, BiConsumer<UUID, ByteArrayDataInput>> listener : this.userNotLoadedListeners.entrySet()) {
if (key.equals(listener.getKey())) { if (key.equals(listener.getKey())) {
listener.getValue().accept(uuid, value); listener.getValue().accept(uuid, value);
} }
@@ -97,37 +97,37 @@ public class RedisMessageService implements MessageService {
} }
@Override @Override
public void registerUserMessageListener(@NonNull String key, @NonNull BiConsumer<@NonNull ChatUser, @NonNull ByteArrayDataInput> listener) { public void registerUserMessageListener(@NonNull final String key, @NonNull final BiConsumer<@NonNull ChatUser, @NonNull ByteArrayDataInput> listener) {
userLoadedListeners.put(key, listener); this.userLoadedListeners.put(key, listener);
subscribeSync.subscribe(key); this.subscribeSync.subscribe(key);
} }
@Override @Override
public void registerUUIDMessageListener(@NonNull String key, @NonNull BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput> listener) { public void registerUUIDMessageListener(@NonNull final String key, @NonNull final BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput> listener) {
userNotLoadedListeners.put(key, listener); this.userNotLoadedListeners.put(key, listener);
subscribeSync.subscribe(key); this.subscribeSync.subscribe(key);
} }
@Override @Override
public void unregisterMessageListener(@NonNull String key) { public void unregisterMessageListener(@NonNull final String key) {
userLoadedListeners.remove(key); this.userLoadedListeners.remove(key);
userNotLoadedListeners.remove(key); this.userNotLoadedListeners.remove(key);
subscribeSync.unsubscribe(key); this.subscribeSync.unsubscribe(key);
} }
@Override @Override
public void sendMessage(@NonNull String key, @NonNull UUID uuid, @NonNull Consumer<@NonNull ByteArrayDataOutput> consumer) { public void sendMessage(@NonNull final String key, @NonNull final UUID uuid, @NonNull final Consumer<@NonNull ByteArrayDataOutput> consumer) {
ByteArrayDataOutput msg = ByteStreams.newDataOutput(); final ByteArrayDataOutput msg = ByteStreams.newDataOutput();
msg.writeLong(serverUUID.getMostSignificantBits()); msg.writeLong(this.serverUUID.getMostSignificantBits());
msg.writeLong(serverUUID.getLeastSignificantBits()); msg.writeLong(this.serverUUID.getLeastSignificantBits());
msg.writeLong(uuid.getMostSignificantBits()); msg.writeLong(uuid.getMostSignificantBits());
msg.writeLong(uuid.getLeastSignificantBits()); msg.writeLong(uuid.getLeastSignificantBits());
consumer.accept(msg); consumer.accept(msg);
publishSync.publish(key, Base64.getEncoder().encodeToString(msg.toByteArray())); this.publishSync.publish(key, Base64.getEncoder().encodeToString(msg.toByteArray()));
} }
} }
@@ -25,7 +25,7 @@ public interface ChatUser extends Audience {
@Nullable @Nullable
String nickname(); String nickname();
default void nickname(@NonNull String nickname) { default void nickname(@NonNull final String nickname) {
this.nickname(nickname, false); this.nickname(nickname, false);
} }
@@ -34,7 +34,7 @@ public interface ChatUser extends Audience {
@Nullable @Nullable
ChatChannel selectedChannel(); ChatChannel selectedChannel();
default void selectedChannel(@NonNull ChatChannel channel) { default void selectedChannel(@NonNull final ChatChannel channel) {
this.selectedChannel(channel, false); this.selectedChannel(channel, false);
} }
@@ -47,7 +47,7 @@ public interface ChatUser extends Audience {
boolean spyingwhispers(); boolean spyingwhispers();
default void spyingWhispers(boolean spyingWhispers) { default void spyingWhispers(final boolean spyingWhispers) {
this.spyingWhispers(spyingWhispers, false); this.spyingWhispers(spyingWhispers, false);
} }
@@ -55,7 +55,7 @@ public interface ChatUser extends Audience {
boolean muted(); boolean muted();
default void muted(boolean muted) { default void muted(final boolean muted) {
this.muted(muted, false); this.muted(muted, false);
} }
@@ -63,7 +63,7 @@ public interface ChatUser extends Audience {
boolean shadowMuted(); boolean shadowMuted();
default void shadowMuted(boolean shadowMuted) { default void shadowMuted(final boolean shadowMuted) {
this.shadowMuted(shadowMuted, false); this.shadowMuted(shadowMuted, false);
} }
@@ -72,17 +72,17 @@ public interface ChatUser extends Audience {
@Nullable @Nullable
UUID replyTarget(); UUID replyTarget();
default void replyTarget(@Nullable UUID target) { default void replyTarget(@Nullable final UUID target) {
this.replyTarget(target, false); this.replyTarget(target, false);
} }
default void replyTarget(@Nullable ChatUser user) { default void replyTarget(@Nullable final ChatUser user) {
this.replyTarget(user.uuid(), false); this.replyTarget(user.uuid(), false);
} }
void replyTarget(@Nullable UUID target, boolean fromRemote); void replyTarget(@Nullable UUID target, boolean fromRemote);
default void replyTarget(@Nullable ChatUser user, boolean fromRemote) { default void replyTarget(@Nullable final ChatUser user, final boolean fromRemote) {
this.replyTarget(user.uuid(), fromRemote); this.replyTarget(user.uuid(), fromRemote);
} }
@@ -90,19 +90,19 @@ public interface ChatUser extends Audience {
void ignoringUser(@NonNull UUID uuid, boolean ignoring, boolean fromRemote); void ignoringUser(@NonNull UUID uuid, boolean ignoring, boolean fromRemote);
default void ignoringUser(@NonNull UUID uuid, boolean ignoring) { default void ignoringUser(@NonNull final UUID uuid, final boolean ignoring) {
this.ignoringUser(uuid, ignoring, false); this.ignoringUser(uuid, ignoring, false);
} }
default boolean ignoringUser(@NonNull ChatUser user) { default boolean ignoringUser(@NonNull final ChatUser user) {
return this.ignoringUser(user.uuid()); return this.ignoringUser(user.uuid());
} }
default void ignoringUser(@NonNull ChatUser user, boolean ignoring, boolean fromRemote) { default void ignoringUser(@NonNull final ChatUser user, final boolean ignoring, final boolean fromRemote) {
this.ignoringUser(user.uuid(), ignoring, fromRemote); this.ignoringUser(user.uuid(), ignoring, fromRemote);
} }
default void ignoringUser(@NonNull ChatUser user, boolean ignoring) { default void ignoringUser(@NonNull final ChatUser user, final boolean ignoring) {
this.ignoringUser(user.uuid(), ignoring, false); this.ignoringUser(user.uuid(), ignoring, false);
} }
@@ -7,7 +7,7 @@ public interface UserChannelSettings {
boolean spying(); boolean spying();
default void spying(boolean spying) { default void spying(final boolean spying) {
this.spying(spying, false); this.spying(spying, false);
} }
@@ -17,14 +17,14 @@ public interface UserChannelSettings {
void ignoring(boolean ignored, boolean fromRemote); void ignoring(boolean ignored, boolean fromRemote);
default void ignoring(boolean ignored) { default void ignoring(final boolean ignored) {
this.ignoring(ignored, false); this.ignoring(ignored, false);
} }
@Nullable @Nullable
TextColor color(); TextColor color();
default void color(@Nullable TextColor color) { default void color(@Nullable final TextColor color) {
this.color(color, false); this.color(color, false);
} }
@@ -18,7 +18,7 @@ public interface UserService {
ChatUser wrap(UUID uuid); ChatUser wrap(UUID uuid);
@Nullable @Nullable
default ChatUser wrapIfLoaded(@NonNull OfflinePlayer player) { default ChatUser wrapIfLoaded(@NonNull final OfflinePlayer player) {
return this.wrapIfLoaded(player.getUniqueId()); return this.wrapIfLoaded(player.getUniqueId());
} }
@@ -52,7 +52,7 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
this.carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat"); this.carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
} }
public CarbonChatUser(@NonNull UUID uuid) { public CarbonChatUser(@NonNull final UUID uuid) {
this(); this();
this.uuid = uuid; this.uuid = uuid;
} }
@@ -60,61 +60,61 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
@Override @Override
@NonNull @NonNull
public Iterable<@NonNull ? extends Audience> audiences() { public Iterable<@NonNull ? extends Audience> audiences() {
return Collections.singleton(carbonChat.getAdventureManager().audiences().player(uuid)); return Collections.singleton(this.carbonChat.adventureManager().audiences().player(this.uuid));
} }
@Override @Override
@Nullable @Nullable
public Player player() { public Player player() {
return Bukkit.getPlayer(uuid); return Bukkit.getPlayer(this.uuid);
} }
@Override @Override
@NonNull @NonNull
public OfflinePlayer offlinePlayer() { public OfflinePlayer offlinePlayer() {
return Bukkit.getOfflinePlayer(uuid); return Bukkit.getOfflinePlayer(this.uuid);
} }
@Override @Override
public boolean online() { public boolean online() {
return offlinePlayer().isOnline(); return this.offlinePlayer().isOnline();
} }
@Override @Override
@NonNull @NonNull
public UUID uuid() { public UUID uuid() {
return uuid; return this.uuid;
} }
@Override @Override
@Nullable @Nullable
public String nickname() { public String nickname() {
return nickname; return this.nickname;
} }
@Override @Override
public void nickname(@Nullable String newNickname, boolean fromRemote) { public void nickname(@Nullable String newNickname, final boolean fromRemote) {
this.nickname = newNickname; this.nickname = newNickname;
if (online()) { if (this.online()) {
if (newNickname != null) { if (newNickname != null) {
Component component = this.carbonChat.getAdventureManager().processMessage(nickname); final Component component = this.carbonChat.adventureManager().processMessage(this.nickname);
newNickname = CarbonChat.LEGACY.serialize(component); newNickname = this.carbonChat.LEGACY.serialize(component);
} }
this.player().setDisplayName(newNickname); this.player().setDisplayName(newNickname);
if (carbonChat.getConfig().getBoolean("nicknames-set-tab-name")) { if (this.carbonChat.getConfig().getBoolean("nicknames-set-tab-name")) {
this.player().setPlayerListName(newNickname); this.player().setPlayerListName(newNickname);
} }
} }
if (!fromRemote) { if (!fromRemote) {
if (nickname == null) { if (this.nickname == null) {
this.carbonChat.getMessageManager().sendMessage("nickname-reset", this.uuid(), (byteArray) -> { this.carbonChat.messageManager().sendMessage("nickname-reset", this.uuid(), byteArray -> {
}); });
} else { } else {
this.carbonChat.getMessageManager().sendMessage("nickname", this.uuid(), (byteArray) -> { this.carbonChat.messageManager().sendMessage("nickname", this.uuid(), byteArray -> {
byteArray.writeUTF(this.nickname); byteArray.writeUTF(this.nickname);
}); });
} }
@@ -124,19 +124,19 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
@Override @Override
@Nullable @Nullable
public ChatChannel selectedChannel() { public ChatChannel selectedChannel() {
return this.carbonChat.getChannelManager().channelOrDefault(selectedChannel); return this.carbonChat.channelManager().channelOrDefault(this.selectedChannel);
} }
@Override @Override
public void selectedChannel(@NonNull ChatChannel chatChannel, boolean fromRemote) { public void selectedChannel(@NonNull final ChatChannel chatChannel, final boolean fromRemote) {
String failureMessage = chatChannel.switchFailureMessage(); final String failureMessage = chatChannel.switchFailureMessage();
ChannelSwitchEvent event = new ChannelSwitchEvent(chatChannel, this, failureMessage); final ChannelSwitchEvent event = new ChannelSwitchEvent(chatChannel, this, failureMessage);
Bukkit.getPluginManager().callEvent(event); Bukkit.getPluginManager().callEvent(event);
if (event.isCancelled()) { if (event.isCancelled()) {
sendMessage(carbonChat.getAdventureManager().processMessage(event.failureMessage(), this.sendMessage(this.carbonChat.adventureManager().processMessage(event.failureMessage(),
"channel", chatChannel.name())); "channel", chatChannel.name()));
return; return;
@@ -145,7 +145,7 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
this.selectedChannel = chatChannel.key(); this.selectedChannel = chatChannel.key();
if (!fromRemote) { if (!fromRemote) {
this.carbonChat.getMessageManager().sendMessage("selected-channel", this.uuid(), (byteArray) -> { this.carbonChat.messageManager().sendMessage("selected-channel", this.uuid(), byteArray -> {
byteArray.writeUTF(chatChannel.key()); byteArray.writeUTF(chatChannel.key());
}); });
} }
@@ -153,24 +153,24 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
@Override @Override
public void clearSelectedChannel() { public void clearSelectedChannel() {
selectedChannel(carbonChat.getChannelManager().defaultChannel()); this.selectedChannel(this.carbonChat.channelManager().defaultChannel());
} }
@Override @Override
public boolean ignoringUser(@NonNull UUID uuid) { public boolean ignoringUser(@NonNull final UUID uuid) {
return ignoredUsers.contains(uuid); return this.ignoredUsers.contains(uuid);
} }
@Override @Override
public void ignoringUser(@NonNull UUID uuid, boolean ignoring, boolean fromRemote) { public void ignoringUser(@NonNull final UUID uuid, final boolean ignoring, final boolean fromRemote) {
if (ignoring) { if (ignoring) {
ignoredUsers.add(uuid); this.ignoredUsers.add(uuid);
} else { } else {
ignoredUsers.remove(uuid); this.ignoredUsers.remove(uuid);
} }
if (!fromRemote) { if (!fromRemote) {
this.carbonChat.getMessageManager().sendMessage("ignoring-user", this.uuid(), (byteArray) -> { this.carbonChat.messageManager().sendMessage("ignoring-user", this.uuid(), byteArray -> {
byteArray.writeLong(uuid.getMostSignificantBits()); byteArray.writeLong(uuid.getMostSignificantBits());
byteArray.writeLong(uuid.getLeastSignificantBits()); byteArray.writeLong(uuid.getLeastSignificantBits());
byteArray.writeBoolean(ignoring); byteArray.writeBoolean(ignoring);
@@ -179,16 +179,16 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
} }
@NonNull @NonNull
public List<@NonNull UUID> getIgnoredUsers() { public List<@NonNull UUID> ignoredUsers() {
return ignoredUsers; return this.ignoredUsers;
} }
@Override @Override
public void muted(boolean muted, boolean fromRemote) { public void muted(final boolean muted, final boolean fromRemote) {
this.muted = muted; this.muted = muted;
if (!fromRemote) { if (!fromRemote) {
this.carbonChat.getMessageManager().sendMessage("muted", this.uuid(), (byteArray) -> { this.carbonChat.messageManager().sendMessage("muted", this.uuid(), byteArray -> {
byteArray.writeBoolean(muted); byteArray.writeBoolean(muted);
}); });
} }
@@ -196,15 +196,15 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
@Override @Override
public boolean muted() { public boolean muted() {
return muted; return this.muted;
} }
@Override @Override
public void shadowMuted(boolean shadowMuted, boolean fromRemote) { public void shadowMuted(final boolean shadowMuted, final boolean fromRemote) {
this.shadowMuted = shadowMuted; this.shadowMuted = shadowMuted;
if (!fromRemote) { if (!fromRemote) {
this.carbonChat.getMessageManager().sendMessage("shadow-muted", this.uuid(), (byteArray) -> { this.carbonChat.messageManager().sendMessage("shadow-muted", this.uuid(), byteArray -> {
byteArray.writeBoolean(shadowMuted); byteArray.writeBoolean(shadowMuted);
}); });
} }
@@ -212,21 +212,21 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
@Override @Override
public boolean shadowMuted() { public boolean shadowMuted() {
return shadowMuted; return this.shadowMuted;
} }
@Override @Override
@Nullable @Nullable
public UUID replyTarget() { public UUID replyTarget() {
return replyTarget; return this.replyTarget;
} }
@Override @Override
public void replyTarget(@Nullable UUID target, boolean fromRemote) { public void replyTarget(@Nullable final UUID target, final boolean fromRemote) {
this.replyTarget = target; this.replyTarget = target;
if (!fromRemote) { if (!fromRemote) {
this.carbonChat.getMessageManager().sendMessage("reply-target", this.uuid(), (byteArray) -> { this.carbonChat.messageManager().sendMessage("reply-target", this.uuid(), byteArray -> {
byteArray.writeLong(target.getMostSignificantBits()); byteArray.writeLong(target.getMostSignificantBits());
byteArray.writeLong(target.getLeastSignificantBits()); byteArray.writeLong(target.getLeastSignificantBits());
}); });
@@ -235,23 +235,23 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
@Override @Override
@NonNull @NonNull
public UserChannelSettings channelSettings(@NonNull ChatChannel channel) { public UserChannelSettings channelSettings(@NonNull final ChatChannel channel) {
return channelSettings.computeIfAbsent(channel.key(), (name) -> { return this.channelSettings.computeIfAbsent(channel.key(), name -> {
return new SimpleUserChannelSettings(uuid, channel.key()); return new SimpleUserChannelSettings(this.uuid, channel.key());
}); });
} }
@NonNull @NonNull
public Map<@NonNull String, @NonNull ? extends UserChannelSettings> getChannelSettings() { public Map<@NonNull String, @NonNull ? extends UserChannelSettings> channelSettings() {
return channelSettings; return this.channelSettings;
} }
@Override @Override
public void spyingWhispers(boolean spyingWhispers, boolean fromRemote) { public void spyingWhispers(final boolean spyingWhispers, final boolean fromRemote) {
this.spyingWhispers = spyingWhispers; this.spyingWhispers = spyingWhispers;
if (!fromRemote) { if (!fromRemote) {
this.carbonChat.getMessageManager().sendMessage("spying-whispers", this.uuid(), (byteArray) -> { this.carbonChat.messageManager().sendMessage("spying-whispers", this.uuid(), byteArray -> {
byteArray.writeBoolean(spyingWhispers); byteArray.writeBoolean(spyingWhispers);
}); });
} }
@@ -259,23 +259,23 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
@Override @Override
public boolean spyingwhispers() { public boolean spyingwhispers() {
return spyingWhispers; return this.spyingWhispers;
} }
@Override @Override
public void sendMessage(@NonNull ChatUser sender, @NonNull String message) { public void sendMessage(@NonNull final ChatUser sender, @NonNull final String message) {
if (ignoringUser(sender) || sender.ignoringUser(this)) { if (this.ignoringUser(sender) || sender.ignoringUser(this)) {
return; return;
} }
String toPlayerFormat = this.carbonChat.getLanguage().getString("message-to-other"); final String toPlayerFormat = this.carbonChat.language().getString("message-to-other");
String fromPlayerFormat = this.carbonChat.getLanguage().getString("message-from-other"); final String fromPlayerFormat = this.carbonChat.language().getString("message-from-other");
String senderName = sender.offlinePlayer().getName(); String senderName = sender.offlinePlayer().getName();
String senderOfflineName = senderName; final String senderOfflineName = senderName;
String targetName = this.offlinePlayer().getName(); String targetName = this.offlinePlayer().getName();
String targetOfflineName = targetName; final String targetOfflineName = targetName;
if (sender.online()) { if (sender.online()) {
senderName = sender.player().getDisplayName(); senderName = sender.player().getDisplayName();
@@ -285,17 +285,17 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
targetName = this.player().getDisplayName(); targetName = this.player().getDisplayName();
} }
Component toPlayerComponent = this.carbonChat.getAdventureManager().processMessage(toPlayerFormat, "br", "\n", final Component toPlayerComponent = this.carbonChat.adventureManager().processMessage(toPlayerFormat, "br", "\n",
"message", message, "message", message,
"targetname", targetOfflineName, "sendername", senderOfflineName, "targetname", targetOfflineName, "sendername", senderOfflineName,
"target", targetName, "sender", senderName); "target", targetName, "sender", senderName);
Component fromPlayerComponent = this.carbonChat.getAdventureManager().processMessage(fromPlayerFormat, "br", "\n", final Component fromPlayerComponent = this.carbonChat.adventureManager().processMessage(fromPlayerFormat, "br", "\n",
"message", message, "message", message,
"targetname", targetOfflineName, "sendername", senderOfflineName, "targetname", targetOfflineName, "sendername", senderOfflineName,
"target", targetName, "sender", senderName); "target", targetName, "sender", senderName);
PrivateMessageEvent event = new PrivateMessageEvent(sender, this, toPlayerComponent, fromPlayerComponent, message); final PrivateMessageEvent event = new PrivateMessageEvent(sender, this, toPlayerComponent, fromPlayerComponent, message);
Bukkit.getPluginManager().callEvent(event); Bukkit.getPluginManager().callEvent(event);
@@ -316,11 +316,11 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
sender.replyTarget(this); sender.replyTarget(this);
this.replyTarget(sender); this.replyTarget(sender);
if (carbonChat.getConfig().getBoolean("pings.on-whisper")) { if (this.carbonChat.getConfig().getBoolean("pings.on-whisper")) {
Key key = Key.of(carbonChat.getConfig().getString("pings.sound")); final Key key = Key.of(this.carbonChat.getConfig().getString("pings.sound"));
Sound.Source source = Sound.Source.valueOf(carbonChat.getConfig().getString("pings.source")); final Sound.Source source = Sound.Source.valueOf(this.carbonChat.getConfig().getString("pings.source"));
float volume = (float) this.carbonChat.getConfig().getDouble("pings.volume"); final float volume = (float) this.carbonChat.getConfig().getDouble("pings.volume");
float pitch = (float) this.carbonChat.getConfig().getDouble("pings.pitch"); final float pitch = (float) this.carbonChat.getConfig().getDouble("pings.pitch");
this.playSound(Sound.of(key, source, volume, pitch)); this.playSound(Sound.of(key, source, volume, pitch));
} }
@@ -329,10 +329,10 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
final String targetNameFinal = targetName; final String targetNameFinal = targetName;
final String senderNameFinal = senderName; final String senderNameFinal = senderName;
if (!carbonChat.isBungeeEnabled()) { if (!this.carbonChat.bungeeEnabled()) {
String playerOfflineFormat = this.carbonChat.getLanguage().getString("other-player-offline"); final String playerOfflineFormat = this.carbonChat.language().getString("other-player-offline");
Component playerOfflineComponent = this.carbonChat.getAdventureManager().processMessage(playerOfflineFormat, final Component playerOfflineComponent = this.carbonChat.adventureManager().processMessage(playerOfflineFormat,
"br", "\n", "br", "\n",
"message", message, "message", message,
"targetname", targetOfflineName, "sendername", senderOfflineName, "targetname", targetOfflineName, "sendername", senderOfflineName,
@@ -343,11 +343,11 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
return; return;
} }
BungeeChannelApi.of(carbonChat).getPlayerList("ALL").thenAccept(list -> { BungeeChannelApi.of(this.carbonChat).getPlayerList("ALL").thenAccept(list -> {
if (!list.contains(this.offlinePlayer().getName())) { if (!list.contains(this.offlinePlayer().getName())) {
String playerOfflineFormat = this.carbonChat.getLanguage().getString("other-player-offline"); final String playerOfflineFormat = this.carbonChat.language().getString("other-player-offline");
Component playerOfflineComponent = this.carbonChat.getAdventureManager().processMessage(playerOfflineFormat, final Component playerOfflineComponent = this.carbonChat.adventureManager().processMessage(playerOfflineFormat,
"br", "\n", "br", "\n",
"message", message, "message", message,
"targetname", targetOfflineName, "sendername", senderOfflineName, "targetname", targetOfflineName, "sendername", senderOfflineName,
@@ -360,26 +360,26 @@ public class CarbonChatUser implements ChatUser, ForwardingAudience {
sender.sendMessage(toPlayerComponent); sender.sendMessage(toPlayerComponent);
this.carbonChat.getMessageManager().sendMessage("whisper-component", sender.uuid(), (byteArray) -> { this.carbonChat.messageManager().sendMessage("whisper-component", sender.uuid(), byteArray -> {
byteArray.writeLong(this.uuid().getMostSignificantBits()); byteArray.writeLong(this.uuid().getMostSignificantBits());
byteArray.writeLong(this.uuid().getLeastSignificantBits()); byteArray.writeLong(this.uuid().getLeastSignificantBits());
byteArray.writeUTF(carbonChat.getAdventureManager().audiences().gsonSerializer().serialize(fromPlayerComponent)); byteArray.writeUTF(this.carbonChat.adventureManager().audiences().gsonSerializer().serialize(fromPlayerComponent));
}); });
}); });
} }
for (Player player : Bukkit.getOnlinePlayers()) { for (final Player player : Bukkit.getOnlinePlayers()) {
ChatUser user = this.carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
if (!user.spyingwhispers()) { if (!user.spyingwhispers()) {
continue; continue;
} }
if (user.uuid().equals(sender.uuid()) || user.uuid().equals(uuid())) { if (user.uuid().equals(sender.uuid()) || user.uuid().equals(this.uuid())) {
continue; continue;
} }
user.sendMessage(carbonChat.getAdventureManager().processMessage(carbonChat.getLanguage().getString("spy-whispers"), user.sendMessage(this.carbonChat.adventureManager().processMessage(this.carbonChat.language().getString("spy-whispers"),
"br", "\n", "message", message, "br", "\n", "message", message,
"targetname", targetOfflineName, "sendername", senderOfflineName, "targetname", targetOfflineName, "sendername", senderOfflineName,
"target", targetName, "sender", senderName)); "target", targetName, "sender", senderName));
@@ -155,7 +155,7 @@ public class MySQLUserService implements UserService {
final List<DbRow> channelSettings = this.database.getResults("SELECT * from sc_channel_settings WHERE uuid = ?;", uuid.toString()); final List<DbRow> channelSettings = this.database.getResults("SELECT * from sc_channel_settings WHERE uuid = ?;", uuid.toString());
final List<DbRow> ignoredUsers = this.database.getResults("SELECT * from sc_ignored_users WHERE uuid = ?;", uuid.toString()); final List<DbRow> ignoredUsers = this.database.getResults("SELECT * from sc_ignored_users WHERE uuid = ?;", uuid.toString());
final ChatChannel channel = this.carbonChat.getChannelManager().channelOrDefault(users.getString("channel")); final ChatChannel channel = this.carbonChat.channelManager().channelOrDefault(users.getString("channel"));
if (channel != null) { if (channel != null) {
user.selectedChannel(channel, true); user.selectedChannel(channel, true);
@@ -172,7 +172,7 @@ public class MySQLUserService implements UserService {
user.spyingWhispers(users.<Boolean>get("spyingwhispers"), true); user.spyingWhispers(users.<Boolean>get("spyingwhispers"), true);
for (final DbRow channelSetting : channelSettings) { for (final DbRow channelSetting : channelSettings) {
final ChatChannel chatChannel = this.carbonChat.getChannelManager().registry().channel(channelSetting.getString("channel")); final ChatChannel chatChannel = this.carbonChat.channelManager().registry().channel(channelSetting.getString("channel"));
if (chatChannel != null) { if (chatChannel != null) {
final UserChannelSettings settings = user.channelSettings(chatChannel); final UserChannelSettings settings = user.channelSettings(chatChannel);
@@ -217,7 +217,7 @@ public class MySQLUserService implements UserService {
this.carbonChat.getLogger().info("Saving user channel settings!"); this.carbonChat.getLogger().info("Saving user channel settings!");
// Save user channel settings // Save user channel settings
for (final Map.Entry<String, ? extends UserChannelSettings> entry : user.getChannelSettings().entrySet()) { for (final Map.Entry<String, ? extends UserChannelSettings> entry : user.channelSettings().entrySet()) {
final UserChannelSettings value = entry.getValue(); final UserChannelSettings value = entry.getValue();
String colorString = null; String colorString = null;
@@ -237,7 +237,7 @@ public class MySQLUserService implements UserService {
// TODO: keep DB up to date with settings as settings are mutated // TODO: keep DB up to date with settings as settings are mutated
stm.executeUpdateQuery("DELETE FROM sc_ignored_users WHERE uuid = ?", user.uuid().toString()); stm.executeUpdateQuery("DELETE FROM sc_ignored_users WHERE uuid = ?", user.uuid().toString());
for (final UUID entry : user.getIgnoredUsers()) { for (final UUID entry : user.ignoredUsers()) {
stm.executeUpdateQuery("INSERT INTO sc_ignored_users (uuid, user) VALUES (?, ?)", stm.executeUpdateQuery("INSERT INTO sc_ignored_users (uuid, user) VALUES (?, ?)",
user.uuid().toString(), entry.toString()); user.uuid().toString(), entry.toString());
} }
@@ -36,7 +36,7 @@ public class SimpleUserChannelSettings implements UserChannelSettings {
@NonNull @NonNull
private CarbonChatUser user() { private CarbonChatUser user() {
return (CarbonChatUser) this.carbonChat.getUserService().wrap(this.uuid); return (CarbonChatUser) this.carbonChat.userService().wrap(this.uuid);
} }
@Override @Override
@@ -49,7 +49,7 @@ public class SimpleUserChannelSettings implements UserChannelSettings {
this.spying = spying; this.spying = spying;
if (!fromRemote) { if (!fromRemote) {
this.carbonChat.getMessageManager().sendMessage("spying-channel", this.uuid, byteArray -> { this.carbonChat.messageManager().sendMessage("spying-channel", this.uuid, byteArray -> {
byteArray.writeUTF(this.channel); byteArray.writeUTF(this.channel);
byteArray.writeBoolean(spying); byteArray.writeBoolean(spying);
}); });
@@ -66,7 +66,7 @@ public class SimpleUserChannelSettings implements UserChannelSettings {
this.ignored = ignored; this.ignored = ignored;
if (!fromRemote) { if (!fromRemote) {
this.carbonChat.getMessageManager().sendMessage("ignoring-channel", this.uuid, byteArray -> { this.carbonChat.messageManager().sendMessage("ignoring-channel", this.uuid, byteArray -> {
byteArray.writeUTF(this.channel); byteArray.writeUTF(this.channel);
byteArray.writeBoolean(ignored); byteArray.writeBoolean(ignored);
}); });
@@ -92,7 +92,7 @@ public class SimpleUserChannelSettings implements UserChannelSettings {
} }
if (!fromRemote) { if (!fromRemote) {
this.carbonChat.getMessageManager().sendMessage("channel-color", this.uuid, byteArray -> { this.carbonChat.messageManager().sendMessage("channel-color", this.uuid, byteArray -> {
byteArray.writeUTF(color.asHexString()); byteArray.writeUTF(color.asHexString());
}); });
} }
@@ -48,43 +48,43 @@ public class CarbonPlaceholders extends PlaceholderExpansion {
if (key.startsWith("can_use_")) { if (key.startsWith("can_use_")) {
final String value = key.replace("can_use_", ""); final String value = key.replace("can_use_", "");
final ChatChannel channel = this.carbonChat.getChannelManager().registry().channel(value); final ChatChannel channel = this.carbonChat.channelManager().registry().channel(value);
if (channel == null) { if (channel == null) {
return "false"; return "false";
} }
final ChatUser user = this.carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
return String.valueOf(channel.canPlayerUse(user)); return String.valueOf(channel.canPlayerUse(user));
} else if (key.startsWith("can_see_")) { } else if (key.startsWith("can_see_")) {
final String value = key.replace("can_see_", ""); final String value = key.replace("can_see_", "");
final ChatChannel channel = this.carbonChat.getChannelManager().registry().channel(value); final ChatChannel channel = this.carbonChat.channelManager().registry().channel(value);
if (channel == null) { if (channel == null) {
return "false"; return "false";
} }
final ChatUser user = this.carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
return String.valueOf(channel.canPlayerSee(user, true)); return String.valueOf(channel.canPlayerSee(user, true));
} else if (key.startsWith("ignoring_channel_")) { } else if (key.startsWith("ignoring_channel_")) {
final String value = key.replace("ignoring_channel_", ""); final String value = key.replace("ignoring_channel_", "");
final ChatChannel channel = this.carbonChat.getChannelManager().registry().channel(value); final ChatChannel channel = this.carbonChat.channelManager().registry().channel(value);
if (channel == null) { if (channel == null) {
return "false"; return "false";
} }
final ChatUser user = this.carbonChat.getUserService().wrap(player); final ChatUser user = this.carbonChat.userService().wrap(player);
return String.valueOf(user.channelSettings(channel).ignored()); return String.valueOf(user.channelSettings(channel).ignored());
} else if (key.startsWith("selected_channel")) { } else if (key.startsWith("selected_channel")) {
final ChatChannel channel = this.carbonChat.getUserService().wrap(player).selectedChannel(); final ChatChannel channel = this.carbonChat.userService().wrap(player).selectedChannel();
return channel == null ? this.carbonChat.getChannelManager().defaultChannel().name() : channel.name(); return channel == null ? this.carbonChat.channelManager().defaultChannel().name() : channel.name();
} }
return null; return null;
@@ -139,7 +139,7 @@ public final class CarbonUtils {
throw new CustomArgument.CustomArgumentException("Invalid player for input (" + input + ")"); throw new CustomArgument.CustomArgumentException("Invalid player for input (" + input + ")");
} }
return carbonChat.getUserService().wrap(player); return carbonChat.userService().wrap(player);
// }).overrideSuggestions((sender, args) -> { // }).overrideSuggestions((sender, args) -> {
// ArrayList<String> players = new ArrayList<>(); // ArrayList<String> players = new ArrayList<>();
// //
@@ -156,7 +156,7 @@ public final class CarbonUtils {
return new CustomArgument<>(input -> { return new CustomArgument<>(input -> {
final CarbonChat carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat"); final CarbonChat carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
return carbonChat.getUserService().wrap(input); return carbonChat.userService().wrap(input);
// }).overrideSuggestions((sender, args) -> { // }).overrideSuggestions((sender, args) -> {
// ArrayList<String> players = new ArrayList<>(); // ArrayList<String> players = new ArrayList<>();
// //
@@ -186,7 +186,7 @@ public final class CarbonUtils {
return new CustomArgument<>(input -> { return new CustomArgument<>(input -> {
final CarbonChat carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat"); final CarbonChat carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
final ChatChannel channel = carbonChat.getChannelManager().registry().channel(input); final ChatChannel channel = carbonChat.channelManager().registry().channel(input);
if (channel == null) { if (channel == null) {
throw new CustomArgument.CustomArgumentException("Invalid channel for input (" + input + ")"); throw new CustomArgument.CustomArgumentException("Invalid channel for input (" + input + ")");
@@ -92,7 +92,7 @@ public class Metrics {
* @param pluginId The id of the plugin. * @param pluginId The id of the plugin.
* It can be found at <a href="https://bstats.org/what-is-my-plugin-id">What is my plugin id?</a> * It can be found at <a href="https://bstats.org/what-is-my-plugin-id">What is my plugin id?</a>
*/ */
public Metrics(Plugin plugin, int pluginId) { public Metrics(final Plugin plugin, final int pluginId) {
if (plugin == null) { if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null!"); throw new IllegalArgumentException("Plugin cannot be null!");
} }
@@ -100,9 +100,9 @@ public class Metrics {
this.pluginId = pluginId; this.pluginId = pluginId;
// Get the config file // Get the config file
File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); final File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
File configFile = new File(bStatsFolder, "config.yml"); final File configFile = new File(bStatsFolder, "config.yml");
YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); final YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);
// Check if the config file exists // Check if the config file exists
if (!config.isSet("serverUuid")) { if (!config.isSet("serverUuid")) {
@@ -127,33 +127,33 @@ public class Metrics {
).copyDefaults(true); ).copyDefaults(true);
try { try {
config.save(configFile); config.save(configFile);
} catch (IOException ignored) { } catch (final IOException ignored) {
} }
} }
// Load the data // Load the data
enabled = config.getBoolean("enabled", true); this.enabled = config.getBoolean("enabled", true);
serverUUID = config.getString("serverUuid"); serverUUID = config.getString("serverUuid");
logFailedRequests = config.getBoolean("logFailedRequests", false); logFailedRequests = config.getBoolean("logFailedRequests", false);
logSentData = config.getBoolean("logSentData", false); logSentData = config.getBoolean("logSentData", false);
logResponseStatusText = config.getBoolean("logResponseStatusText", false); logResponseStatusText = config.getBoolean("logResponseStatusText", false);
if (enabled) { if (this.enabled) {
boolean found = false; boolean found = false;
// Search for all other bStats Metrics classes to see if we are the first one // Search for all other bStats Metrics classes to see if we are the first one
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) { for (final Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try { try {
service.getField("B_STATS_VERSION"); // Our identifier :) service.getField("B_STATS_VERSION"); // Our identifier :)
found = true; // We aren't the first found = true; // We aren't the first
break; break;
} catch (NoSuchFieldException ignored) { } catch (final NoSuchFieldException ignored) {
} }
} }
// Register our service // Register our service
Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal); Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal);
if (!found) { if (!found) {
// We are the first! // We are the first!
startSubmitting(); this.startSubmitting();
} }
} }
} }
@@ -164,7 +164,7 @@ public class Metrics {
* @return Whether bStats is enabled or not. * @return Whether bStats is enabled or not.
*/ */
public boolean isEnabled() { public boolean isEnabled() {
return enabled; return this.enabled;
} }
/** /**
@@ -172,11 +172,11 @@ public class Metrics {
* *
* @param chart The chart to add. * @param chart The chart to add.
*/ */
public void addCustomChart(CustomChart chart) { public void addCustomChart(final CustomChart chart) {
if (chart == null) { if (chart == null) {
throw new IllegalArgumentException("Chart cannot be null!"); throw new IllegalArgumentException("Chart cannot be null!");
} }
charts.add(chart); this.charts.add(chart);
} }
/** /**
@@ -187,13 +187,13 @@ public class Metrics {
timer.scheduleAtFixedRate(new TimerTask() { timer.scheduleAtFixedRate(new TimerTask() {
@Override @Override
public void run() { public void run() {
if (!plugin.isEnabled()) { // Plugin was disabled if (!Metrics.this.plugin.isEnabled()) { // Plugin was disabled
timer.cancel(); timer.cancel();
return; return;
} }
// Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
// Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;) // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
Bukkit.getScheduler().runTask(plugin, () -> submitData()); Bukkit.getScheduler().runTask(Metrics.this.plugin, () -> Metrics.this.submitData());
} }
}, 1000 * 60 * 5, 1000 * 60 * 30); }, 1000 * 60 * 5, 1000 * 60 * 30);
// Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
@@ -208,18 +208,18 @@ public class Metrics {
* @return The plugin specific data. * @return The plugin specific data.
*/ */
public JsonObject getPluginData() { public JsonObject getPluginData() {
JsonObject data = new JsonObject(); final JsonObject data = new JsonObject();
String pluginName = plugin.getDescription().getName(); final String pluginName = this.plugin.getDescription().getName();
String pluginVersion = plugin.getDescription().getVersion(); final String pluginVersion = this.plugin.getDescription().getVersion();
data.addProperty("pluginName", pluginName); // Append the name of the plugin data.addProperty("pluginName", pluginName); // Append the name of the plugin
data.addProperty("id", pluginId); // Append the id of the plugin data.addProperty("id", this.pluginId); // Append the id of the plugin
data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin
JsonArray customCharts = new JsonArray(); final JsonArray customCharts = new JsonArray();
for (CustomChart customChart : charts) { for (final CustomChart customChart : this.charts) {
// Add the data of the custom charts // Add the data of the custom charts
JsonObject chart = customChart.getRequestJsonObject(); final JsonObject chart = customChart.getRequestJsonObject();
if (chart == null) { // If the chart is null, we skip it if (chart == null) { // If the chart is null, we skip it
continue; continue;
} }
@@ -241,25 +241,25 @@ public class Metrics {
try { try {
// Around MC 1.8 the return type was changed to a collection from an array, // Around MC 1.8 the return type was changed to a collection from an array,
// This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; // This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;
Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); final Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers");
playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class) playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class)
? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size() ? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()
: ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
} catch (Exception e) { } catch (final Exception e) {
playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed
} }
int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; final int onlineMode = Bukkit.getOnlineMode() ? 1 : 0;
String bukkitVersion = Bukkit.getVersion(); final String bukkitVersion = Bukkit.getVersion();
String bukkitName = Bukkit.getName(); final String bukkitName = Bukkit.getName();
// OS/Java specific data // OS/Java specific data
String javaVersion = System.getProperty("java.version"); final String javaVersion = System.getProperty("java.version");
String osName = System.getProperty("os.name"); final String osName = System.getProperty("os.name");
String osArch = System.getProperty("os.arch"); final String osArch = System.getProperty("os.arch");
String osVersion = System.getProperty("os.version"); final String osVersion = System.getProperty("os.version");
int coreCount = Runtime.getRuntime().availableProcessors(); final int coreCount = Runtime.getRuntime().availableProcessors();
JsonObject data = new JsonObject(); final JsonObject data = new JsonObject();
data.addProperty("serverUUID", serverUUID); data.addProperty("serverUUID", serverUUID);
@@ -281,40 +281,40 @@ public class Metrics {
* Collects the data and sends it afterwards. * Collects the data and sends it afterwards.
*/ */
private void submitData() { private void submitData() {
final JsonObject data = getServerData(); final JsonObject data = this.getServerData();
JsonArray pluginData = new JsonArray(); final JsonArray pluginData = new JsonArray();
// Search for all other bStats Metrics classes to get their plugin data // Search for all other bStats Metrics classes to get their plugin data
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) { for (final Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try { try {
service.getField("B_STATS_VERSION"); // Our identifier :) service.getField("B_STATS_VERSION"); // Our identifier :)
for (RegisteredServiceProvider<?> provider : Bukkit.getServicesManager().getRegistrations(service)) { for (final RegisteredServiceProvider<?> provider : Bukkit.getServicesManager().getRegistrations(service)) {
try { try {
Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider()); final Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider());
if (plugin instanceof JsonObject) { if (plugin instanceof JsonObject) {
pluginData.add((JsonObject) plugin); pluginData.add((JsonObject) plugin);
} else { // old bstats version compatibility } else { // old bstats version compatibility
try { try {
Class<?> jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject"); final Class<?> jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject");
if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) { if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) {
Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString"); final Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString");
jsonStringGetter.setAccessible(true); jsonStringGetter.setAccessible(true);
String jsonString = (String) jsonStringGetter.invoke(plugin); final String jsonString = (String) jsonStringGetter.invoke(plugin);
JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject(); final JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject();
pluginData.add(object); pluginData.add(object);
} }
} catch (ClassNotFoundException e) { } catch (final ClassNotFoundException e) {
// minecraft version 1.14+ // minecraft version 1.14+
if (logFailedRequests) { if (logFailedRequests) {
this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception", e); this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception", e);
} }
} }
} }
} catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { } catch (final NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) {
} }
} }
} catch (NoSuchFieldException ignored) { } catch (final NoSuchFieldException ignored) {
} }
} }
@@ -324,11 +324,11 @@ public class Metrics {
new Thread(() -> { new Thread(() -> {
try { try {
// Send the data // Send the data
sendData(plugin, data); sendData(this.plugin, data);
} catch (Exception e) { } catch (final Exception e) {
// Something went wrong! :( // Something went wrong! :(
if (logFailedRequests) { if (logFailedRequests) {
plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); this.plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + this.plugin.getName(), e);
} }
} }
}).start(); }).start();
@@ -341,7 +341,7 @@ public class Metrics {
* @param data The data to send. * @param data The data to send.
* @throws Exception If the request failed. * @throws Exception If the request failed.
*/ */
private static void sendData(Plugin plugin, JsonObject data) throws Exception { private static void sendData(final Plugin plugin, final JsonObject data) throws Exception {
if (data == null) { if (data == null) {
throw new IllegalArgumentException("Data cannot be null!"); throw new IllegalArgumentException("Data cannot be null!");
} }
@@ -351,10 +351,10 @@ public class Metrics {
if (logSentData) { if (logSentData) {
plugin.getLogger().info("Sending data to bStats: " + data); plugin.getLogger().info("Sending data to bStats: " + data);
} }
HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); final HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
// Compress the data to save bandwidth // Compress the data to save bandwidth
byte[] compressedData = compress(data.toString()); final byte[] compressedData = compress(data.toString());
// Add headers // Add headers
connection.setRequestMethod("POST"); connection.setRequestMethod("POST");
@@ -367,12 +367,12 @@ public class Metrics {
// Send data // Send data
connection.setDoOutput(true); connection.setDoOutput(true);
try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { try (final DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
outputStream.write(compressedData); outputStream.write(compressedData);
} }
StringBuilder builder = new StringBuilder(); final StringBuilder builder = new StringBuilder();
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { try (final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String line; String line;
while ((line = bufferedReader.readLine()) != null) { while ((line = bufferedReader.readLine()) != null) {
builder.append(line); builder.append(line);
@@ -395,8 +395,8 @@ public class Metrics {
if (str == null) { if (str == null) {
return null; return null;
} }
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { try (final GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) {
gzip.write(str.getBytes(StandardCharsets.UTF_8)); gzip.write(str.getBytes(StandardCharsets.UTF_8));
} }
return outputStream.toByteArray(); return outputStream.toByteArray();
@@ -415,7 +415,7 @@ public class Metrics {
* *
* @param chartId The id of the chart. * @param chartId The id of the chart.
*/ */
CustomChart(String chartId) { CustomChart(final String chartId) {
if (chartId == null || chartId.isEmpty()) { if (chartId == null || chartId.isEmpty()) {
throw new IllegalArgumentException("ChartId cannot be null or empty!"); throw new IllegalArgumentException("ChartId cannot be null or empty!");
} }
@@ -423,18 +423,18 @@ public class Metrics {
} }
private JsonObject getRequestJsonObject() { private JsonObject getRequestJsonObject() {
JsonObject chart = new JsonObject(); final JsonObject chart = new JsonObject();
chart.addProperty("chartId", chartId); chart.addProperty("chartId", this.chartId);
try { try {
JsonObject data = getChartData(); final JsonObject data = this.getChartData();
if (data == null) { if (data == null) {
// If the data is null we don't send the chart. // If the data is null we don't send the chart.
return null; return null;
} }
chart.add("data", data); chart.add("data", data);
} catch (Throwable t) { } catch (final Throwable t) {
if (logFailedRequests) { if (logFailedRequests) {
Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t); Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + this.chartId, t);
} }
return null; return null;
} }
@@ -458,15 +458,15 @@ public class Metrics {
* @param chartId The id of the chart. * @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data. * @param callable The callable which is used to request the chart data.
*/ */
public SimplePie(String chartId, Callable<String> callable) { public SimplePie(final String chartId, final Callable<String> callable) {
super(chartId); super(chartId);
this.callable = callable; this.callable = callable;
} }
@Override @Override
protected JsonObject getChartData() throws Exception { protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject(); final JsonObject data = new JsonObject();
String value = callable.call(); final String value = this.callable.call();
if (value == null || value.isEmpty()) { if (value == null || value.isEmpty()) {
// Null = skip the chart // Null = skip the chart
return null; return null;
@@ -489,22 +489,22 @@ public class Metrics {
* @param chartId The id of the chart. * @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data. * @param callable The callable which is used to request the chart data.
*/ */
public AdvancedPie(String chartId, Callable<Map<String, Integer>> callable) { public AdvancedPie(final String chartId, final Callable<Map<String, Integer>> callable) {
super(chartId); super(chartId);
this.callable = callable; this.callable = callable;
} }
@Override @Override
protected JsonObject getChartData() throws Exception { protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject(); final JsonObject data = new JsonObject();
JsonObject values = new JsonObject(); final JsonObject values = new JsonObject();
Map<String, Integer> map = callable.call(); final Map<String, Integer> map = this.callable.call();
if (map == null || map.isEmpty()) { if (map == null || map.isEmpty()) {
// Null = skip the chart // Null = skip the chart
return null; return null;
} }
boolean allSkipped = true; boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) { for (final Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) { if (entry.getValue() == 0) {
continue; // Skip this invalid continue; // Skip this invalid
} }
@@ -533,25 +533,25 @@ public class Metrics {
* @param chartId The id of the chart. * @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data. * @param callable The callable which is used to request the chart data.
*/ */
public DrilldownPie(String chartId, Callable<Map<String, Map<String, Integer>>> callable) { public DrilldownPie(final String chartId, final Callable<Map<String, Map<String, Integer>>> callable) {
super(chartId); super(chartId);
this.callable = callable; this.callable = callable;
} }
@Override @Override
public JsonObject getChartData() throws Exception { public JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject(); final JsonObject data = new JsonObject();
JsonObject values = new JsonObject(); final JsonObject values = new JsonObject();
Map<String, Map<String, Integer>> map = callable.call(); final Map<String, Map<String, Integer>> map = this.callable.call();
if (map == null || map.isEmpty()) { if (map == null || map.isEmpty()) {
// Null = skip the chart // Null = skip the chart
return null; return null;
} }
boolean reallyAllSkipped = true; boolean reallyAllSkipped = true;
for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) { for (final Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) {
JsonObject value = new JsonObject(); final JsonObject value = new JsonObject();
boolean allSkipped = true; boolean allSkipped = true;
for (Map.Entry<String, Integer> valueEntry : map.get(entryValues.getKey()).entrySet()) { for (final Map.Entry<String, Integer> valueEntry : map.get(entryValues.getKey()).entrySet()) {
value.addProperty(valueEntry.getKey(), valueEntry.getValue()); value.addProperty(valueEntry.getKey(), valueEntry.getValue());
allSkipped = false; allSkipped = false;
} }
@@ -582,15 +582,15 @@ public class Metrics {
* @param chartId The id of the chart. * @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data. * @param callable The callable which is used to request the chart data.
*/ */
public SingleLineChart(String chartId, Callable<Integer> callable) { public SingleLineChart(final String chartId, final Callable<Integer> callable) {
super(chartId); super(chartId);
this.callable = callable; this.callable = callable;
} }
@Override @Override
protected JsonObject getChartData() throws Exception { protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject(); final JsonObject data = new JsonObject();
int value = callable.call(); final int value = this.callable.call();
if (value == 0) { if (value == 0) {
// Null = skip the chart // Null = skip the chart
return null; return null;
@@ -614,22 +614,22 @@ public class Metrics {
* @param chartId The id of the chart. * @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data. * @param callable The callable which is used to request the chart data.
*/ */
public MultiLineChart(String chartId, Callable<Map<String, Integer>> callable) { public MultiLineChart(final String chartId, final Callable<Map<String, Integer>> callable) {
super(chartId); super(chartId);
this.callable = callable; this.callable = callable;
} }
@Override @Override
protected JsonObject getChartData() throws Exception { protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject(); final JsonObject data = new JsonObject();
JsonObject values = new JsonObject(); final JsonObject values = new JsonObject();
Map<String, Integer> map = callable.call(); final Map<String, Integer> map = this.callable.call();
if (map == null || map.isEmpty()) { if (map == null || map.isEmpty()) {
// Null = skip the chart // Null = skip the chart
return null; return null;
} }
boolean allSkipped = true; boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) { for (final Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) { if (entry.getValue() == 0) {
continue; // Skip this invalid continue; // Skip this invalid
} }
@@ -659,22 +659,22 @@ public class Metrics {
* @param chartId The id of the chart. * @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data. * @param callable The callable which is used to request the chart data.
*/ */
public SimpleBarChart(String chartId, Callable<Map<String, Integer>> callable) { public SimpleBarChart(final String chartId, final Callable<Map<String, Integer>> callable) {
super(chartId); super(chartId);
this.callable = callable; this.callable = callable;
} }
@Override @Override
protected JsonObject getChartData() throws Exception { protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject(); final JsonObject data = new JsonObject();
JsonObject values = new JsonObject(); final JsonObject values = new JsonObject();
Map<String, Integer> map = callable.call(); final Map<String, Integer> map = this.callable.call();
if (map == null || map.isEmpty()) { if (map == null || map.isEmpty()) {
// Null = skip the chart // Null = skip the chart
return null; return null;
} }
for (Map.Entry<String, Integer> entry : map.entrySet()) { for (final Map.Entry<String, Integer> entry : map.entrySet()) {
JsonArray categoryValues = new JsonArray(); final JsonArray categoryValues = new JsonArray();
categoryValues.add(new JsonPrimitive(entry.getValue())); categoryValues.add(new JsonPrimitive(entry.getValue()));
values.add(entry.getKey(), categoryValues); values.add(entry.getKey(), categoryValues);
} }
@@ -697,28 +697,28 @@ public class Metrics {
* @param chartId The id of the chart. * @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data. * @param callable The callable which is used to request the chart data.
*/ */
public AdvancedBarChart(String chartId, Callable<Map<String, int[]>> callable) { public AdvancedBarChart(final String chartId, final Callable<Map<String, int[]>> callable) {
super(chartId); super(chartId);
this.callable = callable; this.callable = callable;
} }
@Override @Override
protected JsonObject getChartData() throws Exception { protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject(); final JsonObject data = new JsonObject();
JsonObject values = new JsonObject(); final JsonObject values = new JsonObject();
Map<String, int[]> map = callable.call(); final Map<String, int[]> map = this.callable.call();
if (map == null || map.isEmpty()) { if (map == null || map.isEmpty()) {
// Null = skip the chart // Null = skip the chart
return null; return null;
} }
boolean allSkipped = true; boolean allSkipped = true;
for (Map.Entry<String, int[]> entry : map.entrySet()) { for (final Map.Entry<String, int[]> entry : map.entrySet()) {
if (entry.getValue().length == 0) { if (entry.getValue().length == 0) {
continue; // Skip this invalid continue; // Skip this invalid
} }
allSkipped = false; allSkipped = false;
JsonArray categoryValues = new JsonArray(); final JsonArray categoryValues = new JsonArray();
for (int categoryValue : entry.getValue()) { for (final int categoryValue : entry.getValue()) {
categoryValues.add(new JsonPrimitive(categoryValue)); categoryValues.add(new JsonPrimitive(categoryValue));
} }
values.add(entry.getKey(), categoryValues); values.add(entry.getKey(), categoryValues);
@@ -10,23 +10,23 @@ public interface RedisListener extends RedisPubSubListener<String, String> {
void message(@NonNull String channel, @NonNull String message); void message(@NonNull String channel, @NonNull String message);
@Override @Override
default void message(@NonNull String pattern, @NonNull String channel, @NonNull String message) { default void message(@NonNull final String pattern, @NonNull final String channel, @NonNull final String message) {
} }
@Override @Override
default void subscribed(@NonNull String channel, long count) { default void subscribed(@NonNull final String channel, final long count) {
} }
@Override @Override
default void psubscribed(@NonNull String pattern, long count) { default void psubscribed(@NonNull final String pattern, final long count) {
} }
@Override @Override
default void unsubscribed(@NonNull String channel, long count) { default void unsubscribed(@NonNull final String channel, final long count) {
} }
@Override @Override
default void punsubscribed(@NonNull String pattern, long count) { default void punsubscribed(@NonNull final String pattern, final long count) {
} }
} }