This commit is contained in:
boy0001 2015-08-13 03:45:24 +10:00
parent 5e38d032e0
commit 160ac794e1
8 changed files with 254 additions and 179 deletions

View File

@ -633,7 +633,7 @@ public class PS {
* @return * @return
*/ */
@Deprecated @Deprecated
public static ArrayList<Plot> sortPlotsByTimestamp(Collection<Plot> input) { public ArrayList<Plot> sortPlotsByTimestamp(Collection<Plot> input) {
List<Plot> list; List<Plot> list;
if (input instanceof ArrayList<?>) { if (input instanceof ArrayList<?>) {
list = (List<Plot>) input; list = (List<Plot>) input;
@ -812,7 +812,7 @@ public class PS {
* @deprecated Unchecked, use {@link #sortPlots(Collection, SortType, String)} instead which will in turn call this * @deprecated Unchecked, use {@link #sortPlots(Collection, SortType, String)} instead which will in turn call this
* @param input * @param input
*/ */
public static void sortPlotsByHash(Plot[] input) { public void sortPlotsByHash(Plot[] input) {
List<Plot>[] bucket = new ArrayList[64]; List<Plot>[] bucket = new ArrayList[64];
for (int i = 0; i < bucket.length; i++) { for (int i = 0; i < bucket.length; i++) {
bucket[i] = new ArrayList<Plot>(); bucket[i] = new ArrayList<Plot>();
@ -845,7 +845,7 @@ public class PS {
* @deprecated Unchecked, use {@link #sortPlots(Collection, SortType, String)} instead which will in turn call this * @deprecated Unchecked, use {@link #sortPlots(Collection, SortType, String)} instead which will in turn call this
*/ */
@Deprecated @Deprecated
public static void sortPlotsByTimestamp(Plot[] input) { public void sortPlotsByTimestamp(Plot[] input) {
final int SIZE = 100; final int SIZE = 100;
List<Plot>[] bucket = new ArrayList[SIZE]; List<Plot>[] bucket = new ArrayList[SIZE];
for (int i = 0; i < bucket.length; i++) { for (int i = 0; i < bucket.length; i++) {
@ -1049,9 +1049,13 @@ public class PS {
*/ */
@Deprecated @Deprecated
public HashMap<PlotId, Plot> getPlots(final String world) { public HashMap<PlotId, Plot> getPlots(final String world) {
if (plots.containsKey(world)) { ConcurrentHashMap<PlotId, Plot> myplots = plots.get(world);
if (myplots != null) {
if (world == lastWorld) {
return new HashMap<>(lastMap); return new HashMap<>(lastMap);
} }
return new HashMap<>(myplots);
}
return new HashMap<>(); return new HashMap<>();
} }
@ -1535,58 +1539,49 @@ public class PS {
* Setup the database connection * Setup the database connection
*/ */
public void setupDatabase() { public void setupDatabase() {
if (Settings.DB.USE_MYSQL) {
try { try {
database = new MySQL(Settings.DB.HOST_NAME, Settings.DB.PORT, Settings.DB.DATABASE, Settings.DB.USER, Settings.DB.PASSWORD); if (Settings.DB.USE_MONGO) {
connection = database.openConnection();
{
if (DBFunc.dbManager == null) {
DBFunc.dbManager = new SQLManager(connection, Settings.DB.PREFIX);
}
DBFunc.createTables("mysql");
}
} catch (final Exception e) {
log("&c[Plots] MySQL is not setup correctly. The plugin will disable itself.");
if ((config == null) || config.getBoolean("debug")) {
log("&d==== Here is an ugly stacktrace if you are interested in those things ====");
e.printStackTrace();
log("&d==== End of stacktrace ====");
log("&6Please go to the PlotSquared 'storage.yml' and configure MySQL correctly.");
}
IMP.disable();
return;
}
plots = DBFunc.getPlots();
if (Settings.ENABLE_CLUSTERS) {
ClusterManager.clusters = DBFunc.getClusters();
}
} else if (Settings.DB.USE_MONGO) {
// DBFunc.dbManager = new MongoManager();
log(C.PREFIX.s() + "MongoDB is not yet implemented"); log(C.PREFIX.s() + "MongoDB is not yet implemented");
} else if (Settings.DB.USE_SQLITE) {
try {
this.database = new SQLite(IMP.getDirectory() + File.separator + Settings.DB.SQLITE_DB + ".db");
connection = this.database.openConnection();
{
DBFunc.dbManager = new SQLManager(connection, Settings.DB.PREFIX);
final DatabaseMetaData meta = connection.getMetaData();
meta.getTables(null, null, Settings.DB.PREFIX + "plot", null);
DBFunc.createTables("sqlite");
}
} catch (final Exception e) {
log(C.PREFIX.s() + "&cFailed to open SQLite connection. The plugin will disable itself.");
log("&9==== Here is an ugly stacktrace, if you are interested in those things ===");
e.printStackTrace();
IMP.disable();
return;
}
plots = DBFunc.getPlots();
if (Settings.ENABLE_CLUSTERS) {
ClusterManager.clusters = DBFunc.getClusters();
}
} else {
log(C.PREFIX + "&cNo storage type is set!"); log(C.PREFIX + "&cNo storage type is set!");
IMP.disable(); IMP.disable();
return;
}
if (DBFunc.dbManager == null) {
if (Settings.DB.USE_MYSQL) {
database = new MySQL(Settings.DB.HOST_NAME, Settings.DB.PORT, Settings.DB.DATABASE, Settings.DB.USER, Settings.DB.PASSWORD);
}
else if (Settings.DB.USE_SQLITE) {
database = new SQLite(IMP.getDirectory() + File.separator + Settings.DB.SQLITE_DB + ".db");
}
else {
log(C.PREFIX + "&cNo storage type is set!");
IMP.disable();
return;
}
}
DBFunc.dbManager = new SQLManager(database, Settings.DB.PREFIX, false);
plots = DBFunc.getPlots();
if (Settings.ENABLE_CLUSTERS) {
ClusterManager.clusters = DBFunc.getClusters();
}
}
catch (Exception e) {
log(C.PREFIX.s() + "&cFailed to open DATABASE connection. The plugin will disable itself.");
if (Settings.DB.USE_MONGO) {
log("$4MONGO");
}
else if (Settings.DB.USE_MYSQL) {
log("$4MYSQL");
}
else if (Settings.DB.USE_SQLITE) {
log("$4SQLITE");
}
log("&d==== Here is an ugly stacktrace, if you are interested in those things ===");
e.printStackTrace();
log("&d==== End of stacktrace ====");
log("&6Please go to the PlotSquared 'storage.yml' and configure the database correctly.");
IMP.disable();
return;
} }
} }

View File

@ -1,19 +1,18 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import java.sql.Connection; import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.UUID; import java.util.Arrays;
import java.util.HashSet;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.database.MySQL; import com.intellectualcrafters.plot.database.MySQL;
import com.intellectualcrafters.plot.database.SQLManager; import com.intellectualcrafters.plot.database.SQLManager;
import com.intellectualcrafters.plot.database.SQLite;
import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.StringComparison;
import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.general.commands.CommandDeclaration; import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration( @CommandDeclaration(
@ -23,27 +22,12 @@ import com.plotsquared.general.commands.CommandDeclaration;
permission = "plots.database", permission = "plots.database",
description = "Convert/Backup Storage", description = "Convert/Backup Storage",
requiredType = RequiredType.CONSOLE, requiredType = RequiredType.CONSOLE,
usage = "/plots database <type> [details...]" usage = "/plots database [world] <sqlite|mysql>"
) )
public class Database extends SubCommand { public class Database extends SubCommand {
private static boolean sendMessageU(final UUID uuid, final String msg) { public static void insertPlots(final SQLManager manager, final ArrayList<Plot> plots, final PlotPlayer player) {
if (uuid == null) {
PS.debug(msg);
} else {
final PlotPlayer p = UUIDHandler.getPlayer(uuid);
if ((p != null) && p.isOnline()) {
return MainUtil.sendMessage(p, msg);
} else {
return sendMessageU(null, msg);
}
}
return true;
}
public static void insertPlots(final SQLManager manager, final UUID requester, final Connection c) {
final java.util.Set<Plot> plots = PS.get().getPlots();
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(new Runnable() {
@Override @Override
public void run() { public void run() {
@ -52,20 +36,16 @@ public class Database extends SubCommand {
for (final Plot p : plots) { for (final Plot p : plots) {
ps.add(p); ps.add(p);
} }
sendMessageU(requester, "&6Starting..."); MainUtil.sendMessage(player, "&6Starting...");
manager.createPlotsAndData(ps, new Runnable() { manager.createPlotsAndData(ps, new Runnable() {
@Override @Override
public void run() { public void run() {
sendMessageU(requester, "&6Database conversion finished!"); MainUtil.sendMessage(player, "&6Database conversion finished!");
manager.close();
} }
}); });
} catch (final Exception e) { } catch (final Exception e) {
sendMessageU(requester, "Failed to insert plot objects, see stacktrace for info"); MainUtil.sendMessage(player, "Failed to insert plot objects, see stacktrace for info");
e.printStackTrace();
}
try {
c.close();
} catch (final SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -73,61 +53,72 @@ public class Database extends SubCommand {
} }
@Override @Override
public boolean onCommand(PlotPlayer plr, String[] args) { public boolean onCommand(PlotPlayer player, String[] args) {
if (args.length < 1) { if (args.length < 1) {
return sendMessage(plr, "/plot database [sqlite/mysql]"); MainUtil.sendMessage(player, "/plot database [world] <sqlite|mysql>");
return false;
} }
final String type = new StringComparison(args[0], new String[] { "mysql", "sqlite" }).getBestMatch().toLowerCase(); ArrayList<Plot> plots;
switch (type) { if (PS.get().isPlotWorld(args[0])) {
plots = PS.get().sortPlotsByTemp(PS.get().getPlotsInWorld(args[0]));
args = Arrays.copyOfRange(args, 1, args.length);
}
else {
plots = PS.get().sortPlotsByTemp(PS.get().getPlotsRaw());
}
if (args.length < 1) {
MainUtil.sendMessage(player, "/plot database [world] <sqlite|mysql>");
MainUtil.sendMessage(player, "[arg] indicates an optional argument");
return false;
}
try {
com.intellectualcrafters.plot.database.Database implementation;
String prefix = "";
switch (args[0].toLowerCase()) {
case "mysql": case "mysql":
if (args.length < 6) { if (args.length < 6) {
return sendMessage(plr, "/plot database mysql [host] [port] [username] [password] [database] {prefix}"); return MainUtil.sendMessage(player, "/plot database mysql [host] [port] [username] [password] [database] {prefix}");
} }
final String host = args[1]; final String host = args[1];
final String port = args[2]; final String port = args[2];
final String username = args[3]; final String username = args[3];
final String password = args[4]; final String password = args[4];
final String database = args[5]; final String database = args[5];
String prefix = "";
if (args.length > 6) { if (args.length > 6) {
prefix = args[6]; prefix = args[6];
} }
Connection n; implementation = new MySQL(host, port, database, username, password);
try {
n = new MySQL(host, port, database, username, password).openConnection();
// Connection
if (n.isClosed()) {
return sendMessage(plr, "Failed to open connection");
}
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
return sendMessage(plr, "Failed to open connection, read stacktrace for info");
}
final SQLManager manager = new SQLManager(n, prefix);
try {
manager.createTables("mysql");
} catch (final SQLException e) {
e.printStackTrace();
return sendMessage(plr, "Could not create the required tables and/or load the database") && sendMessage(plr, "Please see the stacktrace for more information");
}
UUID requester = null;
requester = UUIDHandler.getUUID(plr);
insertPlots(manager, requester, n);
break; break;
case "sqlite": case "sqlite":
if (args.length < 2) { if (args.length < 2) {
return sendMessage(plr, "/plot database sqlite [file name]"); return MainUtil.sendMessage(player, "/plot database sqlite [file]: " + args.length + " | " + args[0]);
} }
sendMessage(plr, "This is not supported yet"); implementation = new SQLite(PS.get().IMP.getDirectory() + File.separator + args[1] + ".db");
break; break;
default: default:
return sendMessage(plr, "Unknown database type"); return MainUtil.sendMessage(player, "/plot database [sqlite/mysql]");
} }
return false; try {
} final SQLManager manager = new SQLManager(implementation, prefix, true);
insertPlots(manager, plots, player);
private boolean sendMessage(final PlotPlayer player, final String msg) {
MainUtil.sendMessage(player, msg);
return true; return true;
} }
catch (Exception e) {
MainUtil.sendMessage(player, "$1Failed to save plots, read stacktrace for info");
MainUtil.sendMessage(player, "&d==== Here is an ugly stacktrace, if you are interested in those things ===");
e.printStackTrace();
MainUtil.sendMessage(player, "&d==== End of stacktrace ====");
MainUtil.sendMessage(player, "$1Please make sure you are using the correct arguments!");
return false;
}
}
catch (Exception e) {
MainUtil.sendMessage(player, "$1Failed to open connection, read stacktrace for info");
MainUtil.sendMessage(player, "&d==== Here is an ugly stacktrace, if you are interested in those things ===");
e.printStackTrace();
MainUtil.sendMessage(player, "&d==== End of stacktrace ====");
MainUtil.sendMessage(player, "$1Please make sure you are using the correct arguments!");
return false;
}
}
} }

View File

@ -41,6 +41,7 @@ import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration( @CommandDeclaration(
command = "flag", command = "flag",
aliases = {"f"}, aliases = {"f"},
usage = "/plot flag <set|remove|add|list|info> <flag> <value>",
description = "Manage plot flags", description = "Manage plot flags",
category = CommandCategory.ACTIONS, category = CommandCategory.ACTIONS,
requiredType = RequiredType.NONE, requiredType = RequiredType.NONE,
@ -48,6 +49,11 @@ import com.plotsquared.general.commands.CommandDeclaration;
) )
public class FlagCmd extends SubCommand { public class FlagCmd extends SubCommand {
@Override
public String getUsage() {
return super.getUsage().replaceAll("<flag>", StringMan.join(FlagManager.getFlags(), "|"));
}
@Override @Override
public boolean onCommand(final PlotPlayer player, final String ... args) { public boolean onCommand(final PlotPlayer player, final String ... args) {

View File

@ -22,6 +22,7 @@ package com.intellectualcrafters.plot.commands;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
@ -136,7 +137,7 @@ public class MainCommand extends CommandManager<PlotPlayer> {
return false; return false;
} }
public static List<Command<PlotPlayer>> getCommands(final CommandCategory category, final PlotPlayer player) { public static List<Command<PlotPlayer>> getCommandAndAliases(final CommandCategory category, final PlotPlayer player) {
List<Command<PlotPlayer>> commands = new ArrayList<>(); List<Command<PlotPlayer>> commands = new ArrayList<>();
for (Command<PlotPlayer> command : getInstance().getCommands()) { for (Command<PlotPlayer> command : getInstance().getCommands()) {
if (category != null && !command.getCategory().equals(category)) { if (category != null && !command.getCategory().equals(category)) {
@ -150,6 +151,20 @@ public class MainCommand extends CommandManager<PlotPlayer> {
return commands; return commands;
} }
public static List<Command<PlotPlayer>> getCommands(final CommandCategory category, final PlotPlayer player) {
List<Command<PlotPlayer>> commands = new ArrayList<>();
for (Command<PlotPlayer> command : new HashSet<>(getInstance().getCommands())) {
if (category != null && !command.getCategory().equals(category)) {
continue;
}
if (player != null && !Permissions.hasPermission(player, command.getPermission())) {
continue;
}
commands.add(command);
}
return commands;
}
//// public static List<String> helpMenu(final PlotPlayer player, final CommandCategory category, int page) { //// public static List<String> helpMenu(final PlotPlayer player, final CommandCategory category, int page) {
// List<Command<PlotPlayer>> commands; // List<Command<PlotPlayer>> commands;
// // commands = getCommands(category, player); // // commands = getCommands(category, player);
@ -338,10 +353,57 @@ public class MainCommand extends CommandManager<PlotPlayer> {
MainUtil.sendMessage(plr, C.NOT_VALID_SUBCOMMAND); MainUtil.sendMessage(plr, C.NOT_VALID_SUBCOMMAND);
{ {
List<Command<PlotPlayer>> cmds = getCommands(null, plr); List<Command<PlotPlayer>> cmds = getCommands(null, plr);
if (label == null || cmds.size() == 0 || (cmd = new StringComparison<>(label, cmds).getMatchObject()) == null) { if (label == null || cmds.size() == 0) {
MainUtil.sendMessage(plr, C.DID_YOU_MEAN, "/plot help"); MainUtil.sendMessage(plr, C.DID_YOU_MEAN, "/plot help");
} }
else { else {
HashSet<String> setargs = new HashSet<>(args.length + 1);
for (String arg : args) {
setargs.add(arg.toLowerCase());
}
setargs.add(label.toLowerCase());
String[] allargs = setargs.toArray(new String[setargs.size()]);
int best = 0;
for (Command<PlotPlayer> current : cmds) {
if (current.getUsage() != null) {
int count = 0;
for (String word : new HashSet<String>(Arrays.asList((current.getUsage() + " " + current.getPermission() + " " + current.getCategory().name()).toLowerCase().replaceAll("\\||\\>|\\<|\\[|\\]|\\{|\\}|\\_|\\/", " ").trim().replaceAll("\\s+", " ").split(" ")))) {
for (int i = 0; i < allargs.length; i++) {
String arg = allargs[i];
if (best - count - (allargs.length - i) * 3 >= 0) {
continue;
}
if (StringMan.isEqual(arg, word)) {
count+=3;
}
else if (word.length() > arg.length() && word.contains(arg)) {
count+=2;
}
}
}
for (String word : new HashSet<String>(Arrays.asList((current.getDescription()).toLowerCase().replaceAll("\\||\\>|\\<|\\[|\\]|\\{|\\}|\\_|\\/", " ").trim().replaceAll("\\s+", " ").split(" ")))) {
for (int i = 0; i < allargs.length; i++) {
String arg = allargs[i];
if (best - count - (allargs.length - i) * 2 >= 0) {
continue;
}
if (StringMan.isEqual(arg, word)) {
count+=2;
}
else if (word.length() > arg.length() && word.contains(arg)) {
count++;
}
}
}
if (count > best) {
best = count;
cmd = current;
}
}
}
if (cmd == null) {
cmd = new StringComparison<>(label, getCommandAndAliases(null, plr)).getMatchObject();
}
MainUtil.sendMessage(plr, C.DID_YOU_MEAN, cmd.getUsage().replaceAll("\\{label\\}", parts[0])); MainUtil.sendMessage(plr, C.DID_YOU_MEAN, cmd.getUsage().replaceAll("\\{label\\}", parts[0]));
} }
} }

View File

@ -54,7 +54,7 @@ import com.plotsquared.listener.PlotListener;
command = "set", command = "set",
description = "Set a plot value", description = "Set a plot value",
aliases = {"s"}, aliases = {"s"},
usage = "/plot set <arg> <value(s)...>", usage = "/plot set <biome|alias|home|flag> <value...>",
permission = "plots.set", permission = "plots.set",
category = CommandCategory.ACTIONS, category = CommandCategory.ACTIONS,
requiredType = RequiredType.NONE requiredType = RequiredType.NONE

View File

@ -42,6 +42,7 @@ import com.intellectualcrafters.plot.object.comment.PlotComment;
* @author Empire92 * @author Empire92
*/ */
public interface AbstractDB { public interface AbstractDB {
/** /**
* The UUID that will count as everyone * The UUID that will count as everyone
*/ */
@ -76,7 +77,7 @@ public interface AbstractDB {
* *
* @throws SQLException If the database manager is unable to create the tables * @throws SQLException If the database manager is unable to create the tables
*/ */
void createTables(final String database) throws Exception; void createTables() throws Exception;
/** /**
* Delete a plot * Delete a plot

View File

@ -71,8 +71,12 @@ public class SQLManager implements AbstractDB {
public final String CREATE_PLOT; public final String CREATE_PLOT;
public final String CREATE_CLUSTER; public final String CREATE_CLUSTER;
private final String prefix; private final String prefix;
// Private Final // Private
private Connection connection; private Connection connection;
private boolean CLOSED = false;
// Private Final
private final Database database;
private final boolean MYSQL;
/** /**
* important tasks * important tasks
@ -97,9 +101,13 @@ public class SQLManager implements AbstractDB {
* cluster_settings * cluster_settings
*/ */
public volatile ConcurrentHashMap<PlotCluster, Queue<UniqueStatement>> clusterTasks; public volatile ConcurrentHashMap<PlotCluster, Queue<UniqueStatement>> clusterTasks;
private boolean debug;
public synchronized Queue<Runnable> getGlobalTasks() {
return globalTasks;
}
public void addPlotTask(Plot plot, UniqueStatement task) { public synchronized void addPlotTask(Plot plot, UniqueStatement task) {
if (plot == null) { if (plot == null) {
plot = new Plot("", new PlotId(Integer.MAX_VALUE, Integer.MAX_VALUE), null); plot = new Plot("", new PlotId(Integer.MAX_VALUE, Integer.MAX_VALUE), null);
} }
@ -130,7 +138,7 @@ public class SQLManager implements AbstractDB {
tasks.add(task); tasks.add(task);
} }
public void addClusterTask(PlotCluster cluster, UniqueStatement task) { public synchronized void addClusterTask(PlotCluster cluster, UniqueStatement task) {
Queue<UniqueStatement> tasks = clusterTasks.get(cluster); Queue<UniqueStatement> tasks = clusterTasks.get(cluster);
if (tasks == null) { if (tasks == null) {
tasks = new ConcurrentLinkedQueue<>(); tasks = new ConcurrentLinkedQueue<>();
@ -139,8 +147,8 @@ public class SQLManager implements AbstractDB {
tasks.add(task); tasks.add(task);
} }
public void addGlobalTask(Runnable task) { public synchronized void addGlobalTask(Runnable task) {
globalTasks.add(task); getGlobalTasks().add(task);
} }
@ -149,10 +157,14 @@ public class SQLManager implements AbstractDB {
* *
* @param c connection * @param c connection
* @param p prefix * @param p prefix
* @throws Exception
*/ */
public SQLManager(final Connection c, final String p) { public SQLManager(final Database database, final String p, final boolean debug) throws Exception {
this.debug = debug;
// Private final // Private final
this.connection = c; this.database = database;
this.connection = database.openConnection();
this.MYSQL = (database instanceof MySQL);
globalTasks = new ConcurrentLinkedQueue<>(); globalTasks = new ConcurrentLinkedQueue<>();
plotTasks = new ConcurrentHashMap<>(); plotTasks = new ConcurrentHashMap<>();
clusterTasks = new ConcurrentHashMap<>(); clusterTasks = new ConcurrentHashMap<>();
@ -161,15 +173,15 @@ public class SQLManager implements AbstractDB {
public void run() { public void run() {
long last = System.currentTimeMillis(); long last = System.currentTimeMillis();
while (true) { while (true) {
if (PS.get().getDatabase() == null) { if (CLOSED) {
break; break;
} }
// schedule reconnect // schedule reconnect
if (Settings.DB.USE_MYSQL && System.currentTimeMillis() - last > 550000) { if (MYSQL && System.currentTimeMillis() - last > 550000) {
last = System.currentTimeMillis(); last = System.currentTimeMillis();
try { try {
close(); close();
connection = PS.get().getDatabase().forceConnection(); connection = database.forceConnection();
} catch (SQLException | ClassNotFoundException e) { } catch (SQLException | ClassNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -196,15 +208,16 @@ public class SQLManager implements AbstractDB {
this.CREATE_PLOT = "INSERT INTO `" + this.prefix + "plot`(`plot_id_x`, `plot_id_z`, `owner`, `world`, `timestamp`) VALUES(?, ?, ?, ?, ?)"; this.CREATE_PLOT = "INSERT INTO `" + this.prefix + "plot`(`plot_id_x`, `plot_id_z`, `owner`, `world`, `timestamp`) VALUES(?, ?, ?, ?, ?)";
this.CREATE_CLUSTER = "INSERT INTO `" + this.prefix + "cluster`(`pos1_x`, `pos1_z`, `pos2_x`, `pos2_z`, `owner`, `world`) VALUES(?, ?, ?, ?, ?, ?)"; this.CREATE_CLUSTER = "INSERT INTO `" + this.prefix + "cluster`(`pos1_x`, `pos1_z`, `pos2_x`, `pos2_z`, `owner`, `world`) VALUES(?, ?, ?, ?, ?, ?)";
updateTables(); updateTables();
createTables();
} }
public boolean sendBatch() { public boolean sendBatch() {
try { try {
if (globalTasks.size() > 0) { if (getGlobalTasks().size() > 0) {
if (connection.getAutoCommit()) { if (connection.getAutoCommit()) {
connection.setAutoCommit(false); connection.setAutoCommit(false);
} }
Runnable task = globalTasks.remove(); Runnable task = getGlobalTasks().remove();
if (task != null) { if (task != null) {
task.run(); task.run();
} }
@ -530,7 +543,7 @@ public class SQLManager implements AbstractDB {
try { try {
stmt.setString((i * 4) + 3, plot.owner.toString()); stmt.setString((i * 4) + 3, plot.owner.toString());
} catch (final Exception e) { } catch (final Exception e) {
stmt.setString((i * 4) + 3, DBFunc.everyone.toString()); stmt.setString((i * 4) + 3, everyone.toString());
} }
stmt.setString((i * 5) + 4, plot.world); stmt.setString((i * 5) + 4, plot.world);
stmt.setTimestamp((i * 5) + 5, new Timestamp(plot.getTimestamp())); stmt.setTimestamp((i * 5) + 5, new Timestamp(plot.getTimestamp()));
@ -544,7 +557,7 @@ public class SQLManager implements AbstractDB {
try { try {
stmt.setString((i * 6) + 4, plot.owner.toString()); stmt.setString((i * 6) + 4, plot.owner.toString());
} catch (final Exception e1) { } catch (final Exception e1) {
stmt.setString((i * 6) + 4, DBFunc.everyone.toString()); stmt.setString((i * 6) + 4, everyone.toString());
} }
stmt.setString((i * 6) + 5, plot.world); stmt.setString((i * 6) + 5, plot.world);
stmt.setTimestamp((i * 6) + 6, new Timestamp(plot.getTimestamp())); stmt.setTimestamp((i * 6) + 6, new Timestamp(plot.getTimestamp()));
@ -570,7 +583,7 @@ public class SQLManager implements AbstractDB {
return; return;
} }
int packet; int packet;
if (Settings.DB.USE_MYSQL) { if (MYSQL) {
packet = Math.min(size, 5000); packet = Math.min(size, 5000);
} else { } else {
packet = Math.min(size, 50); packet = Math.min(size, 50);
@ -612,7 +625,7 @@ public class SQLManager implements AbstractDB {
if (whenDone != null) whenDone.run(); if (whenDone != null) whenDone.run();
return; return;
} catch (Exception e) { } catch (Exception e) {
if (Settings.DB.USE_MYSQL) { if (MYSQL) {
e.printStackTrace(); e.printStackTrace();
PS.debug("&cERROR 1: " + " | " + objList.get(0).getClass().getCanonicalName()); PS.debug("&cERROR 1: " + " | " + objList.get(0).getClass().getCanonicalName());
} }
@ -868,6 +881,9 @@ public class SQLManager implements AbstractDB {
public void commit() { public void commit() {
try { try {
if (CLOSED) {
return;
}
if (!this.connection.getAutoCommit()) { if (!this.connection.getAutoCommit()) {
this.connection.commit(); this.connection.commit();
this.connection.setAutoCommit(true); this.connection.setAutoCommit(true);
@ -928,14 +944,13 @@ public class SQLManager implements AbstractDB {
* @throws SQLException * @throws SQLException
*/ */
@Override @Override
public void createTables(final String database) throws SQLException { public void createTables() throws SQLException {
final String[] tables; final String[] tables;
if (Settings.ENABLE_CLUSTERS) { if (Settings.ENABLE_CLUSTERS) {
tables = new String[]{"plot", "plot_denied", "plot_helpers", "plot_comments", "plot_trusted", "plot_rating", "plot_settings", "cluster"}; tables = new String[]{"plot", "plot_denied", "plot_helpers", "plot_comments", "plot_trusted", "plot_rating", "plot_settings", "cluster"};
} else { } else {
tables = new String[]{"plot", "plot_denied", "plot_helpers", "plot_comments", "plot_trusted", "plot_rating", "plot_settings"}; tables = new String[]{"plot", "plot_denied", "plot_helpers", "plot_comments", "plot_trusted", "plot_rating", "plot_settings"};
} }
final boolean mysql = database.equals("mysql");
final DatabaseMetaData meta = connection.getMetaData(); final DatabaseMetaData meta = connection.getMetaData();
int create = 0; int create = 0;
for (final String s : tables) { for (final String s : tables) {
@ -952,7 +967,7 @@ public class SQLManager implements AbstractDB {
add_constraint = create == tables.length; add_constraint = create == tables.length;
PS.debug("Creating tables"); PS.debug("Creating tables");
final Statement stmt = this.connection.createStatement(); final Statement stmt = this.connection.createStatement();
if (mysql) { if (MYSQL) {
stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + this.prefix + "plot` (" + "`id` INT(11) NOT NULL AUTO_INCREMENT," + "`plot_id_x` INT(11) NOT NULL," + "`plot_id_z` INT(11) NOT NULL," + "`owner` VARCHAR(40) NOT NULL," + "`world` VARCHAR(45) NOT NULL," + "`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP," + "PRIMARY KEY (`id`)" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=0"); stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + this.prefix + "plot` (" + "`id` INT(11) NOT NULL AUTO_INCREMENT," + "`plot_id_x` INT(11) NOT NULL," + "`plot_id_z` INT(11) NOT NULL," + "`owner` VARCHAR(40) NOT NULL," + "`world` VARCHAR(45) NOT NULL," + "`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP," + "PRIMARY KEY (`id`)" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=0");
stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + this.prefix + "plot_denied` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + this.prefix + "plot_denied` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8");
stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + this.prefix + "plot_helpers` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + this.prefix + "plot_helpers` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8");
@ -1154,6 +1169,9 @@ public class SQLManager implements AbstractDB {
} }
} }
} }
rs.close();
rs = data.getColumns(null, null, this.prefix + "plot_denied", "plot_plot_id");
if (rs.next()) {
try (Statement statement = connection.createStatement()) { try (Statement statement = connection.createStatement()) {
statement.executeUpdate("DELETE FROM `" + this.prefix + "plot_denied` WHERE `plot_plot_id` NOT IN (SELECT `id` FROM `" + this.prefix + "plot`)"); statement.executeUpdate("DELETE FROM `" + this.prefix + "plot_denied` WHERE `plot_plot_id` NOT IN (SELECT `id` FROM `" + this.prefix + "plot`)");
statement.close(); statement.close();
@ -1182,6 +1200,7 @@ public class SQLManager implements AbstractDB {
e2.printStackTrace(); e2.printStackTrace();
} }
} }
}
catch (Exception e) { catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -2351,7 +2370,7 @@ public class SQLManager implements AbstractDB {
public void run() { public void run() {
try { try {
close(); close();
SQLManager.this.connection = PS.get().getDatabase().forceConnection(); SQLManager.this.connection = database.forceConnection();
final Statement stmt = connection.createStatement(); final Statement stmt = connection.createStatement();
stmt.addBatch("DROP TABLE `" + prefix + "cluster_invited`"); stmt.addBatch("DROP TABLE `" + prefix + "cluster_invited`");
stmt.addBatch("DROP TABLE `" + prefix + "cluster_helpers`"); stmt.addBatch("DROP TABLE `" + prefix + "cluster_helpers`");
@ -2524,6 +2543,7 @@ public class SQLManager implements AbstractDB {
@Override @Override
public void close() { public void close() {
try { try {
CLOSED = true;
connection.close(); connection.close();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();

View File

@ -113,7 +113,7 @@ public abstract class Command<E extends CommandCaller> extends CommandManager {
return this.command; return this.command;
} }
final public String getUsage() { public String getUsage() {
if (this.usage.length() == 0) { if (this.usage.length() == 0) {
return "/{label} " + command; return "/{label} " + command;
} }
@ -127,7 +127,7 @@ public abstract class Command<E extends CommandCaller> extends CommandManager {
return this.permission; return this.permission;
} }
final public String getDescription() { public String getDescription() {
return this.description; return this.description;
} }