Redo chatconfig loading.

This commit is contained in:
LlmDl committed 2022-10-03 10:43:14 -05:00
1 parent 355ad72e03
commit 5c454b9f01
9 files changed
+241 -636

No files matched your search

+10 -3
View File
@@ -25,6 +25,7 @@ import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.dynmap.DynmapAPI;
import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
@@ -48,6 +49,7 @@ public class Chat extends JavaPlugin {
private ConfigurationHandler channelsConfig;
protected PluginManager pm;
private static Chat chat = null;
private Towny towny = null;
private DynmapAPI dynMap = null;
@@ -61,6 +63,7 @@ public class Chat extends JavaPlugin {
@Override
public void onEnable() {
chat = this;
pm = getServer().getPluginManager();
channelsConfig = new ConfigurationHandler(this);
channels = new ChannelsHolder(this);
@@ -106,11 +109,16 @@ public class Chat extends JavaPlugin {
private void loadConfigs() {
FileMgmt.checkFolders(new String[] { getRootPath(), getChannelsPath() });
if (!ChatSettings.loadCommentedConfig(getChannelsPath() + FileMgmt.fileSeparator() + "ChatConfig.yml", this.getDescription().getVersion()))
if (!ChatSettings.loadCommentedConfig(getChannelsPath() + File.separator + "ChatConfig.yml"))
chatConfigError = true;
if (!channelsConfig.loadChannels(getChannelsPath(), "Channels.yml"))
channelsConfigError = true;
}
public static Chat getTownyChat() {
return chat;
}
@Override
public void onDisable() {
unregisterPermissions();
@@ -198,7 +206,7 @@ public class Chat extends JavaPlugin {
}
public String getChannelsPath() {
return getRootPath() + FileMgmt.fileSeparator() + "settings";
return getRootPath() + File.separator + "settings";
}
/**
@@ -218,7 +226,6 @@ public class Chat extends JavaPlugin {
public Towny getTowny() {
return towny;
}
public DynmapAPI getDynmap() {
return dynMap;
@@ -106,13 +106,13 @@ public class TownyChatFormatter {
// Output depending on what tags are present
if ((!tTag.isEmpty()) && (!nTag.isEmpty())) {
if (ChatSettings.getBothTags().contains("%t") || ChatSettings.getBothTags().contains("%n")) {
if (ChatSettings.getBothTag().contains("%t") || ChatSettings.getBothTag().contains("%n")) {
// Then it contains %s & %s
// Small suttle change so that an issue is solved, it is documented in the config.
// But only after addition of this. (v0.50)
return ChatSettings.getBothTags().replace("%t", tTag).replace("%n", nTag);
return ChatSettings.getBothTag().replace("%t", tTag).replace("%n", nTag);
} else {
return String.format(ChatSettings.getBothTags(), nTag, tTag);
return String.format(ChatSettings.getBothTag(), nTag, tTag);
}
}
@@ -67,7 +67,7 @@ public class StandardChannel extends Channel {
}
// Set the channel specific format
String format = getFormat(player, channelType);
String format = ChatSettings.getChannelFormat(player, channelType);
// Get the list of message recipients.
Set<Player> recipients = getRecipients(player, town, nation, channelType, event.getRecipients());
@@ -130,16 +130,6 @@ public class StandardChannel extends Channel {
}
}
private String getFormat(Player player, channelTypes channelType) {
return switch(channelType) {
case TOWN -> ChatSettings.getRelevantFormatGroup(player).getTOWN();
case NATION -> ChatSettings.getRelevantFormatGroup(player).getNATION();
case ALLIANCE -> ChatSettings.getRelevantFormatGroup(player).getALLIANCE();
case DEFAULT -> ChatSettings.getRelevantFormatGroup(player).getDEFAULT();
case GLOBAL, PRIVATE -> ChatSettings.getRelevantFormatGroup(player).getGLOBAL();
};
}
private Set<Player> getRecipients(Player player, Town town, Nation nation, channelTypes channelType, Set<Player> recipients) {
return switch (channelType) {
case TOWN -> new HashSet<>(findRecipients(player, TownyAPI.getInstance().getOnlinePlayers(town)));
@@ -15,22 +15,6 @@ public class channelFormats {
}
private String name, GLOBAL, TOWN, NATION, ALLIANCE, DEFAULT;
/**
* @return a clone of this channelFormats
*/
public channelFormats clone(String name) {
channelFormats clone = new channelFormats(name.toLowerCase());
clone.setGLOBAL(this.getGLOBAL());
clone.setTOWN(this.getTOWN());
clone.setNATION(this.getNATION());
clone.setALLIANCE(this.getALLIANCE());
clone.setDEFAULT(this.getDEFAULT());
return clone;
}
/**
* @return the name
@@ -1,11 +1,13 @@
package com.palmergames.bukkit.TownyChat.config;
import com.palmergames.bukkit.TownyChat.Chat;
import com.palmergames.bukkit.TownyChat.channels.channelFormats;
import com.palmergames.bukkit.TownyChat.util.FileMgmt;
import com.palmergames.bukkit.TownyChat.channels.channelTypes;
import com.palmergames.bukkit.config.CommentedConfiguration;
import com.palmergames.bukkit.config.ConfigNodes;
import com.palmergames.bukkit.towny.TownyUniverse;
import com.palmergames.bukkit.towny.object.TownyWorld;
import com.palmergames.util.FileMgmt;
import org.bukkit.Bukkit;
import org.bukkit.configuration.ConfigurationSection;
@@ -14,18 +16,13 @@ import org.bukkit.entity.Player;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
public class ChatSettings extends tag_formats {
public class ChatSettings {
private static boolean modify_chat;
private static boolean per_world;
private static boolean alone_message;
private static boolean display_modes_set_on_join;
private static String alone_message_string;
private static Map<String, channelFormats> formatGroups = new HashMap<String, channelFormats>();
private static Map<String, channelFormats> worldFormatGroups = new HashMap<String, channelFormats>();
private static CommentedConfiguration chatConfig, newChatConfig;
/**
@@ -35,10 +32,10 @@ public class ChatSettings extends tag_formats {
* @return
* @throws IOException
*/
public static boolean loadCommentedConfig(String filepath, String version) {
public static boolean loadCommentedConfig(String filepath) {
File file = FileMgmt.CheckYMLExists(new File(filepath));
if (file != null) {
if (FileMgmt.checkOrCreateFile(filepath)) {
File file = new File(filepath);
// read the config.yml into memory
ChatSettings.chatConfig = new CommentedConfiguration(file.toPath());
@@ -48,11 +45,7 @@ public class ChatSettings extends tag_formats {
Bukkit.getLogger().severe("[TownyChat] Online YAML Parser: https://yaml-online-parser.appspot.com/");
return false;
}
setDefaults(version, file);
try {
// Pre-1.18.1 this option does not exist.
chatConfig.options().width(500);
} catch (NoSuchMethodError ignored) {}
setDefaults(file);
chatConfig.save();
}
return true;
@@ -62,48 +55,47 @@ public class ChatSettings extends tag_formats {
* Builds a new chatconfig reading old chatconfig data,
* and setting new nodes to default values.
*/
private static void setDefaults(String version, File file) {
private static void setDefaults(File file) {
String version = Chat.getTownyChat().getDescription().getVersion();
newChatConfig = new CommentedConfiguration(file.toPath());
newChatConfig.load();
for (ChatConfigNodes root : ChatConfigNodes.values()) {
if (root.getComments().length > 0)
addComment(root.getRoot(), root.getComments());
if (root.getRoot() == ChatConfigNodes.WORLDS.getRoot()) {
// Per-worlds section.
// setNewProperty(root.getRoot(), root.getDefault());
setWorldDefaults();
} else if (root.getRoot() == ChatConfigNodes.VERSION.getRoot()) {
if (root.getRoot() == ChatConfigNodes.WORLDS.getRoot())
setWorldDefaults(); // Per-worlds section.
else if (root.getRoot() == ChatConfigNodes.VERSION.getRoot())
setNewProperty(root.getRoot(), version);
} else if (root.getRoot() == ChatConfigNodes.LAST_RUN_VERSION.getRoot())
else if (root.getRoot() == ChatConfigNodes.LAST_RUN_VERSION.getRoot())
setNewProperty(root.getRoot(), getLastRunVersion(version));
else {
else
// A regular config node.
setNewProperty(root.getRoot(), (chatConfig.get(root.getRoot().toLowerCase()) != null) ? chatConfig.get(root.getRoot().toLowerCase()) : root.getDefault());
}
}
chatConfig = newChatConfig;
newChatConfig = null;
}
private static void setWorldDefaults() {
if (perWorld()) {
if (isPer_world()) {
for (TownyWorld world : TownyUniverse.getInstance().getTownyWorlds()) {
if (!chatConfig.contains("worlds." + world )
|| !chatConfig.contains("worlds." + world + ".global")
|| !chatConfig.contains("worlds." + world + ".town")
|| !chatConfig.contains("worlds." + world + ".nation")
|| !chatConfig.contains("worlds." + world + ".alliance")
|| !chatConfig.contains("worlds." + world + ".default")) {
newChatConfig.createSection("worlds." + world);
ConfigurationSection worldsection = newChatConfig.getConfigurationSection("worlds." + world);
worldsection.set("global", (chatConfig.get("worlds." + world + ".global")!= null) ? chatConfig.get("worlds." + world + ".global") : ChatConfigNodes.CHANNEL_FORMATS_GLOBAL.getDefault());
worldsection.set("town", (chatConfig.get("worlds." + world + ".town")!= null) ? chatConfig.get("worlds." + world + ".town") : ChatConfigNodes.CHANNEL_FORMATS_TOWN.getDefault());
worldsection.set("nation", (chatConfig.get("worlds." + world + ".nation")!= null) ? chatConfig.get("worlds." + world + ".nation") : ChatConfigNodes.CHANNEL_FORMATS_NATION.getDefault());
worldsection.set("alliance", (chatConfig.get("worlds." + world + ".alliance")!= null) ? chatConfig.get("worlds." + world + ".alliance") : ChatConfigNodes.CHANNEL_FORMATS_ALLIANCE.getDefault());
worldsection.set("default", (chatConfig.get("worlds." + world + ".default")!= null) ? chatConfig.get("worlds." + world + ".default") : ChatConfigNodes.CHANNEL_FORMATS_DEFAULT.getDefault());
String path = "worlds." + world;
if (!chatConfig.contains(path )
|| !chatConfig.contains(path + ".global")
|| !chatConfig.contains(path + ".town")
|| !chatConfig.contains(path + ".nation")
|| !chatConfig.contains(path + ".alliance")
|| !chatConfig.contains(path + ".default")) {
newChatConfig.createSection(path);
ConfigurationSection worldsection = newChatConfig.getConfigurationSection(path);
worldsection.set("global", getOrDefault(path + ".global", ChatConfigNodes.CHANNEL_FORMATS_GLOBAL));
worldsection.set("town", getOrDefault(path + ".town", ChatConfigNodes.CHANNEL_FORMATS_TOWN));
worldsection.set("nation", getOrDefault(path + ".nation", ChatConfigNodes.CHANNEL_FORMATS_NATION));
worldsection.set("alliance", getOrDefault(path + ".alliance", ChatConfigNodes.CHANNEL_FORMATS_ALLIANCE));
worldsection.set("default", getOrDefault(path + ".default", ChatConfigNodes.CHANNEL_FORMATS_DEFAULT));
}
}
} else {
@@ -112,7 +104,7 @@ public class ChatSettings extends tag_formats {
}
}
public static void addComment(String root, String... comments) {
private static void addComment(String root, String... comments) {
newChatConfig.addComment(root.toLowerCase(), comments);
}
@@ -123,11 +115,11 @@ public class ChatSettings extends tag_formats {
newChatConfig.set(root.toLowerCase(), value.toString());
}
public static String getLastRunVersion(String currentVersion) {
private static String getLastRunVersion(String currentVersion) {
return getString(ConfigNodes.LAST_RUN_VERSION.getRoot(), currentVersion);
}
public static String getString(String root, String def) {
private static String getString(String root, String def) {
String data = chatConfig.getString(root.toLowerCase(), def);
if (data == null) {
sendError(root.toLowerCase() + " from ChatConfig.yml");
@@ -136,13 +128,12 @@ public class ChatSettings extends tag_formats {
return data;
}
private static void sendError(String msg) {
System.out.println("[TownyChat] Error could not read " + msg);
private static String getString(ChatConfigNodes node) {
return chatConfig.getString(node.getRoot().toLowerCase(), node.getDefault());
}
private static boolean perWorld() {
return getBoolean(ChatConfigNodes.MODIFY_CHAT_PER_WORLD);
private static void sendError(String msg) {
Chat.getTownyChat().getLogger().warning("[TownyChat] Error could not read " + msg);
}
private static boolean getBoolean(ChatConfigNodes node) {
@@ -150,273 +141,137 @@ public class ChatSettings extends tag_formats {
return Boolean.parseBoolean(chatConfig.getString(node.getRoot().toLowerCase(), node.getDefault()));
}
/**
* @return the formatGroups
/*
* Get ChatConfig variables.
*/
public static Map<String, channelFormats> getFormatGroups() {
return formatGroups;
}
/**
* @param formatGroups
* the formatGroups to set
*/
public static void setFormatGroups(Map<String, channelFormats> formatGroups) {
ChatSettings.formatGroups = formatGroups;
}
/**
* @return the formatGroup
*/
public static channelFormats getFormatGroup(String name) {
return formatGroups.get(name.toLowerCase());
}
public static boolean hasFormatGroup(String groupName) {
return formatGroups.containsKey(groupName.toLowerCase());
}
public static void addFormatGroup(channelFormats group) {
if (hasFormatGroup(group.getName()))
formatGroups.remove(group.getName());
formatGroups.put(group.getName(), group);
}
public static void removeFormatGroup(String name) {
if (hasFormatGroup(name.toLowerCase()))
formatGroups.remove(name.toLowerCase());
}
public static channelFormats getRelevantFormatGroup (Player player) {
if (isPer_world()) {
String name = player.getWorld().getName();
if (hasFormatGroup(name))
return getFormatGroup(name);
}
return getFormatGroup("channel_formats");
}
/**
* @return the modify_chat
*/
public static boolean isModify_chat() {
return modify_chat;
}
/**
* @param modify_chat
* the modify_chat to set
*/
public static void setModify_chat(boolean modify_chat) {
ChatSettings.modify_chat = modify_chat;
return getBoolean(ChatConfigNodes.MODIFY_CHAT_ENABLE);
}
/**
* @return the alone_message
*/
public static boolean isUsingAloneMessage() {
return alone_message;
}
/**
* @param alone_message
*/
public static boolean setUsingAloneMessage(boolean alone_message) {
return ChatSettings.alone_message = alone_message;
return getBoolean(ChatConfigNodes.MODIFY_CHAT_ALONE_MESSAGE);
}
/**
* @param alone_message_string
* @return
*/
public static String setUsingAloneMessageString(String alone_message_string) {
return ChatSettings.alone_message_string = alone_message_string;
}
/**
* @return the alone_message_string
*/
public static String getUsingAloneMessageString() {
return ChatSettings.alone_message_string;
}
/**
* @param display_modes_set_on_join
*/
public static boolean setDisplayModesSetOnJoin(boolean display_modes_set_on_join) {
return ChatSettings.display_modes_set_on_join = display_modes_set_on_join;
}
/**
* @return the display_modes_set_on_join setting
*/
public static boolean getShowChannelMessageOnServerJoin() {
return display_modes_set_on_join;
return getString(ChatConfigNodes.MODIFY_CHAT_ALONE_MESSAGE_STRING);
}
/**
* @return the per_world
*/
public static boolean isPer_world() {
return per_world;
return getBoolean(ChatConfigNodes.MODIFY_CHAT_PER_WORLD);
}
/**
* @param per_world
* the per_world to set
* @return the display_modes_set_on_join setting
*/
public static void setPer_world(boolean per_world) {
ChatSettings.per_world = per_world;
public static boolean getShowChannelMessageOnServerJoin() {
return getBoolean(ChatConfigNodes.DISPLAY_CHANNEL_JOIN_MESSAGE_ON_JOIN);
}
/**
* Adds customizable channel formats for each world.
*
* @return true if new worlds we're found
/*
* Get Tags formats.
*/
public static boolean populateWorldFormats() {
boolean updated = false;
public static String getWorldTag() {
return getString(ChatConfigNodes.TAG_FORMATS_WORLD);
}
for (TownyWorld world : TownyUniverse.getInstance().getTownyWorlds()) {
if (!hasFormatGroup(world.getName())) {
addFormatGroup(getFormatGroup("channel_formats").clone(world.getName()));
updated = true;
public static String getTownTag() {
return getString(ChatConfigNodes.TAG_FORMATS_TOWN);
}
public static String getNationTag() {
return getString(ChatConfigNodes.TAG_FORMATS_NATION);
}
public static String getBothTag() {
return getString(ChatConfigNodes.TAG_FORMATS_BOTH);
}
/*
* Get Colour formats.
*/
public static String getKingColour() {
return getString(ChatConfigNodes.COLOUR_KING);
}
public static String getMayorColour() {
return getString(ChatConfigNodes.COLOUR_MAYOR);
}
public static String getResidentColour() {
return getString(ChatConfigNodes.COLOUR_RESIDENT);
}
public static String getNomadColour() {
return getString(ChatConfigNodes.COLOUR_NOMAD);
}
/*
* Get ChannelType Formats
*/
public static String getChannelFormat(Player player, channelTypes type) {
if (isPer_world()) {
String name = player.getWorld().getName().toLowerCase(Locale.ROOT);
if (worldFormatGroups.containsKey(name)) {
channelFormats worldFormat = worldFormatGroups.get(name);
String format = switch (type) {
case GLOBAL, PRIVATE -> worldFormat.getGLOBAL();
case NATION -> worldFormat.getNATION();
case TOWN -> worldFormat.getTOWN();
case ALLIANCE -> worldFormat.getALLIANCE();
case DEFAULT -> worldFormat.getDEFAULT();
};
if (format != null && !format.isEmpty())
return format;
}
}
return updated;
return switch(type) {
case GLOBAL, PRIVATE -> getString(ChatConfigNodes.CHANNEL_FORMATS_GLOBAL);
case NATION -> getString(ChatConfigNodes.CHANNEL_FORMATS_NATION);
case TOWN -> getString(ChatConfigNodes.CHANNEL_FORMATS_TOWN);
case ALLIANCE -> getString(ChatConfigNodes.CHANNEL_FORMATS_ALLIANCE);
case DEFAULT -> getString(ChatConfigNodes.CHANNEL_FORMATS_DEFAULT);
};
}
}
//////////////////////////////////////////////////
class tag_formats extends chat_colours{
private static String WorldTag, TownTag, NationTag, BothTags;
/**
* @return the World tag
*/
public static String getWorldTag() {
return WorldTag;
public static void loadWorldFormats() {
if (!isPer_world())
return;
for (TownyWorld world : TownyUniverse.getInstance().getTownyWorlds()) {
String worldName = world.getName();
String path = "worlds." + worldName;
if (chatConfig.contains(path)) {
channelFormats worldFormat = new channelFormats(worldName);
worldFormat.setGLOBAL(getOrDefault(path + ".global", ChatConfigNodes.CHANNEL_FORMATS_GLOBAL));
worldFormat.setDEFAULT(getOrDefault(path + ".default", ChatConfigNodes.CHANNEL_FORMATS_DEFAULT));
worldFormat.setTOWN(getOrDefault(path + ".town", ChatConfigNodes.CHANNEL_FORMATS_TOWN));
worldFormat.setNATION(getOrDefault(path + ".nation", ChatConfigNodes.CHANNEL_FORMATS_NATION));
worldFormat.setALLIANCE(getOrDefault(path + ".alliance", ChatConfigNodes.CHANNEL_FORMATS_ALLIANCE));
addWorldFormat(worldFormat);
}
}
}
private static String getOrDefault(String configPath, ChatConfigNodes channelNode) {
return (String) chatConfig.get(configPath != null ? configPath : channelNode.getDefault());
}
/**
* @param tag the World tag to set
*/
public static void setWorldTag(String tag) {
tag_formats.WorldTag = tag;
private static void addWorldFormat(channelFormats format) {
worldFormatGroups.put(format.getName().toLowerCase(Locale.ROOT), format);
}
/**
* @return the TownTag
*/
public static String getTownTag() {
return TownTag;
}
/**
* @param tag the TOWN tag to set
*/
public static void setTownTag(String tag) {
tag_formats.TownTag = tag;
}
/**
* @return NationTag
*/
public static String getNationTag() {
return NationTag;
}
/**
* @param tag the NATION tag to set
*/
public static void setNationTag(String tag) {
tag_formats.NationTag = tag;
}
/**
* @return BothTags the nation and town tags
*/
public static String getBothTags() {
return BothTags;
}
/**
* @param tag the Nation and Town tags to set
*/
public static void setBothTags(String tag) {
tag_formats.BothTags = tag;
}
}
class chat_colours {
private static String KING, MAYOR, RESIDENT, NOMAD;
/**
* @return KING the KING colour
*/
public static String getKingColour() {
return KING;
}
/**
* @param colour the colour to set
*/
public static void setKingColour(String colour) {
chat_colours.KING = colour;
}
/**
* @return MAYOR the MAYOR colour
*/
public static String getMayorColour() {
return MAYOR;
}
/**
* @param colour the colour to set
*/
public static void setMayorColour(String colour) {
chat_colours.MAYOR = colour;
}
/**
* @return RESIDENT the RESIDENT colour
*/
public static String getResidentColour() {
return RESIDENT;
}
/**
* @param colour the RESIDENT colour tag to set
*/
public static void setResidentColour(String colour) {
chat_colours.RESIDENT = colour;
}
/**
* @return NOMAD the NOMAD colour
*/
public static String getNomadColour() {
return NOMAD;
}
/**
* @param colour the NOMAD colour tag to set
*/
public static void setNomadColour(String colour) {
chat_colours.NOMAD = colour;
}}
}
@@ -3,11 +3,11 @@ package com.palmergames.bukkit.TownyChat.config;
import com.palmergames.bukkit.TownyChat.Chat;
import com.palmergames.bukkit.TownyChat.channels.Channel;
import com.palmergames.bukkit.TownyChat.channels.StandardChannel;
import com.palmergames.bukkit.TownyChat.channels.channelFormats;
import com.palmergames.bukkit.TownyChat.channels.channelTypes;
import com.palmergames.bukkit.TownyChat.util.FileMgmt;
import org.bukkit.Bukkit;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -41,268 +41,119 @@ public class ConfigurationHandler {
@SuppressWarnings("unchecked")
public boolean loadChannels(String filepath, String defaultRes) {
String filename = filepath + FileMgmt.fileSeparator() + defaultRes;
String filename = filepath + File.separator + defaultRes;
Map<String, Object> file;
try {
file = FileMgmt.getFile(filename, defaultRes, null);
file = FileMgmt.getFile(filename, defaultRes);
} catch (Exception e) {
Bukkit.getLogger().severe("[TownyChat] Failed to load Channels.yml!");
Bukkit.getLogger().severe("[TownyChat] Please check that the file passes a YAML Parser test:");
Bukkit.getLogger().severe("[TownyChat] Online YAML Parser: https://yaml-online-parser.appspot.com/");
return false;
}
if (file != null) {
if (file == null || !file.containsKey("Channels"))
return false;
for (String rootNode : file.keySet()) {
// Parse the channels
Map<String, Object> allChannelNodes = (Map<String, Object>) file.get("Channels");
if (allChannelNodes == null)
return false;
// Load channels if the file is NOT empty
for (String channelKey : allChannelNodes.keySet()) {
if (rootNode.equalsIgnoreCase("Channels")) {
// Parse the channels
Map<String, Object> allChannelNodes = (Map<String, Object>) file.get(rootNode);
// Load channels if the file is NOT empty
if (allChannelNodes != null) {
for (String channelKey : allChannelNodes.keySet()) {
Map<String, Object> thisChannelNode = (Map<String, Object>) allChannelNodes.get(channelKey);
Channel channel = new StandardChannel(plugin, channelKey.toLowerCase());
for (String key : thisChannelNode.keySet()) {
Object element = thisChannelNode.get(key);
if (key.equalsIgnoreCase("commands"))
if (element instanceof ArrayList)
channel.setCommands((List<String>) element);
else if (element instanceof String)
channel.setCommands(Arrays.asList(element.toString()));
if (key.equalsIgnoreCase("type"))
if (element instanceof String)
channel.setType(channelTypes.valueOf(element.toString()));
Map<String, Object> thisChannelNode = (Map<String, Object>) allChannelNodes.get(channelKey);
Channel channel = new StandardChannel(plugin, channelKey.toLowerCase());
if (key.equalsIgnoreCase("hooked")) {
if (element instanceof Boolean) {
channel.setHooked((Boolean)element);
} else if (element instanceof String) {
channel.setHooked(Boolean.parseBoolean(element.toString()));
} else if (element instanceof Integer) {
channel.setHooked(Integer.parseInt(element.toString()) != 0);
}
}
for (String key : thisChannelNode.keySet()) {
Object element = thisChannelNode.get(key);
if (key.equalsIgnoreCase("autojoin")) {
if (element instanceof Boolean) {
channel.setAutoJoin((Boolean)element);
} else if (element instanceof String) {
channel.setAutoJoin(Boolean.parseBoolean(element.toString()));
} else if (element instanceof Integer) {
channel.setAutoJoin(Integer.parseInt(element.toString()) != 0);
}
}
if (key.equalsIgnoreCase("commands"))
if (element instanceof ArrayList)
channel.setCommands((List<String>) element);
else if (element instanceof String)
channel.setCommands(Arrays.asList(element.toString()));
if (key.equalsIgnoreCase("default")) {
boolean set = false;
if (element instanceof Boolean) {
set = (element != null && ((Boolean)element) == true);
} else if (element instanceof String) {
set = Boolean.parseBoolean((String)element);
} else if (element instanceof Integer) {
set = (element != null && ((Integer)element) != 0);
}
if (set) {
plugin.getChannelsHandler().setDefaultChannel(channel);
plugin.getLogger().info("Default Channel set to " + channel.getName());
}
}
if (key.equalsIgnoreCase("spam_time")) {
channel.setSpam_time(Double.valueOf(element.toString()));
}
if (key.equalsIgnoreCase("type"))
if (element instanceof String)
channel.setType(channelTypes.valueOf(element.toString()));
if (key.equalsIgnoreCase("channeltag"))
if (element instanceof String)
channel.setChannelTag(element.toString());
if (key.equalsIgnoreCase("messagecolour"))
if (element instanceof String)
channel.setMessageColour(element.toString());
if (key.equalsIgnoreCase("permission"))
if (element instanceof String)
channel.setPermission(element.toString());
if (key.equalsIgnoreCase("leavepermission"))
if (element instanceof String)
channel.setLeavePermission(element.toString());
if (key.equalsIgnoreCase("range"))
channel.setRange(Double.valueOf(element.toString()));
if (key.equalsIgnoreCase("sound"))
channel.setChannelSound(String.valueOf(element));
}
// If no leave permission is set, create a default permission name
if (channel.getLeavePermission() == null) {
channel.setLeavePermission("towny.chat.leave." + channel.getName().toLowerCase());
}
plugin.getChannelsHandler().addChannel(channel);
//System.out.print("Channel: " + channel.getName() + " : Type : " + channel.getType().name());
}
if (plugin.getChannelsHandler().getDefaultChannel() == null) {
// If there is no default channel set it to the first one that was parsed (the top one in the config)
// This is because not everyone knows that you need to add a default: true into the channels.yml to make it the default channel!
plugin.getChannelsHandler().setDefaultChannel(plugin.getChannelsHandler().getAllChannels().entrySet().iterator().next().getValue());
}
return true;
if (key.equalsIgnoreCase("hooked")) {
if (element instanceof Boolean) {
channel.setHooked((Boolean)element);
} else if (element instanceof String) {
channel.setHooked(Boolean.parseBoolean(element.toString()));
} else if (element instanceof Integer) {
channel.setHooked(Integer.parseInt(element.toString()) != 0);
}
}
}
}
return false;
}
/**
* Load the ChatConfig.yml
*
* If it doesn't exist, create it from the resource in this jar.
*
* @param filepath
* @param defaultRes
* @return true if the config was loaded
*/
@SuppressWarnings({ "unchecked" })
public boolean loadConfig(String filepath, String defaultRes) {
String filename = filepath + FileMgmt.fileSeparator() + defaultRes;
if (key.equalsIgnoreCase("autojoin")) {
if (element instanceof Boolean) {
channel.setAutoJoin((Boolean)element);
} else if (element instanceof String) {
channel.setAutoJoin(Boolean.parseBoolean(element.toString()));
} else if (element instanceof Integer) {
channel.setAutoJoin(Integer.parseInt(element.toString()) != 0);
}
}
// Pass the plugin reference so it can load the defaults if needed.
Map<String, Object> file = FileMgmt.getFile(filename);
if (file != null) {
for (String Key : file.keySet()) {
if (Key.equalsIgnoreCase("modify_chat")) {
Map<String, Object> subNodes = (Map<String, Object>) file.get(Key);
for (String element : subNodes.keySet()) {
if (element.equalsIgnoreCase("enable"))
ChatSettings.setModify_chat(Boolean.valueOf(subNodes.get(element).toString()));
if (element.equalsIgnoreCase("per_world"))
ChatSettings.setPer_world(Boolean.valueOf(subNodes.get(element).toString()));
if (element.equalsIgnoreCase("alone_message"))
ChatSettings.setUsingAloneMessage(Boolean.valueOf(subNodes.get(element).toString()));
if (element.equalsIgnoreCase("alone_message_string"))
ChatSettings.setUsingAloneMessageString(String.valueOf(subNodes.get(element).toString()));
if (key.equalsIgnoreCase("default")) {
boolean set = false;
if (element instanceof Boolean) {
set = (element != null && ((Boolean)element) == true);
} else if (element instanceof String) {
set = Boolean.parseBoolean((String)element);
} else if (element instanceof Integer) {
set = (element != null && ((Integer)element) != 0);
}
if (set) {
plugin.getChannelsHandler().setDefaultChannel(channel);
plugin.getLogger().info("Default Channel set to " + channel.getName());
}
}
if (Key.equalsIgnoreCase("display_channel_join_message_on_joining_the_server"))
ChatSettings.setDisplayModesSetOnJoin(Boolean.valueOf(file.get(Key).toString()));
if (Key.equalsIgnoreCase("colour")) {
Map<String, Object> subNodes = (Map<String, Object>) file.get(Key);
for (String element : subNodes.keySet()) {
if (element.equalsIgnoreCase("king"))
ChatSettings.setKingColour(subNodes.get(element).toString());
if (element.equalsIgnoreCase("mayor"))
ChatSettings.setMayorColour(subNodes.get(element).toString());
if (element.equalsIgnoreCase("resident"))
ChatSettings.setResidentColour(subNodes.get(element).toString());
if (element.equalsIgnoreCase("nomad"))
ChatSettings.setNomadColour(subNodes.get(element).toString());
}
if (key.equalsIgnoreCase("spam_time")) {
channel.setSpam_time(Double.valueOf(element.toString()));
}
if (Key.equalsIgnoreCase("tag_formats")) {
Map<String, Object> subNodes = (Map<String, Object>) file.get(Key);
if (key.equalsIgnoreCase("channeltag"))
if (element instanceof String)
channel.setChannelTag(element.toString());
for (String element : subNodes.keySet()) {
if (element.equalsIgnoreCase("world"))
ChatSettings.setWorldTag(subNodes.get(element).toString());
if (key.equalsIgnoreCase("messagecolour"))
if (element instanceof String)
channel.setMessageColour(element.toString());
if (element.equalsIgnoreCase("town"))
ChatSettings.setTownTag(subNodes.get(element).toString());
if (key.equalsIgnoreCase("permission"))
if (element instanceof String)
channel.setPermission(element.toString());
if (key.equalsIgnoreCase("leavepermission"))
if (element instanceof String)
channel.setLeavePermission(element.toString());
if (element.equalsIgnoreCase("nation"))
ChatSettings.setNationTag(subNodes.get(element).toString());
if (element.equalsIgnoreCase("both"))
ChatSettings.setBothTags(subNodes.get(element).toString());
}
}
if (Key.equalsIgnoreCase("channel_formats")) {
Map<String, Object> subNodes = (Map<String, Object>) file.get(Key);
channelFormats group = new channelFormats(Key);
for (String element : subNodes.keySet()) {
if (element.equalsIgnoreCase("global"))
group.setGLOBAL(subNodes.get(element).toString());
if (element.equalsIgnoreCase("town"))
group.setTOWN(subNodes.get(element).toString());
if (element.equalsIgnoreCase("nation"))
group.setNATION(subNodes.get(element).toString());
if (element.equalsIgnoreCase("alliance"))
group.setALLIANCE(subNodes.get(element).toString());
if (element.equalsIgnoreCase("default"))
group.setDEFAULT(subNodes.get(element).toString());
}
ChatSettings.addFormatGroup(group);
}
if (Key.equalsIgnoreCase("worlds")) {
Map<String, Object> allWorlds = (Map<String, Object>) file.get(Key);
if (allWorlds != null) {
for (String worlds : allWorlds.keySet()) {
Map<String, Object> world = (Map<String, Object>) allWorlds.get(worlds);
channelFormats group = new channelFormats(worlds);
for (String element : world.keySet()) {
if (element.equalsIgnoreCase("global"))
group.setGLOBAL(world.get(element).toString());
if (element.equalsIgnoreCase("town"))
group.setTOWN(world.get(element).toString());
if (element.equalsIgnoreCase("nation"))
group.setNATION(world.get(element).toString());
if (element.equalsIgnoreCase("alliance"))
group.setALLIANCE(world.get(element).toString());
if (element.equalsIgnoreCase("default"))
group.setDEFAULT(world.get(element).toString());
}
ChatSettings.addFormatGroup(group);
}
}
}
if (key.equalsIgnoreCase("range"))
channel.setRange(Double.valueOf(element.toString()));
if (key.equalsIgnoreCase("sound"))
channel.setChannelSound(String.valueOf(element));
}
return true;
// If no leave permission is set, create a default permission name
if (channel.getLeavePermission() == null) {
channel.setLeavePermission("towny.chat.leave." + channel.getName().toLowerCase());
}
plugin.getChannelsHandler().addChannel(channel);
}
return false;
if (plugin.getChannelsHandler().getDefaultChannel() == null) {
// If there is no default channel set it to the first one that was parsed (the top one in the config)
// This is because not everyone knows that you need to add a default: true into the channels.yml to make it the default channel!
plugin.getChannelsHandler().setDefaultChannel(plugin.getChannelsHandler().getAllChannels().entrySet().iterator().next().getValue());
}
return true;
}
}
@@ -182,7 +182,7 @@ public class TownyChatPlayerListener implements Listener {
* We found no channels available so modify the chat (if enabled) and exit.
*/
if (ChatSettings.isModify_chat()) {
event.setFormat(ChatSettings.getRelevantFormatGroup(player).getGLOBAL().replace("{channelTag}", "").replace("{msgcolour}", ""));
event.setFormat(ChatSettings.getChannelFormat(player, channelTypes.GLOBAL).replace("{channelTag}", "").replace("{msgcolour}", ""));
Resident resident = TownyUniverse.getInstance().getResident(player.getUniqueId());
LocalTownyChatEvent chatEvent = new LocalTownyChatEvent(event, resident);
@@ -1,6 +1,7 @@
package com.palmergames.bukkit.TownyChat.tasks;
import com.palmergames.bukkit.TownyChat.Chat;
import com.palmergames.bukkit.TownyChat.config.ChatSettings;
import com.palmergames.bukkit.towny.Towny;
/*
@@ -25,13 +26,14 @@ public class onLoadedTask implements Runnable {
if (this.towny.isEnabled()) {
// Setup our config here as we now have Towny loaded.
if (this.towny.isError() || (!plugin.getConfigurationHandler().loadConfig(plugin.getChannelsPath(), "ChatConfig.yml"))) {
if (this.towny.isError()) {
plugin.getLogger().severe("Disabling TownyChat...");
plugin.getServer().getPluginManager().disablePlugin(plugin);
return;
}
ChatSettings.loadWorldFormats();
plugin.getLogger().info("-******* TownyChat enabled *******-");
plugin.registerPermissions();
plugin.registerEvents();
@@ -13,7 +13,6 @@ import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import com.palmergames.bukkit.TownyChat.Chat;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.reader.UnicodeReader;
@@ -30,38 +29,7 @@ public class FileMgmt {
}
@SuppressWarnings("unchecked")
public static Map<String, Object> getFile(String filepath) {
try {
File f = new File(filepath);
Yaml yamlChannels = new Yaml(new SafeConstructor());
Object channelsRootDataNode;
FileInputStream fileInputStream = new FileInputStream(f);
try {
channelsRootDataNode = yamlChannels.load(new UnicodeReader(fileInputStream));
if (channelsRootDataNode == null) {
throw new NullPointerException();
}
} catch (Exception ex) {
throw new IllegalArgumentException("The following file couldn't pass on Parser.\n" + f.getPath(), ex);
} finally {
fileInputStream.close();
}
if (channelsRootDataNode instanceof Map)
return (Map<String, Object>) channelsRootDataNode;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@SuppressWarnings("unchecked")
public static Map<String, Object> getFile(String filepath, String resource, Chat plugin) {
public static Map<String, Object> getFile(String filepath, String resource) {
try {
File f = new File(filepath);
@@ -108,7 +76,7 @@ public class FileMgmt {
}
// pass a resource name and it will return it's contents as a string
public static String convertStreamToString(String name) throws IOException {
private static String convertStreamToString(String name) throws IOException {
if (name != null) {
Writer writer = new StringWriter();
InputStream is = FileMgmt.class.getResourceAsStream(name);
@@ -144,7 +112,7 @@ public class FileMgmt {
* @param FileName
* @return true on success
*/
public static boolean stringToFile(String source, String FileName) {
private static boolean stringToFile(String source, String FileName) {
if (source != null) {
// Save the string to file (*.yml)
@@ -158,18 +126,6 @@ public class FileMgmt {
return false;
}
public static File CheckYMLExists(File file) {
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
/**
* Writes the contents of a string to a file.
@@ -181,7 +137,7 @@ public class FileMgmt {
* @return True on success.
* @throws IOException
*/
public static boolean stringToFile(String source, File file) throws IOException {
private static boolean stringToFile(String source, File file) throws IOException {
try {
@@ -199,44 +155,4 @@ public class FileMgmt {
}
}
public static String fileSeparator() {
return System.getProperty("file.separator");
}
/**
* Pass a file and it will return it's contents as a string.
*
* @param file File to read.
* @return Contents of file. String will be empty in case of any errors.
*/
public static String convertFileToString(File file) {
if (file != null && file.exists() && file.canRead() && !file.isDirectory()) {
Writer writer = new StringWriter();
InputStream is = null;
char[] buffer = new char[1024];
try {
is = new FileInputStream(file);
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
reader.close();
} catch (IOException e) {
System.out.println("Exception ");
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ignore) {
}
}
}
return writer.toString();
} else {
return "";
}
}
}