Skip to content

Commit

Permalink
Add new command for database users to load groups correctly. Fixes #9
Browse files Browse the repository at this point in the history
…and #17
  • Loading branch information
sgtcaze committed Mar 1, 2016
1 parent b82d76e commit 331a88f
Show file tree
Hide file tree
Showing 12 changed files with 157 additions and 29 deletions.
11 changes: 11 additions & 0 deletions documentation/Commands.creole
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
| nte | clear [player] | Clears the prefix and suffix for a player |
| nte | <prefix/suffix> [player] <text> | Sets the prefix or suffix for a player |
| nte | groups list | Lists all loaded groups |
| nte | groups order <groups> | Orders the priority of groups. |
| nte | groups add [group] | Creates a new group |
| nte | groups remove [group] | Removes a group |
| nte | groups [group] [perm] <value> | Sets the default permission for a group |
Expand All @@ -16,6 +17,16 @@

== Example Command Usage

=== Ordering Group Priority
Suppose we have 3 groups: Owner, Admin, Default. The first group looked at is the one with the highest priority. We would use:

{{{
/ne groups order Owner Admin Default
}}}

NametagEdit will remember the order so groups always load properly.
v4.0.1 - Only users who use a database can use this command

=== Editing Invidiual Prefixes/Suffixes
Suppose we wish to have a nametag like

Expand Down
19 changes: 19 additions & 0 deletions src/main/java/com/nametagedit/plugin/NametagCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.nametagedit.plugin.converter.Converter;
import com.nametagedit.plugin.converter.ConverterTask;
import com.nametagedit.plugin.storage.data.GroupData;
import com.nametagedit.plugin.storage.database.tasks.GroupConfigUpdater;
import com.nametagedit.plugin.utils.Utils;
import lombok.AllArgsConstructor;
import mkremins.fanciful.FancyMessage;
Expand All @@ -15,6 +16,10 @@
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionDefault;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@AllArgsConstructor
public class NametagCommand implements CommandExecutor {

Expand Down Expand Up @@ -72,6 +77,7 @@ private void sendLegacyUsage(CommandSender sender) {
sender.sendMessage(Utils.format("&6/ne clear <Player> &fClears a player's nametag"));
sender.sendMessage(Utils.format("&e&lGroup Usage"));
sender.sendMessage(Utils.format("&6/ne groups list &fLists the current loaded groups"));
sender.sendMessage(Utils.format("&6/ne groups order <MyTopGroup> <MySecond> ..."));
sender.sendMessage(Utils.format("&6/ne groups add <Group> &fCreates a group"));
sender.sendMessage(Utils.format("&6/ne groups remove <Group> &fRemoves a group"));
sender.sendMessage(Utils.format("&6/ne groups <Group> permission <value> &fChanges the permission"));
Expand All @@ -91,6 +97,7 @@ private void sendUsage(CommandSender sender) {
.then("\n/ne clear <Player> ").color(ChatColor.GOLD).suggest("/ne clear ").then("Clears a player's nametag").color(ChatColor.WHITE)
.then("\nGroup Usage ").color(ChatColor.YELLOW).style(ChatColor.BOLD).then(" (Click a Command!)").color(ChatColor.GRAY)
.then("\n/ne groups list ").color(ChatColor.GOLD).suggest("/ne groups list").then("Lists the current loaded groups").color(ChatColor.WHITE)
.then("\n/ne groups order <group> ... ").color(ChatColor.GOLD).suggest("/ne groups order ").then("Orders groups for the database").color(ChatColor.WHITE)
.then("\n/ne groups add <Group> ").color(ChatColor.GOLD).suggest("/ne groups add ").then("Creates a group").color(ChatColor.WHITE)
.then("\n/ne groups remove <Group> ").color(ChatColor.GOLD).suggest("/ne groups remove ").then("Removes a group").color(ChatColor.WHITE)
.then("\n/ne groups <Group> permission <value> ").color(ChatColor.GOLD).suggest("/ne groups Group permission my.permission").then("Changes the permission").color(ChatColor.WHITE)
Expand Down Expand Up @@ -193,6 +200,18 @@ private void cmdGroups(CommandSender sender, String[] args) {
sender.sendMessage(Utils.format("&6Group: &f" + groupData.getGroupName() + " &6Permission: &f" + groupData.getPermission()
+ " &6Formatted: " + groupData.getPrefix() + sender.getName() + groupData.getSuffix()));
}
} else if (args[1].equalsIgnoreCase("order")) {
if (!handler.getPlugin().getConfig().getBoolean("MySQL.Enabled")) {
sender.sendMessage(Utils.format("&cThis option is (temporarily) only available for NametagEdit servers that use a database."));
return;
}

if (args.length <= 2) {
sender.sendMessage(Utils.format("&cBe sure to enter the group order!"));
return;
}

handler.getAbstractConfig().orderGroups(sender, args);
} else if (args[1].equalsIgnoreCase("remove")) {
if (args.length == 3) {
String group = args[2];
Expand Down
25 changes: 24 additions & 1 deletion src/main/java/com/nametagedit/plugin/NametagHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import com.nametagedit.plugin.storage.data.GroupData;
import com.nametagedit.plugin.storage.data.PlayerData;
import com.nametagedit.plugin.storage.database.DatabaseConfig;
import com.nametagedit.plugin.storage.database.tasks.GroupConfigUpdater;
import com.nametagedit.plugin.storage.flatfile.FlatFileConfig;
import com.nametagedit.plugin.utils.UUIDFetcher;
import com.nametagedit.plugin.utils.Utils;
Expand Down Expand Up @@ -166,6 +167,28 @@ private void handleClear(UUID uuid, String player) {
abstractConfig.clear(uuid, player);
}

public void loadDatabaseSettings(HashMap<String, String> settings) {
String orderSetting = settings.get("order");
if (orderSetting != null) {
String[] order = orderSetting.split(" ");
List<GroupData> current = new ArrayList<>();
// Determine order for current loaded groups
for (String group : order) {
Iterator<GroupData> itr = groupData.iterator();
while (itr.hasNext()) {
GroupData groupData = itr.next();
if (groupData.getGroupName().equalsIgnoreCase(group)) {
current.add(groupData);
itr.remove();
break;
}
}
}
current.addAll(groupData); // Add remaining entries (bad order, wasn't specified)
this.groupData = current;
}
}

public void applyTags() {
for (Player online : Utils.getOnline()) {
if (online != null) {
Expand All @@ -175,13 +198,13 @@ public void applyTags() {
}

public void applyTagToPlayer(Player player) {
if (player == null) { return; }
UUID uuid = player.getUniqueId();
PlayerData data = playerData.get(uuid);
if (data != null) {
plugin.getManager().updateNametag(player.getName(), Utils.format(data.getPrefix(), true), Utils.format(data.getSuffix(), true));
} else {
for (GroupData group : groupData) {
System.out.println("Group order: " + group.getGroupName());
if (player.hasPermission(group.getBukkitPermission())) {
plugin.getManager().updateNametag(player.getName(), Utils.format(group.getPrefix(), true), Utils.format(group.getSuffix(), true));
break;
Expand Down
38 changes: 21 additions & 17 deletions src/main/java/com/nametagedit/plugin/converter/ConverterTask.java
Original file line number Diff line number Diff line change
Expand Up @@ -82,27 +82,31 @@ private boolean convertFilesToDatabase(Connection connection) throws SQLExceptio
final YamlConfiguration players = Utils.getConfig(playersFile);

PreparedStatement insertOrUpdate = connection.prepareStatement(PLAYER_SAVER);
for (String key : players.getConfigurationSection("Players").getKeys(false)) {
insertOrUpdate.setString(1, key);
insertOrUpdate.setString(2, players.getString("Players." + key + ".Name"));
insertOrUpdate.setString(3, Utils.deformat(players.getString("Players." + key + ".Prefix", "")));
insertOrUpdate.setString(4, Utils.deformat(players.getString("Players." + key + ".Suffix", "")));
insertOrUpdate.setString(5, Utils.deformat(players.getString("Players." + key + ".Prefix", "")));
insertOrUpdate.setString(6, Utils.deformat(players.getString("Players." + key + ".Suffix", "")));
insertOrUpdate.addBatch();
if (players != null) {
for (String key : players.getConfigurationSection("Players").getKeys(false)) {
insertOrUpdate.setString(1, key);
insertOrUpdate.setString(2, players.getString("Players." + key + ".Name"));
insertOrUpdate.setString(3, Utils.deformat(players.getString("Players." + key + ".Prefix", "")));
insertOrUpdate.setString(4, Utils.deformat(players.getString("Players." + key + ".Suffix", "")));
insertOrUpdate.setString(5, Utils.deformat(players.getString("Players." + key + ".Prefix", "")));
insertOrUpdate.setString(6, Utils.deformat(players.getString("Players." + key + ".Suffix", "")));
insertOrUpdate.addBatch();
}
}

insertOrUpdate.executeBatch();
insertOrUpdate = connection.prepareStatement(GROUP_SAVER);
for (String key : groups.getConfigurationSection("Groups").getKeys(false)) {
insertOrUpdate.setString(1, key);
insertOrUpdate.setString(2, groups.getString("Groups." + key + ".Permission"));
insertOrUpdate.setString(3, Utils.deformat(groups.getString("Groups." + key + ".Prefix", "")));
insertOrUpdate.setString(4, Utils.deformat(groups.getString("Groups." + key + ".Suffix", "")));
insertOrUpdate.setString(5, Utils.deformat(groups.getString("Groups." + key + ".Prefix", "")));
insertOrUpdate.setString(6, Utils.deformat(groups.getString("Groups." + key + ".Suffix", "")));
insertOrUpdate.setString(7, groups.getString("Groups." + key + ".Permission"));
insertOrUpdate.addBatch();
if (groups != null) {
for (String key : groups.getConfigurationSection("Groups").getKeys(false)) {
insertOrUpdate.setString(1, key);
insertOrUpdate.setString(2, groups.getString("Groups." + key + ".Permission"));
insertOrUpdate.setString(3, Utils.deformat(groups.getString("Groups." + key + ".Prefix", "")));
insertOrUpdate.setString(4, Utils.deformat(groups.getString("Groups." + key + ".Suffix", "")));
insertOrUpdate.setString(5, Utils.deformat(groups.getString("Groups." + key + ".Prefix", "")));
insertOrUpdate.setString(6, Utils.deformat(groups.getString("Groups." + key + ".Suffix", "")));
insertOrUpdate.setString(7, groups.getString("Groups." + key + ".Permission"));
insertOrUpdate.addBatch();
}
}

insertOrUpdate.executeBatch();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.nametagedit.plugin.storage.data.GroupData;
import com.nametagedit.plugin.storage.data.PlayerData;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import java.util.UUID;
Expand All @@ -26,4 +27,6 @@ public interface AbstractConfig {

void clear(UUID uuid, String targetName);

void orderGroups(CommandSender commandSender, String[] args);

}
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,15 @@
import com.nametagedit.plugin.storage.data.GroupData;
import com.nametagedit.plugin.storage.data.PlayerData;
import com.nametagedit.plugin.storage.database.tasks.*;
import com.nametagedit.plugin.utils.Utils;
import com.zaxxer.hikari.HikariDataSource;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

public class DatabaseConfig implements AbstractConfig {
Expand Down Expand Up @@ -40,13 +45,13 @@ public void load() {

@Override
public void reload() {
new DataDownloader(handler, hikari).runTask(plugin);
new DataDownloader(handler, hikari).runTaskAsynchronously(plugin);
}

@Override
public void shutdown() {
if (hikari != null) {
hikari.shutdown();
hikari.close();
}
}

Expand Down Expand Up @@ -80,4 +85,15 @@ public void clear(UUID uuid, String targetName) {
new PlayerDeleter(uuid, hikari).runTaskAsynchronously(plugin);
}

@Override
public void orderGroups(CommandSender commandSender, String[] args) {
List<String> order = new ArrayList<>(Arrays.asList(args).subList(2, args.length));
String formatted = Arrays.toString(order.toArray());
formatted = formatted.substring(1, formatted.length() - 1).replace(",", "");
commandSender.sendMessage(Utils.format("&c&lNametagEdit Group Order:"));
commandSender.sendMessage(formatted);
commandSender.sendMessage(Utils.format("&cType /ne reload for these changes to take effect"));
new GroupConfigUpdater("order", formatted, hikari).runTaskAsynchronously(handler.getPlugin());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ public DataDownloader(NametagHandler handler, HikariDataSource hikari) {

@Override
public void run() {
final HashMap<String, String> settings = new HashMap<>();
final List<GroupData> groupData = new ArrayList<>();
final Map<UUID, PlayerData> playerData = new HashMap<>();

Expand All @@ -56,6 +57,11 @@ public void run() {
}
}

results = connection.prepareStatement("SELECT setting,value FROM nte_config").executeQuery();
while (results.next()) {
settings.put(results.getString("setting"), results.getString("value"));
}

results.close();
} catch (SQLException e) {
e.printStackTrace();
Expand All @@ -65,7 +71,7 @@ public void run() {
public void run() {
handler.setGroupData(groupData);
handler.setPlayerData(playerData);

handler.loadDatabaseSettings(settings);
for (Player player : Bukkit.getOnlinePlayers()) {
PlayerData data = playerData.get(player.getUniqueId());
if (data != null) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.nametagedit.plugin.storage.database.tasks;

import com.zaxxer.hikari.HikariDataSource;
import lombok.AllArgsConstructor;
import org.bukkit.scheduler.BukkitRunnable;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@AllArgsConstructor
public class GroupConfigUpdater extends BukkitRunnable {

private String setting;
private String value;
private HikariDataSource hikari;

@Override
public void run() {
try (Connection connection = hikari.getConnection()) {
String query = "INSERT INTO nte_config VALUES(?, ?) ON DUPLICATE KEY UPDATE value=?";
PreparedStatement update = connection.prepareStatement(query);
update.setString(1, setting);
update.setString(2, value);
update.setString(3, value);
update.execute();
update.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ public class PlayerLoader extends BukkitRunnable {
public void run() {
String tempPrefix = null;
String tempSuffix = null;
boolean found = false;

try (Connection connection = hikari.getConnection()) {
String query = "SELECT prefix,suffix FROM nte_players WHERE uuid=?";
Expand All @@ -38,6 +39,7 @@ public void run() {
if (resultSet.next()) {
tempPrefix = resultSet.getString("prefix");
tempSuffix = resultSet.getString("suffix");
found = true;
}

resultSet.close();
Expand All @@ -46,19 +48,22 @@ public void run() {
} finally {
final String prefix = tempPrefix == null ? "" : tempPrefix;
final String suffix = tempSuffix == null ? "" : tempSuffix;
final boolean finalFound = found;

new BukkitRunnable() {
@Override
public void run() {
Player player = Bukkit.getPlayer(uuid);
if (player != null) {
PlayerData data = handler.getPlayerData(player);
if (data == null) {
data = new PlayerData(player.getName(), player.getUniqueId(), prefix, suffix);
handler.getPlayerData().put(player.getUniqueId(), data);
} else {
data.setPrefix(prefix);
data.setSuffix(suffix);
if (finalFound) {
PlayerData data = handler.getPlayerData(player);
if (data == null) {
data = new PlayerData(player.getName(), player.getUniqueId(), prefix, suffix);
handler.getPlayerData().put(player.getUniqueId(), data);
} else {
data.setPrefix(prefix);
data.setSuffix(suffix);
}
}

handler.applyTagToPlayer(player);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ public class TableCreator extends BukkitRunnable {
private HikariDataSource hikari;

private final List<String> QUERIES = new ArrayList<String>() {{
add("CREATE TABLE IF NOT EXISTS `nte_config` (`setting` varchar(16) NOT NULL, `value` varchar(200) NOT NULL, PRIMARY KEY (`setting`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;");
add("CREATE TABLE IF NOT EXISTS `nte_players` (`uuid` varchar(64) NOT NULL, `name` varchar(16) NOT NULL, `prefix` varchar(16) NOT NULL, `suffix` varchar(16) NOT NULL, PRIMARY KEY (`uuid`))");
add("CREATE TABLE IF NOT EXISTS `nte_groups` (`name` varchar(64) NOT NULL, `permission` varchar(16) NOT NULL, `prefix` varchar(16) NOT NULL, `suffix` varchar(16) NOT NULL, PRIMARY KEY (`name`))");
}};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import com.nametagedit.plugin.storage.data.PlayerData;
import com.nametagedit.plugin.utils.Utils;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;

Expand Down Expand Up @@ -97,6 +98,11 @@ public void clear(UUID uuid, String targetName) {
save(players, playersFile);
}

@Override
public void orderGroups(CommandSender commandSender, String[] args) {
// TODO: Not implemented yet
}

private void save(YamlConfiguration config, File file) {
try {
config.save(file);
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/com/nametagedit/plugin/utils/Utils.java
Original file line number Diff line number Diff line change
Expand Up @@ -86,10 +86,11 @@ public static YamlConfiguration getConfig(File file) {
if (!file.exists()) {
file.createNewFile();
}
return YamlConfiguration.loadConfiguration(file);
} catch (IOException e) {
e.printStackTrace();
return null;
}
return YamlConfiguration.loadConfiguration(file);
}

public static YamlConfiguration getConfig(File file, String resource, Plugin plugin) {
Expand Down

0 comments on commit 331a88f

Please sign in to comment.