First attempts at including CommentedConfiguration into TownyChat

This commit is contained in:
LlmDl committed 2018-02-17 13:55:34 -06:00
1 parent 6d794e210a
commit aa8e816df7
5 files changed
+594 -1

No files matched your search

@@ -1,5 +1,7 @@
package com.palmergames.bukkit.TownyChat;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import org.bukkit.permissions.Permission;
@@ -18,11 +20,14 @@ import com.palmergames.bukkit.TownyChat.Command.MuteListCommand;
import com.palmergames.bukkit.TownyChat.Command.TownyChatCommand;
import com.palmergames.bukkit.TownyChat.Command.UnmuteCommand;
import com.palmergames.bukkit.TownyChat.channels.ChannelsHolder;
import com.palmergames.bukkit.TownyChat.config.ChatConfigNodes;
import com.palmergames.bukkit.TownyChat.config.CommentedConfiguration;
import com.palmergames.bukkit.TownyChat.config.ConfigurationHandler;
import com.palmergames.bukkit.TownyChat.listener.HeroicDeathForwarder;
import com.palmergames.bukkit.TownyChat.listener.TownyChatPlayerListener;
import com.palmergames.bukkit.TownyChat.tasks.onLoadedTask;
import com.palmergames.bukkit.TownyChat.util.FileMgmt;
import com.palmergames.bukkit.config.ConfigNodes;
import com.palmergames.bukkit.towny.Towny;
/**
@@ -35,9 +40,12 @@ import com.palmergames.bukkit.towny.Towny;
public class Chat extends JavaPlugin {
private String version = "2.0";
private TownyChatPlayerListener TownyPlayerListener;
private ChannelsHolder channels;
private ConfigurationHandler configuration;
private static CommentedConfiguration chatConfig, newChatConfig;
protected PluginManager pm;
private Towny towny = null;
@@ -50,6 +58,8 @@ public class Chat extends JavaPlugin {
@Override
public void onEnable() {
version = this.getDescription().getVersion();
pm = getServer().getPluginManager();
configuration = new ConfigurationHandler(this);
@@ -57,6 +67,12 @@ public class Chat extends JavaPlugin {
checkPlugins();
try {
loadNewConfig(getTowny().getDataFolder().getPath() + FileMgmt.fileSeparator() + "settings" + FileMgmt.fileSeparator() + "ChatConfig2.yml", this.getDescription().getVersion());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* This executes the task with a 1 tick delay avoiding the bukkit
* depends bug.
@@ -86,6 +102,22 @@ public class Chat extends JavaPlugin {
FileMgmt.checkFolders(new String[] { getRootPath(), getChannelsPath() });
return configuration.loadChannels(getChannelsPath(), "Channels.yml");
}
public static void loadNewConfig(String filepath, String version) throws IOException {
File file = FileMgmt.CheckYMLExists(new File(filepath));
if (file != null) {
// read the config.yml into memory
chatConfig = new CommentedConfiguration(file);
if (!chatConfig.load())
System.out.print("Failed to load ChatConfig!");
setDefaults(version, file);
chatConfig.save();
}
}
@Override
public void onDisable() {
@@ -220,4 +252,71 @@ public class Chat extends JavaPlugin {
public HeroicDeathForwarder getHeroicDeath() {
return heroicDeathListener;
}
/**
* Builds a new config reading old config data.
*/
private static void setDefaults(String version, File file) {
newChatConfig = new CommentedConfiguration(file);
newChatConfig.load();
for (ChatConfigNodes root : ChatConfigNodes.values()) {
if (root.getComments().length > 0)
addComment(root.getRoot(), root.getComments());
if (root.getRoot() == ChatConfigNodes.VERSION.getRoot()) {
setNewProperty(root.getRoot(), version);
} else if (root.getRoot() == ChatConfigNodes.LAST_RUN_VERSION.getRoot())
setNewProperty(root.getRoot(), getLastRunVersion(version));
else {
System.out.println("**** setDefaults() ***");
System.out.println("* Loading: " + root.getRoot());
if (chatConfig.get(root.getRoot().toLowerCase()) != null) {
System.out.println("* Found: " + chatConfig.get(root.getRoot().toLowerCase()));
} else {
System.out.println("* Setting Default: " + root.getDefault());
}
setNewProperty(root.getRoot(), (chatConfig.get(root.getRoot().toLowerCase()) != null) ? chatConfig.get(root.getRoot().toLowerCase()) : root.getDefault());
}
}
chatConfig = newChatConfig;
newChatConfig = null;
}
public static void addComment(String root, String... comments) {
newChatConfig.addComment(root.toLowerCase(), comments);
}
private static void setNewProperty(String root, Object value) {
if (value == null) {
// System.out.print("value is null for " + root.toLowerCase());
value = "";
}
newChatConfig.set(root.toLowerCase(), value.toString());
}
public static String getLastRunVersion(String currentVersion) {
return getString(ConfigNodes.LAST_RUN_VERSION.getRoot(), currentVersion);
}
public static String getString(String root, String def) {
String data = chatConfig.getString(root.toLowerCase(), def);
if (data == null) {
sendError(root.toLowerCase() + " from ChatConfig.yml");
return "";
}
return data;
}
private static void sendError(String msg) {
System.out.println("[TownyChat] Error could not read " + msg);
}
}
@@ -0,0 +1,217 @@
package com.palmergames.bukkit.TownyChat.config;
public enum ChatConfigNodes {
VERSION_HEADER("version", "", ""),
VERSION(
"version.version",
"",
"# This is the current version of Towny. Please do not edit."),
LAST_RUN_VERSION(
"version.last_run_version",
"",
"# This is for showing the changelog on updates. Please do not edit."),
// CHATCONFIGCOMMENTS(
// "chatconfigcomments",
// "",
// "",
// "############################################################",
// "# +------------------------------------------------------+ #",
// "# | ChatConfig.yml | #",
// "# +------------------------------------------------------+ #",
// "############################################################",
// "",
// "# The formats below will specify the changes made to the player chat when talking.",
// "",
// "# {worldname} - Displays the world the player is currently in.",
// "# {town} - Displays town name if a member of a town.",
// "# {townformatted} - Displays town name (if a member of a town) using tag_format.town.",
// "# {towntag} - Displays the formated town tag (if a member of a town) using modify_chat.tag_format.town.",
// "# {towntagoverride} - Displays the formated town tag (if a member of a town and present) or falls back to the full name (using modify_chat.tag_format.town).",
// "",
// "# {nation} - Displays nation name if a member of a nation.",
// "# {nationformatted} - Displays nation name (if a member of a nation) using tag_format.town.",
// "# {nationtag} - Displays the formated nation tag (if a member of a nation) using modify_chat.tag_format.nation.",
// "# {nationtagoverride} - Displays the formated nation tag (if a member of a nation and present) or falls back to the full name (using modify_chat.tag_format.nation).",
// "",
// "# {townytag} - Displays the formated town/nation tag as specified in modify_chat.tag_format.both.",
// "# {townyformatted} - Displays the formated full town/nation names as specified in modify_chat.tag_format.both.",
// "# {townytagoverride} - Displays the formated town/nation tag (if present) or falls back to the full names (using modify_chat.tag_format.both).",
// "",
// "# {title} - Towny resident Title.",
// "# {surname} - Towny resident Surname.",
// "# {townynameprefix} - Towny name prefix taken from the townLevel/nationLevels.",
// "# {townynamepostfix} - Towny name postfix taken from the townLevel/nationLevels.",
// "# {townyprefix} - Towny resident title, or townynameprefix if no title exists.",
// "# {townypostfix} - Towny resident surname, or townynamepostfix if no surname exists",
// "",
// "# {townycolor} - Towny name colour for king/mayor/resident.",
// "# {group} - Players group name pulled from your permissions plugin.",
// "# {permuserprefix} - Permission user prefix.",
// "# {permusersuffix} - Permission user suffix.",
// "# {permgroupprefix} - Permission group prefix.",
// "# {permgroupsuffix} - Permission group suffix.",
// "# {permprefix} - Permission group and user prefix.",
// "# {permsuffix} - Permission group and user suffix.",
// "",
// "# {playername} - Default player name.",
// "# {modplayername} - Modified player name (use if Towny is over writing some other plugins changes).",
// "# {msg} - The message sent.",
// "",
// "# {channelTag} - Defined in the channels entry in Channels.yml.",
// "# {msgcolour} - Defined in the channels entry in Channels.yml.",
// "",
// "# Text colouring",
// "# --------------",
// "# Black = &0, Navy = &1, Green = &2, Blue = &3, Red = &4",
// "# Purple = &5, Gold = &6, LightGray = &7, Gray = &8",
// "# DarkPurple = &9, LightGreen = &a, LightBlue = &b",
// "# Rose = &c, LightPurple = &d, Yellow = &e, White = &f",
// "",
// "# Text altering",
// "# -------------",
// "# Bold = &l, Italics = &o, Underlined = &n,",
// "# Magic = &k, Strike = &m, Reset = &r"),
// SPAM_TIME(
// "spam_time",
// "0.5",
// "",
// "# Spam_time set the minimum time between messages to be flagged as spam"),
HEROIC_DEATH_TO_IRC("HeroicDeathToIRC",
"",
"",
"# If using our updated HeroicDeath.jar and craftIRC 3.1 (dev), you can",
"#configure what IRC channels you want death messages relayed to."),
HEROIC_DEATH_TO_IRC_ENABLED(
"HeroicDeathToIRC.enabled",
"true"),
HEROIC_DEATH_TO_IRC_CRAFTIRCTAGS(
"HeroicDeathToIRC.craftIRCTags",
"admin",
"# comma delimited list of craftIRC channel tags 'admin,blah,blah'."),
CHANNEL_FORMATS(
"channel_formats",
"",
""),
CHANNEL_FORMATS_GLOBAL(
"channel_formats.global",
"{channelTag} {worldname}{townytagoverride}{townycolor}{permprefix}{group} {townyprefix}{modplayername}{townypostfix}{permsuffix}&f:{msgcolour} {msg}",
"# This is the format which will be used for GLOBAL chat/channels.",
"# This is also the format used when you have modify_chat.enable: true, but use other plugins to handle chat."),
CHANNEL_FORMATS_TOWN(
"channel_formats.town",
"{channelTag} {townycolor}{permprefix}{townyprefix}{playername}{townypostfix}{permsuffix}&f:{msgcolour} {msg}",
"# TOWN channel types."),
CHANNEL_FORMATS_NATION(
"channel_formats.nation",
"{channelTag} {towntagoverride}{townycolor}{permprefix}{townyprefix}{playername}{townypostfix}{permsuffix}&f:{msgcolour} {msg}",
"# NATION channel types."),
CHANNEL_FORMATS_DEFAULT(
"channel_formats.default",
"{channelTag} {permprefix}{playername}{permsuffix}&f:{msgcolour} {msg}",
"# DEFAULT channel types."),
// TAG_FORMATS(
// "tag_formats",
// "",
// ""),
// TAG_FORMATS_WORLD(
// "tag_formats.world",
// "&f[&f%s&f] "),
// TAG_FORMATS_TOWN(
// "tag_formats.town",
// "&f[&3%s&f] "),
// TAG_FORMATS_NATION(
// "tag_formats.nation",
// "&f[&e%s&f] "),
// TAG_FORMATS_BOTH(
// "tag_formats.both",
// "&f[&6%s&f|&3%s&f] ",
// "# First %s is the nation tag, second is the town tag."),
// COLOUR(
// "colour",
// "",
// ""),
// COLOUR_KING(
// "colour.king",
// "&6"),
// COLOUR_MAYOR(
// "colour.mayor",
// "&b"),
// COLOUR_RESIDENT(
// "colour.resident",
// "&f"),
MODIFY_CHAT(
"modify_chat",
"",
""),
MODIFY_CHAT_ENABLE(
"modify_chat.enable",
"true",
"# This is used for when you don't have another plugin to format chat.",
"# or you want some other plugin to handle open chat, but want Towny formatting.",
"# It will cause Towny to overwrite any other plugins alterations to the format."),
MODIFY_CHAT_PER_WORLD(
"modify_chat.per_world",
"false",
"# This is used for when you don't have another plugin to format chat.",
"# These can then be altered individually."),
MODIFY_CHAT_ALONE_MESSAGE(
"modify_chat.alone_message",
"false",
"# If true any player who speaks in a channel in which he cannot be heard,",
"# either by being along in the channel or out-of-range of another player in his chat channel,",
"# that player will see a message saying they cannot be heard."),
MODIFY_CHAT_ALONE_MESSAGE_STRING(
"modify_chat.alone_message_string",
"'No one in range can hear you or you are alone in this channel.'",
"# This allows you to set your alone message."),
WORLDS("worlds","","");
private final String Root;
private final String Default;
private String[] comments;
private ChatConfigNodes(String root, String def, String... comments) {
this.Root = root;
this.Default = def;
this.comments = comments;
}
/**
* Retrieves the root for a config option
*
* @return The root for a config option
*/
public String getRoot() {
return Root;
}
/**
* Retrieves the default value for a config path
*
* @return The default value for a config path
*/
public String getDefault() {
return Default;
}
/**
* Retrieves the comment for a config path
*
* @return The comments for a config path
*/
public String[] getComments() {
if (comments != null) {
return comments;
}
String[] comments = new String[1];
comments[0] = "";
return comments;
}
}
@@ -0,0 +1,220 @@
package com.palmergames.bukkit.TownyChat.config;
import com.palmergames.bukkit.TownyChat.util.FileMgmt;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
/**
* @author dumptruckman
*/
public class CommentedConfiguration extends YamlConfiguration {
private HashMap<String, String> comments;
private File file;
public CommentedConfiguration(File file) {
super();
//this.load(file);
comments = new HashMap<String, String>();
this.file = file;
}
public boolean load() {
boolean loaded = true;
try {
this.load(file);
} catch (FileNotFoundException e) {
loaded = false;
} catch (IOException e) {
loaded = false;
} catch (InvalidConfigurationException e) {
loaded = false;
}
return loaded;
}
public boolean save() {
boolean saved = true;
// Save the config just like normal
try {
super.save(file);
} catch (Exception e) {
saved = false;
}
// if there's comments to add and it saved fine, we need to add comments
if (!comments.isEmpty() && saved) {
// String array of each line in the config file
String[] yamlContents = FileMgmt.convertFileToString(file).split("[" + System.getProperty("line.separator") + "]");
// This will hold the newly formatted line
String newContents = "";
// This holds the current path the lines are at in the config
String currentPath = "";
// This tells if the specified path has already been commented
boolean commentedPath = false;
// This flags if the line is a node or unknown text.
boolean node = false;
// The depth of the path. (number of words separated by periods - 1)
int depth = 0;
// Loop through the config lines
for (String line : yamlContents) {
System.out.println("**** A line of yamlContents: **");
System.out.println("* Initial line: " + line);
// If the line is a node (and not something like a list value)
if (line.contains(": ") || (line.length() > 1 && line.charAt(line.length() - 1) == ':')) {
// This is a new node so we need to mark it for commenting (if there are comments)
commentedPath = false;
// This is a node so flag it as one
node = true;
// Grab the index of the end of the node name
int index = 0;
index = line.indexOf(": ");
if (index < 0) {
index = line.length() - 1;
}
// If currentPath is empty, store the node name as the currentPath. (this is only on the first iteration, i think)
if (currentPath.isEmpty()) {
currentPath = line.substring(0, index);
} else {
// Calculate the whitespace preceding the node name
int whiteSpace = 0;
for (int n = 0; n < line.length(); n++) {
if (line.charAt(n) == ' ') {
whiteSpace++;
} else {
break;
}
}
// Find out if the current depth (whitespace * 2) is greater/lesser/equal to the previous depth
if (whiteSpace / 2 > depth) {
// Path is deeper. Add a . and the node name
currentPath += "." + line.substring(whiteSpace, index);
depth++;
} else if (whiteSpace / 2 < depth) {
// Path is shallower, calculate current depth from whitespace (whitespace / 2) and subtract that many levels from the currentPath
int newDepth = whiteSpace / 2;
for (int i = 0; i < depth - newDepth; i++) {
currentPath = currentPath.replace(currentPath.substring(currentPath.lastIndexOf(".")), "");
}
// Grab the index of the final period
int lastIndex = currentPath.lastIndexOf(".");
if (lastIndex < 0) {
// if there isn't a final period, set the current path to nothing because we're at root
currentPath = "";
} else {
// If there is a final period, replace everything after it with nothing
currentPath = currentPath.replace(currentPath.substring(currentPath.lastIndexOf(".")), "");
currentPath += ".";
}
// Add the new node name to the path
currentPath += line.substring(whiteSpace, index);
// Reset the depth
depth = newDepth;
} else {
// Path is same depth, replace the last path node name to the current node name
int lastIndex = currentPath.lastIndexOf(".");
if (lastIndex < 0) {
// if there isn't a final period, set the current path to nothing because we're at root
currentPath = "";
} else {
// If there is a final period, replace everything after it with nothing
currentPath = currentPath.replace(currentPath.substring(currentPath.lastIndexOf(".")), "");
currentPath += ".";
}
//currentPath = currentPath.replace(currentPath.substring(currentPath.lastIndexOf(".")), "");
currentPath += line.substring(whiteSpace, index);
}
}
} else
node = false;
if (node) {
String comment = null;
if (!commentedPath) {
// If there's a comment for the current path, retrieve it and flag that path as already commented
comment = comments.get(currentPath);
}
if (comment != null) {
// Add the comment to the beginning of the current line
line = comment + System.getProperty("line.separator") + line + System.getProperty("line.separator");
comment = null;
commentedPath = true;
} else {
// Add a new line as it is a node, but has no comment
line += System.getProperty("line.separator");
}
}
// Add the (modified) line to the total config String
//System.out.println("Printing newContents: " + newContents);
System.out.println("* Printing line: " + line);
System.out.println("* Node: " + node);
System.out.println("*");
newContents += line + ((!node) ? System.getProperty("line.separator") : "");
}
/*
* Due to a bukkit bug we need to strip any extra new lines from the
* beginning of this file, else they will multiply.
*/
while (newContents.startsWith(System.getProperty("line.separator")))
newContents = newContents.replaceFirst(System.getProperty("line.separator"), "");
try {
// Write the string to the config file
FileMgmt.stringToFile(newContents, file);
} catch (IOException e) {
saved = false;
}
}
return saved;
}
/**
* Adds a comment just before the specified path. The comment can be
* multiple lines. An empty string will indicate a blank line.
*
* @param path Configuration path to add comment.
* @param commentLines Comments to add. One String per line.
*/
public void addComment(String path, String... commentLines) {
StringBuilder commentstring = new StringBuilder();
String leadingSpaces = "";
for (int n = 0; n < path.length(); n++) {
if (path.charAt(n) == '.') {
leadingSpaces += " ";
}
}
for (String line : commentLines) {
if (!line.isEmpty()) {
line = leadingSpaces + line;
} else {
line = " ";
}
if (commentstring.length() > 0) {
commentstring.append(System.getProperty("line.separator"));
}
commentstring.append(line);
}
comments.put(path, commentstring.toString());
}
}
@@ -132,6 +132,18 @@ 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.
@@ -167,4 +179,49 @@ 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) {
System.out.println("**** The outputs of FileMgmt's convertFileToString's 'while' **");
System.out.println("* n = " + n);
System.out.println("* reader.read(buffer) = " + reader.read(buffer));
System.out.println("*");
writer.write(buffer, 0, n);
}
reader.close();
} catch (IOException e) {
System.out.println("Exception ");
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ignore) {
}
}
}
System.out.println("**** The final return of FileMgmt's convertFileToString before it is parsed into an array by the **");
System.out.println("* writer.toString(): " + writer.toString());
System.out.println("*");
return writer.toString();
} else {
return "";
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
name: TownyChat
main: com.palmergames.bukkit.TownyChat.Chat
version: 0.51
version: 0.52
author: ElgarL, Shade, phrstbrn
website: http://towny.palmergames.com/towny/townychat/
description: >