From 6536e402b4bc28a8905f32309ae63874c4fae48f Mon Sep 17 00:00:00 2001 From: Zrips Date: Tue, 18 Jul 2017 18:01:42 +0300 Subject: [PATCH] New data based handling system, more robust in case of something strange --- pom.xml | 2 +- src/main/java/com/gamingmesh/jobs/Jobs.java | 20 +- .../com/gamingmesh/jobs/PlayerManager.java | 10 + .../jobs/config/GeneralConfigManager.java | 100 +- .../gamingmesh/jobs/dao/JobsClassLoader.java | 28 + .../gamingmesh/jobs/dao/JobsConnection.java | 27 +- .../jobs/dao/JobsConnectionPool.java | 19 +- .../java/com/gamingmesh/jobs/dao/JobsDAO.java | 525 ++++++++-- .../com/gamingmesh/jobs/dao/JobsDAOMySQL.java | 878 ----------------- .../gamingmesh/jobs/dao/JobsDAOSQLite.java | 893 ------------------ .../com/gamingmesh/jobs/dao/JobsDriver.java | 56 -- .../com/gamingmesh/jobs/dao/JobsManager.java | 111 +++ .../com/gamingmesh/jobs/dao/JobsMySQL.java | 250 +++++ .../com/gamingmesh/jobs/dao/JobsSQLite.java | 240 +++++ .../jobs/dao/JobsTableInterface.java | 13 + .../jobs/stuff/JobsClassLoader.java | 45 - src/main/resources/plugin.yml | 4 +- 17 files changed, 1178 insertions(+), 2043 deletions(-) create mode 100644 src/main/java/com/gamingmesh/jobs/dao/JobsClassLoader.java delete mode 100644 src/main/java/com/gamingmesh/jobs/dao/JobsDAOMySQL.java delete mode 100644 src/main/java/com/gamingmesh/jobs/dao/JobsDAOSQLite.java delete mode 100644 src/main/java/com/gamingmesh/jobs/dao/JobsDriver.java create mode 100644 src/main/java/com/gamingmesh/jobs/dao/JobsManager.java create mode 100644 src/main/java/com/gamingmesh/jobs/dao/JobsMySQL.java create mode 100644 src/main/java/com/gamingmesh/jobs/dao/JobsSQLite.java create mode 100644 src/main/java/com/gamingmesh/jobs/dao/JobsTableInterface.java delete mode 100644 src/main/java/com/gamingmesh/jobs/stuff/JobsClassLoader.java diff --git a/pom.xml b/pom.xml index ada3f112..80358b4b 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ 4.0.0 Jobs jobs - 3.9.7 + 3.9.8 Jobs http://maven.apache.org diff --git a/src/main/java/com/gamingmesh/jobs/Jobs.java b/src/main/java/com/gamingmesh/jobs/Jobs.java index 5ef68c56..bcead591 100644 --- a/src/main/java/com/gamingmesh/jobs/Jobs.java +++ b/src/main/java/com/gamingmesh/jobs/Jobs.java @@ -74,8 +74,8 @@ import com.gamingmesh.jobs.container.JobInfo; import com.gamingmesh.jobs.container.JobProgression; import com.gamingmesh.jobs.container.JobsPlayer; import com.gamingmesh.jobs.container.PlayerInfo; +import com.gamingmesh.jobs.dao.*; import com.gamingmesh.jobs.container.FastPayment; -import com.gamingmesh.jobs.dao.JobsDAO; import com.gamingmesh.jobs.economy.BufferedEconomy; import com.gamingmesh.jobs.economy.BufferedPayment; import com.gamingmesh.jobs.economy.Economy; @@ -86,7 +86,6 @@ import com.gamingmesh.jobs.listeners.McMMOlistener; import com.gamingmesh.jobs.listeners.PistonProtectionListener; import com.gamingmesh.jobs.selection.SelectionManager; import com.gamingmesh.jobs.stuff.ActionBar; -import com.gamingmesh.jobs.stuff.JobsClassLoader; import com.gamingmesh.jobs.stuff.Loging; import com.gamingmesh.jobs.stuff.TabComplete; import com.gamingmesh.jobs.stuff.VersionChecker; @@ -115,6 +114,8 @@ public class Jobs extends JavaPlugin { private static Loging loging; private static BlockProtectionManager BpManager = null; + private static JobsManager DBManager = null; + private static PistonProtectionListener PistonProtectionListener = null; private static McMMOlistener McMMOlistener = null; @@ -228,6 +229,12 @@ public class Jobs extends JavaPlugin { return BpManager; } + public static JobsManager getDBManager() { + if (DBManager == null) + DBManager = new JobsManager(instance); + return DBManager; + } + public static void setShopManager(Jobs plugin) { shopManager = new ShopManager(plugin); } @@ -375,6 +382,7 @@ public class Jobs extends JavaPlugin { } protected static Jobs instance; + public static Jobs getInstance() { return instance; } @@ -626,13 +634,7 @@ public class Jobs extends JavaPlugin { * Executes close connections */ public static void ChangeDatabase() { - if (dao != null) { - dao.closeConnections(); - } - if (GconfigManager.storageMethod.equals("mysql")) - GconfigManager.startSqlite(); - else - GconfigManager.startMysql(); + getDBManager().switchDataBase(); pManager.reload(); } diff --git a/src/main/java/com/gamingmesh/jobs/PlayerManager.java b/src/main/java/com/gamingmesh/jobs/PlayerManager.java index df534cbe..2a53241e 100644 --- a/src/main/java/com/gamingmesh/jobs/PlayerManager.java +++ b/src/main/java/com/gamingmesh/jobs/PlayerManager.java @@ -37,6 +37,7 @@ import org.bukkit.entity.Player; import org.bukkit.entity.Tameable; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; + import com.gamingmesh.jobs.api.JobsJoinEvent; import com.gamingmesh.jobs.api.JobsLeaveEvent; import com.gamingmesh.jobs.api.JobsLevelUpEvent; @@ -210,6 +211,15 @@ public class PlayerManager { } } } + + /** + * Save all the information of all of the players + */ + public void saveEntireChacheOfPlayers() { + for (Entry one : playersUUIDCache.entrySet()) { + one.getValue().save(); + } + } /** * Get the player job info for specific player diff --git a/src/main/java/com/gamingmesh/jobs/config/GeneralConfigManager.java b/src/main/java/com/gamingmesh/jobs/config/GeneralConfigManager.java index 9d4cd041..d0500b43 100644 --- a/src/main/java/com/gamingmesh/jobs/config/GeneralConfigManager.java +++ b/src/main/java/com/gamingmesh/jobs/config/GeneralConfigManager.java @@ -39,8 +39,6 @@ import com.gamingmesh.jobs.container.CurrencyLimit; import com.gamingmesh.jobs.container.CurrencyType; import com.gamingmesh.jobs.container.LocaleReader; import com.gamingmesh.jobs.container.Schedule; -import com.gamingmesh.jobs.dao.JobsDAOMySQL; -import com.gamingmesh.jobs.dao.JobsDAOSQLite; import com.gamingmesh.jobs.stuff.ChatColor; import com.gamingmesh.jobs.stuff.VersionChecker.Version; @@ -397,24 +395,26 @@ public class GeneralConfigManager { Jobs.getPluginLogger().warning("Invalid locale \"" + localeString + "\" defaulting to " + locale.getLanguage()); } - c.getW().addComment("storage-method", "storage method, can be MySQL, sqlite"); - storageMethod = c.get("storage-method", "sqlite"); - if (storageMethod.equalsIgnoreCase("mysql")) { - startMysql(); - } else if (storageMethod.equalsIgnoreCase("sqlite")) { - startSqlite(); - } else { - Jobs.getPluginLogger().warning("Invalid storage method! Changing method to sqlite!"); - c.getC().set("storage-method", "sqlite"); - startSqlite(); - } - - c.getW().addComment("mysql-username", "Requires Mysql."); - c.get("mysql-username", "root"); - c.get("mysql-password", ""); - c.get("mysql-hostname", "localhost:3306"); - c.get("mysql-database", "minecraft"); - c.get("mysql-table-prefix", "jobs_"); + Jobs.getDBManager().start(c); + +// c.getW().addComment("storage-method", "storage method, can be MySQL, sqlite"); +// storageMethod = c.get("storage-method", "sqlite"); +// if (storageMethod.equalsIgnoreCase("mysql")) { +// startMysql(); +// } else if (storageMethod.equalsIgnoreCase("sqlite")) { +// startSqlite(); +// } else { +// Jobs.getPluginLogger().warning("Invalid storage method! Changing method to sqlite!"); +// c.getC().set("storage-method", "sqlite"); +// startSqlite(); +// } +// +// c.getW().addComment("mysql-username", "Requires Mysql."); +// c.get("mysql-username", "root"); +// c.get("mysql-password", ""); +// c.get("mysql-hostname", "localhost:3306"); +// c.get("mysql-database", "minecraft"); +// c.get("mysql-table-prefix", "jobs_"); c.getW().addComment("save-period", "How often in minutes you want it to save. This must be a non-zero number"); c.get("save-period", 10); @@ -858,36 +858,36 @@ public class GeneralConfigManager { } } - public synchronized void startMysql() { - File f = new File(plugin.getDataFolder(), "generalConfig.yml"); - YamlConfiguration config = YamlConfiguration.loadConfiguration(f); - String legacyUrl = config.getString("mysql-url"); - if (legacyUrl != null) { - String jdbcString = "jdbc:mysql://"; - if (legacyUrl.toLowerCase().startsWith(jdbcString)) { - legacyUrl = legacyUrl.substring(jdbcString.length()); - String[] parts = legacyUrl.split("/"); - if (parts.length >= 2) { - config.set("mysql-hostname", parts[0]); - config.set("mysql-database", parts[1]); - } - } - } - String username = config.getString("mysql-username"); - if (username == null) { - Jobs.getPluginLogger().severe("mysql-username property invalid or missing"); - } - String password = config.getString("mysql-password"); - String hostname = config.getString("mysql-hostname"); - String database = config.getString("mysql-database"); - String prefix = config.getString("mysql-table-prefix"); - if (plugin.isEnabled()) - Jobs.setDAO(JobsDAOMySQL.initialize(plugin, hostname, database, username, password, prefix)); - } - - public synchronized void startSqlite() { - Jobs.setDAO(JobsDAOSQLite.initialize(plugin)); - } +// public synchronized void startMysql() { +// File f = new File(plugin.getDataFolder(), "generalConfig.yml"); +// YamlConfiguration config = YamlConfiguration.loadConfiguration(f); +// String legacyUrl = config.getString("mysql-url"); +// if (legacyUrl != null) { +// String jdbcString = "jdbc:mysql://"; +// if (legacyUrl.toLowerCase().startsWith(jdbcString)) { +// legacyUrl = legacyUrl.substring(jdbcString.length()); +// String[] parts = legacyUrl.split("/"); +// if (parts.length >= 2) { +// config.set("mysql-hostname", parts[0]); +// config.set("mysql-database", parts[1]); +// } +// } +// } +// String username = config.getString("mysql-username"); +// if (username == null) { +// Jobs.getPluginLogger().severe("mysql-username property invalid or missing"); +// } +// String password = config.getString("mysql-password"); +// String hostname = config.getString("mysql-hostname"); +// String database = config.getString("mysql-database"); +// String prefix = config.getString("mysql-table-prefix"); +// if (plugin.isEnabled()) +// Jobs.setDAO(JobsDAOMySQL.initialize(plugin, hostname, database, username, password, prefix)); +// } +// +// public synchronized void startSqlite() { +// Jobs.setDAO(JobsDAOSQLite.initialize(plugin)); +// } public int getSelectionTooldID() { return getSelectionTooldID; diff --git a/src/main/java/com/gamingmesh/jobs/dao/JobsClassLoader.java b/src/main/java/com/gamingmesh/jobs/dao/JobsClassLoader.java new file mode 100644 index 00000000..eb87c626 --- /dev/null +++ b/src/main/java/com/gamingmesh/jobs/dao/JobsClassLoader.java @@ -0,0 +1,28 @@ +package com.gamingmesh.jobs.dao; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.net.URLClassLoader; + +import com.gamingmesh.jobs.Jobs; + + +public class JobsClassLoader extends URLClassLoader { + + public JobsClassLoader(Jobs core) { + super(new URL[0], core.getClass().getClassLoader()); + } + + public void addFile(File f) throws IOException { + addURL(f.toURI().toURL()); + } + + @Override + public void addURL(URL url) { + for (URL u : getURLs()) + if (url.sameFile(u)) return; + + super.addURL(url); + } +} diff --git a/src/main/java/com/gamingmesh/jobs/dao/JobsConnection.java b/src/main/java/com/gamingmesh/jobs/dao/JobsConnection.java index 56731035..965c7e92 100644 --- a/src/main/java/com/gamingmesh/jobs/dao/JobsConnection.java +++ b/src/main/java/com/gamingmesh/jobs/dao/JobsConnection.java @@ -1,24 +1,7 @@ -/** - * Jobs Plugin for Bukkit - * Copyright (C) 2011 Zak Ford - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - package com.gamingmesh.jobs.dao; import java.sql.Connection; +import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; @@ -59,6 +42,10 @@ public class JobsConnection { return conn.prepareStatement(sql); } + public synchronized PreparedStatement prepareStatement(String sql, int returnGeneratedKeys) throws SQLException { + return conn.prepareStatement(sql, returnGeneratedKeys); + } + public synchronized void setAutoCommit(Boolean mode) throws SQLException { conn.setAutoCommit(mode); } @@ -66,4 +53,8 @@ public class JobsConnection { public synchronized void commit() throws SQLException { conn.commit(); } + + public synchronized DatabaseMetaData getMetaData() throws SQLException { + return conn.getMetaData(); + } } diff --git a/src/main/java/com/gamingmesh/jobs/dao/JobsConnectionPool.java b/src/main/java/com/gamingmesh/jobs/dao/JobsConnectionPool.java index 7e42f00a..fc3f4ecf 100644 --- a/src/main/java/com/gamingmesh/jobs/dao/JobsConnectionPool.java +++ b/src/main/java/com/gamingmesh/jobs/dao/JobsConnectionPool.java @@ -1,21 +1,3 @@ -/** - * Jobs Plugin for Bukkit - * Copyright (C) 2011 Zak Ford - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - package com.gamingmesh.jobs.dao; import java.sql.Connection; @@ -25,6 +7,7 @@ import java.sql.SQLException; import com.gamingmesh.jobs.Jobs; + public class JobsConnectionPool { private JobsConnection connection; private String url; diff --git a/src/main/java/com/gamingmesh/jobs/dao/JobsDAO.java b/src/main/java/com/gamingmesh/jobs/dao/JobsDAO.java index 3b6788b4..e33f34fc 100644 --- a/src/main/java/com/gamingmesh/jobs/dao/JobsDAO.java +++ b/src/main/java/com/gamingmesh/jobs/dao/JobsDAO.java @@ -1,21 +1,3 @@ -/** - * Jobs Plugin for Bukkit - * Copyright (C) 2011 Zak Ford - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - package com.gamingmesh.jobs.dao; import java.sql.PreparedStatement; @@ -35,7 +17,6 @@ import org.bukkit.OfflinePlayer; import org.bukkit.World; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; -import org.bukkit.util.Vector; import com.gamingmesh.jobs.Jobs; import com.gamingmesh.jobs.container.BlockProtection; @@ -52,27 +33,387 @@ import com.gamingmesh.jobs.container.LogAmounts; import com.gamingmesh.jobs.container.PlayerInfo; import com.gamingmesh.jobs.container.PlayerPoints; import com.gamingmesh.jobs.container.TopList; +import com.gamingmesh.jobs.dao.JobsManager.DataBaseType; import com.gamingmesh.jobs.economy.PaymentData; -import com.gamingmesh.jobs.stuff.Debug; import com.gamingmesh.jobs.stuff.TimeManage; -/** - * Data Access Object interface for the Jobs plugin - * - * Interface that holds all methods that a DAO needs to have - * @author Alex - * - */ public abstract class JobsDAO { private JobsConnectionPool pool; - private String prefix; - private HashMap> map = new HashMap>(); + private static String prefix; private Jobs plugin; - protected JobsDAO(Jobs plugin, String driverName, String url, String username, String password, String prefix) { + private static DataBaseType dbType = DataBaseType.SqLite; + + // Not in use currently + public enum TablesFieldsType { + decimal, number, text, varchar, stringList, stringLongMap, stringIntMap, locationMap, state, location, longNumber; + } + + public enum UserTableFields implements JobsTableInterface { + player_uuid("varchar(36)", TablesFieldsType.varchar), + username("text", TablesFieldsType.text), + seen("bigint", TablesFieldsType.longNumber); + + private String type; + private TablesFieldsType fieldType; + + UserTableFields(String type, TablesFieldsType fieldType) { + this.type = type; + this.fieldType = fieldType; + } + + @Override + public String getCollumn() { + return this.name(); + } + + @Override + public String getType() { + return type; + } + + @Override + public TablesFieldsType getFieldType() { + return fieldType; + } + } + + public enum JobsTableFields implements JobsTableInterface { + userid("int", TablesFieldsType.number), + job("text", TablesFieldsType.text), + experience("int", TablesFieldsType.number), + level("int", TablesFieldsType.number); + + private String type; + private TablesFieldsType fieldType; + + JobsTableFields(String type, TablesFieldsType fieldType) { + this.type = type; + this.fieldType = fieldType; + } + + @Override + public String getCollumn() { + return this.name(); + } + + @Override + public String getType() { + return type; + } + + @Override + public TablesFieldsType getFieldType() { + return fieldType; + } + } + + public enum ArchiveTableFields implements JobsTableInterface { + userid("int", TablesFieldsType.number), + job("text", TablesFieldsType.text), + experience("int", TablesFieldsType.number), + level("int", TablesFieldsType.number); + + private String type; + private TablesFieldsType fieldType; + + ArchiveTableFields(String type, TablesFieldsType fieldType) { + this.type = type; + this.fieldType = fieldType; + } + + @Override + public String getCollumn() { + return this.name(); + } + + @Override + public String getType() { + return type; + } + + @Override + public TablesFieldsType getFieldType() { + return fieldType; + } + } + + public enum BlockTableFields implements JobsTableInterface { + world("varchar(36)", TablesFieldsType.varchar), + x("int", TablesFieldsType.number), + y("int", TablesFieldsType.number), + z("int", TablesFieldsType.number), + recorded("bigint", TablesFieldsType.longNumber), + resets("bigint", TablesFieldsType.longNumber); + + private String type; + private TablesFieldsType fieldType; + + BlockTableFields(String type, TablesFieldsType fieldType) { + this.type = type; + this.fieldType = fieldType; + } + + @Override + public String getCollumn() { + return this.name(); + } + + @Override + public String getType() { + return type; + } + + @Override + public TablesFieldsType getFieldType() { + return fieldType; + } + } + + public enum LimitTableFields implements JobsTableInterface { + userid("int", TablesFieldsType.number), + type("varchar(36)", TablesFieldsType.number), + collected("double", TablesFieldsType.decimal), + started("bigint", TablesFieldsType.longNumber); + + private String ttype; + private TablesFieldsType fieldType; + + LimitTableFields(String type, TablesFieldsType fieldType) { + this.ttype = type; + this.fieldType = fieldType; + } + + @Override + public String getCollumn() { + return this.name(); + } + + @Override + public String getType() { + return ttype; + } + + @Override + public TablesFieldsType getFieldType() { + return fieldType; + } + } + + public enum LogTableFields implements JobsTableInterface { + userid("int", TablesFieldsType.number), + time("bigint", TablesFieldsType.longNumber), + action("varchar(20)", TablesFieldsType.varchar), + itemname("text", TablesFieldsType.text), + count("int", TablesFieldsType.number), + money("double", TablesFieldsType.decimal), + exp("double", TablesFieldsType.decimal); + + private String type; + private TablesFieldsType fieldType; + + LogTableFields(String type, TablesFieldsType fieldType) { + this.type = type; + this.fieldType = fieldType; + } + + @Override + public String getCollumn() { + return this.name(); + } + + @Override + public String getType() { + return type; + } + + @Override + public TablesFieldsType getFieldType() { + return fieldType; + } + } + + public enum PointsTableFields implements JobsTableInterface { + userid("int", TablesFieldsType.number), + totalpoints("double", TablesFieldsType.decimal), + currentpoints("double", TablesFieldsType.decimal); + + private String type; + private TablesFieldsType fieldType; + + PointsTableFields(String type, TablesFieldsType fieldType) { + this.type = type; + this.fieldType = fieldType; + } + + @Override + public String getCollumn() { + return this.name(); + } + + @Override + public String getType() { + return type; + } + + @Override + public TablesFieldsType getFieldType() { + return fieldType; + } + } + + public enum ExploreTableFields implements JobsTableInterface { + worldname("varchar(64)", TablesFieldsType.varchar), + chunkX("int", TablesFieldsType.number), + chunkZ("int", TablesFieldsType.number), + playerName("text", TablesFieldsType.text); + + private String type; + private TablesFieldsType fieldType; + + ExploreTableFields(String type, TablesFieldsType fieldType) { + this.type = type; + this.fieldType = fieldType; + } + + @Override + public String getCollumn() { + return this.name(); + } + + @Override + public String getType() { + return type; + } + + @Override + public TablesFieldsType getFieldType() { + return fieldType; + } + } + + public enum DBTables { + UsersTable("users", + "CREATE TABLE `[tableName]` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY[fields]);", + "CREATE TABLE `[tableName]` (`id` INTEGER PRIMARY KEY AUTOINCREMENT[fields]);", UserTableFields.class), + JobsTable("jobs", + "CREATE TABLE `[tableName]` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY[fields]);", + "CREATE TABLE `[tableName]` (`id` INTEGER PRIMARY KEY AUTOINCREMENT[fields]);", JobsTableFields.class), + ArchiveTable("archive", + "CREATE TABLE `[tableName]` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY[fields]);", + "CREATE TABLE `[tableName]` (`id` INTEGER PRIMARY KEY AUTOINCREMENT[fields]);", ArchiveTableFields.class), + BlocksTable("blocks", + "CREATE TABLE `[tableName]` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY[fields]);", + "CREATE TABLE `[tableName]` (`id` INTEGER PRIMARY KEY AUTOINCREMENT[fields]);", BlockTableFields.class), + LimitsTable("limits", + "CREATE TABLE `[tableName]` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY[fields]);", + "CREATE TABLE `[tableName]` (`id` INTEGER PRIMARY KEY AUTOINCREMENT[fields]);", LimitTableFields.class), + LogTable("log", + "CREATE TABLE `[tableName]` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY[fields]);", + "CREATE TABLE `[tableName]` (`id` INTEGER PRIMARY KEY AUTOINCREMENT[fields]);", LogTableFields.class), + ExploreTable("explore", + "CREATE TABLE `[tableName]` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY[fields]);", + "CREATE TABLE `[tableName]` (`id` INTEGER PRIMARY KEY AUTOINCREMENT[fields]);", ExploreTableFields.class), + PointsTable("points", + "CREATE TABLE `[tableName]` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY[fields]);", + "CREATE TABLE `[tableName]` (`id` INTEGER PRIMARY KEY AUTOINCREMENT[fields]);", PointsTableFields.class); + + private String mySQL; + private String sQlite; + private String tableName; + private JobsTableInterface[] c; + + DBTables(String tableName, String MySQL, String SQlite, Class cc) { + this.tableName = tableName; + this.mySQL = MySQL; + this.sQlite = SQlite; + this.c = (JobsTableInterface[]) cc.getEnumConstants(); + } + + private String getQR() { + switch (dbType) { + case MySQL: + return this.mySQL.replace("[tableName]", prefix + this.tableName); + case SqLite: + return this.sQlite.replace("[tableName]", this.tableName); + } + return ""; + } + + public String getQuery() { + String rp = ""; + for (JobsTableInterface one : this.getInterface()) { + rp += ", " + "`" + one.getCollumn() + "` " + one.getType(); + } + return getQR().replace("[fields]", rp); + } + + public JobsTableInterface[] getInterface() { + return this.c; + } + +// public String getUpdateQuery() { +// +// String rp = ""; +// for (JobsTableInterface one : this.getInterface()) { +// if (one.getCollumn().equalsIgnoreCase("userid") || one.getCollumn().equalsIgnoreCase("player_uuid")) +// continue; +// if (!rp.isEmpty()) +// rp += ", "; +// +// } +// +// switch (this) { +// case JobsTable: +// for (JobsTableInterface one : this.getInterface()) { +// if (one == JobsTableFields.userid) +// continue; +// if (!rp.isEmpty()) +// rp += ", "; +// rp += "`" + one.getCollumn() + "` = ?"; +// } +// rp = "UPDATE `" + getTableName() + "` SET " + rp + " WHERE `player_id` = ?;"; +// return rp; +// default: +// rp = ""; +// for (JobsTableInterface one : this.getInterface()) { +// if (one.getCollumn().equalsIgnoreCase("userid") || one.getCollumn().equalsIgnoreCase("player_uuid")) +// continue; +// if (!rp.isEmpty()) +// rp += ", "; +// rp += "`" + one.getCollumn() + "` = ?"; +// } +// rp = "UPDATE `" + getTableName() + "` SET " + rp + " WHERE `id` = ?;"; +// return rp; +// } +// } +// +// public String getInsertQuery() { +// String rp = ""; +// String q = ""; +// +// for (JobsTableInterface one : this.getInterface()) { +// if (!rp.isEmpty()) +// rp += ", "; +// rp += "`" + one.getCollumn() + "`"; +// +// if (!q.isEmpty()) +// q += ", "; +// q += "?"; +// } +// rp = "INSERT INTO `" + getTableName() + "` (" + rp + ") VALUES (" + q + ");"; +// return rp; +// } + + public String getTableName() { + return prefix + tableName; + } + } + + protected JobsDAO(Jobs plugin, String driverName, String url, String username, String password, String pr) { this.plugin = plugin; - this.prefix = prefix; + prefix = pr; try { pool = new JobsConnectionPool(driverName, url, username, password); } catch (Exception e) { @@ -84,66 +425,101 @@ public abstract class JobsDAO { setupConfig(); int version = getSchemaVersion(); if (version == 0) { - Jobs.getPluginLogger().severe("Could not initialize database! Could not determine schema version!"); + Jobs.consoleMsg("&cCould not initialize database! Could not determine schema version!"); return; } try { - checkUpdate(); - if (version > 1) { - if (version <= 2) - checkUpdate2(); - checkUpdate4(); - checkUpdate5(); - if (version <= 6) - checkUpdate6(); - if (version <= 7) - checkUpdate7(); - // creating explore database - checkUpdate8(); - checkUpdate9(); - // creating block protection database - checkUpdate10(); - // adding seen field into users table - checkUpdate11(); - } - version = 11; updateSchemaVersion(version); + for (DBTables one : DBTables.values()) { + createDefaultTable(one); + } + checkDefaultCollumns(); } finally { } - - loadAllSavedJobs(); - } protected abstract void setupConfig() throws SQLException; protected abstract void checkUpdate() throws SQLException; - protected abstract void checkUpdate2() throws SQLException; + public abstract Statement prepareStatement(String query) throws SQLException; - protected abstract void checkUpdate4() throws SQLException; + public abstract boolean createTable(String query) throws SQLException; - protected abstract void checkUpdate5() throws SQLException; + public abstract boolean isTable(String table); - protected abstract void checkUpdate6() throws SQLException; + public abstract boolean isCollumn(String table, String collumn); - protected abstract void checkUpdate7() throws SQLException; + public abstract boolean truncate(String table); - protected abstract void checkUpdate8() throws SQLException; + public abstract boolean addCollumn(String table, String collumn, String type); - protected abstract void checkUpdate9() throws SQLException; + public abstract boolean drop(String table); - protected abstract void checkUpdate10() throws SQLException; + public boolean isConnected() { + try { + return pool.getConnection() != null; + } catch (SQLException e) { + return false; + } + } - protected abstract void checkUpdate11() throws SQLException; + public void setAutoCommit(boolean state) { + JobsConnection conn = getConnection(); + if (conn == null) + return; + try { + conn.setAutoCommit(state); + } catch (SQLException e) { + e.printStackTrace(); + } + } - protected abstract boolean createDefaultLogBase(); + public void commit() { + JobsConnection conn = getConnection(); + if (conn == null) + return; - protected abstract boolean createDefaultArchiveBase(); + try { + conn.commit(); + } catch (SQLException e) { + e.printStackTrace(); + } + } - protected abstract boolean dropDataBase(String name); + private boolean createDefaultTable(DBTables table) { + if (this.isTable(table.getTableName())) + return true; + try { + this.createTable(table.getQuery()); + return true; + } catch (SQLException e) { + e.printStackTrace(); + } + return false; + } + + private boolean checkDefaultCollumns() { + for (DBTables one : DBTables.values()) { + for (JobsTableInterface oneT : one.getInterface()) { + if (this.isCollumn(one.getTableName(), oneT.getCollumn())) + continue; + this.addCollumn(one.getTableName(), oneT.getCollumn(), oneT.getType()); + } + } + + return true; + } + + public DataBaseType getDbType() { + return dbType; + } + + public void setDbType(DataBaseType dabType) { + dbType = dabType; + } /** * Gets the database prefix @@ -203,6 +579,8 @@ public abstract class JobsDAO { return jobs; } + private HashMap> map = new HashMap>(); + public List getAllJobs(PlayerInfo pInfo) { List list = map.get(pInfo.getID()); if (list != null) @@ -302,7 +680,7 @@ public abstract class JobsDAO { PreparedStatement prest = null; ResultSet res = null; try { - prest = conn.prepareStatement("SELECT `id` FROM `" + this.prefix + "users` WHERE `player_uuid` = ?;"); + prest = conn.prepareStatement("SELECT `id` FROM `" + prefix + "users` WHERE `player_uuid` = ?;"); prest.setString(1, uuid.toString()); res = prest.executeQuery(); res.next(); @@ -1065,8 +1443,8 @@ public abstract class JobsDAO { e.printStackTrace(); close(prest1); close(prest2); - this.dropDataBase("log"); - this.createDefaultLogBase(); + drop(DBTables.LogTable.getTableName()); + createDefaultTable(DBTables.LogTable); } finally { close(prest1); close(prest2); @@ -1095,8 +1473,8 @@ public abstract class JobsDAO { } catch (Exception e) { close(res); close(prest); - this.dropDataBase("log"); - this.createDefaultLogBase(); + drop(DBTables.LogTable.getTableName()); + createDefaultTable(DBTables.LogTable); } finally { close(res); close(prest); @@ -1551,7 +1929,7 @@ public abstract class JobsDAO { /** * Get a database connection - * @return JobsConnection object + * @return DBConnection object * @throws SQLException */ protected JobsConnection getConnection() { @@ -1570,7 +1948,7 @@ public abstract class JobsDAO { pool.closeConnection(); } - private static void close(ResultSet res) { + protected static void close(ResultSet res) { if (res != null) try { res.close(); @@ -1591,4 +1969,5 @@ public abstract class JobsDAO { public HashMap> getMap() { return map; } + } diff --git a/src/main/java/com/gamingmesh/jobs/dao/JobsDAOMySQL.java b/src/main/java/com/gamingmesh/jobs/dao/JobsDAOMySQL.java deleted file mode 100644 index 6b57a0f6..00000000 --- a/src/main/java/com/gamingmesh/jobs/dao/JobsDAOMySQL.java +++ /dev/null @@ -1,878 +0,0 @@ -/** - * Jobs Plugin for Bukkit - * Copyright (C) 2011 Zak Ford - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.gamingmesh.jobs.dao; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.HashMap; -import java.util.UUID; -import java.util.Map.Entry; - -import org.bukkit.Bukkit; -import com.gamingmesh.jobs.Jobs; -import com.gamingmesh.jobs.container.PlayerInfo; -import com.gamingmesh.jobs.stuff.UUIDUtil; - -public class JobsDAOMySQL extends JobsDAO { - private String database; - - private JobsDAOMySQL(Jobs plugin, String hostname, String database, String username, String password, String prefix) { - super(plugin, "com.mysql.jdbc.Driver", "jdbc:mysql://" + hostname + "/" + database + "?autoReconnect=true&useSSL=false", username, password, prefix); - this.database = database; - } - - public static JobsDAOMySQL initialize(Jobs plugin, String hostname, String database, String username, String password, String prefix) { - JobsDAOMySQL dao = new JobsDAOMySQL(plugin, hostname, database, username, password, prefix); - try { - dao.setUp(); - } catch (SQLException e) { - e.printStackTrace(); - } - return dao; - } - - private static void close(ResultSet res) { - if (res != null) { - try { - res.close(); - } catch (SQLException e) { - } - } - } - - private static void close(PreparedStatement prest) { - if (prest != null) { - try { - prest.close(); - } catch (SQLException e) { - } - } - } - - @Override - protected synchronized void setupConfig() throws SQLException { - JobsConnection conn = getConnection(); - if (conn == null) { - Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); - return; - } - - if (!isTable(getPrefix() + "config")) { - PreparedStatement insert = null; - try { - executeSQL("CREATE TABLE `" + getPrefix() + "config` (`key` varchar(50) NOT NULL PRIMARY KEY, `value` varchar(100) NOT NULL);"); - insert = conn.prepareStatement("INSERT INTO `" + getPrefix() + "config` (`key`, `value`) VALUES (?, ?);"); - insert.setString(1, "version"); - insert.setString(2, "1"); - insert.execute(); - } finally { - close(insert); - } - } - } - - @SuppressWarnings("resource") - private boolean isTable(String table) { - Statement statement; - try { - statement = getConnection().createStatement(); - } catch (SQLException e) { - Jobs.consoleMsg("&cCould not check if its table, SQLException: " + e.getMessage()); - return false; - } - try { - statement.executeQuery("SELECT * FROM " + table); - statement.close(); - return true; - } catch (SQLException e) { - close(statement); - return false; - } - } - - public boolean isCollumn(String table, String collumn) { - Statement statement; - try { - statement = getConnection().createStatement(); - } catch (SQLException e) { - Jobs.consoleMsg("&cCould not check if its collumn, SQLException: " + e.getMessage()); - return false; - } - try { - statement.executeQuery("SELECT " + collumn + " FROM " + table); - statement.close(); - return true; - } catch (SQLException e) { - close(statement); - return false; - } - } - - @SuppressWarnings("resource") - public boolean createTable(String query) { - Jobs.consoleMsg(query); - Statement statement = null; - if (query == null || query.equals("")) { - Jobs.consoleMsg("&cCould not create table: query is empty or null."); - return false; - } - - try { - statement = getConnection().createStatement(); - statement.execute(query); - statement.close(); - } catch (SQLException e) { - Jobs.consoleMsg("&cCould not create table, SQLException: " + e.getMessage()); - close(statement); - return false; - } finally { - close(statement); - } - return true; - } - - @Override - protected synchronized void checkUpdate() throws SQLException { - JobsConnection conn = getConnection(); - if (conn == null) { - Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); - return; - } - createDefaultJobsBase(); - createDefaultLogBase(); - createDefaultArchiveBase(); - createDefaultPointsBase(); - createDefaultExploreBase(); - createDefaultUsersBase(); - createDefaultBlockProtection(); - createDefaultLimitBase(); - } - - @Override - protected synchronized void checkUpdate2() throws SQLException { - JobsConnection conn = getConnection(); - if (conn == null) { - Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); - return; - } - PreparedStatement prest = null; - ResultSet res = null; - int rows = 0; - try { - // Check for jobs table - prest = conn.prepareStatement("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = ? AND table_name = ? AND column_name = ?;"); - prest.setString(1, database); - prest.setString(2, getPrefix() + "jobs"); - prest.setString(3, "username"); - res = prest.executeQuery(); - if (res.next()) { - rows = res.getInt(1); - } - } finally { - close(res); - close(prest); - } - - try { - if (rows == 0) - executeSQL("ALTER TABLE `" + getPrefix() + "jobs` ADD COLUMN `username` varchar(20);"); - } finally { - } - } - - @Override - protected synchronized void checkUpdate4() throws SQLException { - JobsConnection conn = getConnection(); - if (conn == null) { - Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); - return; - } - PreparedStatement prest = null; - ResultSet res = null; - int rows = 0; - try { - // Check for jobs table - prest = conn.prepareStatement("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = ? AND table_name = ?;"); - prest.setString(1, database); - prest.setString(2, getPrefix() + "archive"); - res = prest.executeQuery(); - if (res.next()) { - rows = res.getInt(1); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - close(res); - close(prest); - } - - try { - if (rows == 0) - executeSQL("CREATE TABLE `" + getPrefix() - + "archive` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `player_uuid` binary(16) NOT NULL, `username` varchar(20), `job` varchar(20), `experience` int, `level` int);"); - } catch (Exception e) { - e.printStackTrace(); - } finally { - } - } - - @Override - protected synchronized void checkUpdate5() throws SQLException { - JobsConnection conn = getConnection(); - if (conn == null) { - Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); - return; - } - PreparedStatement prest = null; - ResultSet res = null; - int rows = 0; - try { - // Check for jobs table - prest = conn.prepareStatement("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = ? AND table_name = ?;"); - prest.setString(1, database); - prest.setString(2, getPrefix() + "log"); - res = prest.executeQuery(); - if (res.next()) { - rows = res.getInt(1); - } - } finally { - close(res); - close(prest); - } - - try { - if (rows == 0) - executeSQL("CREATE TABLE `" + getPrefix() - + "log` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `player_uuid` binary(16) NOT NULL, `username` varchar(20), `time` bigint, `action` varchar(20), `itemname` varchar(60), `count` int, `money` double, `exp` double);"); - } finally { - } - } - - @Override - protected synchronized void checkUpdate6() throws SQLException { - JobsConnection conn = getConnection(); - if (conn == null) { - Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); - return; - } - try { - executeSQL("ALTER TABLE `" + getPrefix() + "log` MODIFY `itemname` VARCHAR(60);"); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Override - protected synchronized void checkUpdate7() throws SQLException { - JobsConnection conn = getConnection(); - if (conn == null) { - Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); - return; - } - - boolean convertJobs = true; - PreparedStatement tempPst = conn.prepareStatement("SELECT * FROM `" + getPrefix() + "jobs`;"); - ResultSet tempRes = tempPst.executeQuery(); - - boolean noJobsdata = true; - try { - while (tempRes.next()) { - noJobsdata = false; - tempRes.getByte("player_uuid"); - break; - } - } catch (Exception e) { - convertJobs = false; - } finally { - tempRes.close(); - tempPst.close(); - } - if (noJobsdata) { - dropDataBase("jobs"); - createDefaultJobsBase(); - convertJobs = false; - } - - if (convertJobs) { - Jobs.getPluginLogger().info("Converting byte uuids to string. This could take a long time!!!"); - // Converting jobs players byte uuid into string - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "jobs_temp` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `player_uuid` varchar(36) NOT NULL,`username` varchar(20), `job` varchar(20), `experience` int, `level` int);"); - } catch (Exception e) { - } - - PreparedStatement pst1 = conn.prepareStatement("SELECT * FROM `" + getPrefix() + "jobs`;"); - ResultSet rs = pst1.executeQuery(); - PreparedStatement insert = null; - - conn.setAutoCommit(false); - - while (rs.next()) { - - byte[] uuidBytes = rs.getBytes("player_uuid"); - - if (uuidBytes == null) - continue; - - String uuid = UUIDUtil.fromBytes(uuidBytes).toString(); - - if (uuid != null) { - insert = conn.prepareStatement("INSERT INTO `" + getPrefix() - + "jobs_temp` (`player_uuid`, `username`, `job`, `experience`, `level`) VALUES (?, ?, ?, ?, ?);"); - insert.setString(1, uuid); - insert.setString(2, rs.getString("username")); - insert.setString(3, rs.getString("job")); - insert.setInt(4, rs.getInt("experience")); - insert.setInt(5, rs.getInt("level")); - insert.addBatch(); - } - } - - if (insert != null) - insert.executeBatch(); - - conn.commit(); - conn.setAutoCommit(true); - - if (insert != null) - insert.close(); - rs.close(); - pst1.close(); - - executeSQL("DROP TABLE IF EXISTS `" + getPrefix() + "jobs`;"); - executeSQL("ALTER TABLE `" + getPrefix() + "jobs_temp` RENAME TO `" + getPrefix() + "jobs`;"); - } - - boolean convertArchive = true; - PreparedStatement tempArchivePst = conn.prepareStatement("SELECT * FROM `" + getPrefix() + "archive`;"); - ResultSet tempArchiveRes = tempArchivePst.executeQuery(); - - boolean noArchivedata = true; - try { - while (tempArchiveRes.next()) { - noArchivedata = false; - tempArchiveRes.getByte("player_uuid"); - break; - } - } catch (Exception e) { - convertArchive = false; - } finally { - tempArchiveRes.close(); - tempArchivePst.close(); - } - if (noArchivedata) { - dropDataBase("archive"); - createDefaultArchiveBase(); - convertArchive = false; - } - - if (convertArchive) { - // Converting archive players byte uuid into string - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "archive_temp` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `player_uuid` varchar(36) NOT NULL, `username` varchar(20), `job` varchar(20), `experience` int, `level` int);"); - } catch (Exception e) { - } - - PreparedStatement pst11 = conn.prepareStatement("SELECT * FROM `" + getPrefix() + "archive`;"); - ResultSet rs1 = pst11.executeQuery(); - PreparedStatement insert1 = null; - - conn.setAutoCommit(false); - - while (rs1.next()) { - String uuid = UUIDUtil.fromBytes(rs1.getBytes("player_uuid")).toString(); - if (uuid != null) { - insert1 = conn.prepareStatement("INSERT INTO `" + getPrefix() - + "archive_temp` (`player_uuid`, `username`, `job`, `experience`, `level`) VALUES (?, ?, ?, ?, ?);"); - insert1.setString(1, uuid); - insert1.setString(2, rs1.getString("username")); - insert1.setString(3, rs1.getString("job")); - insert1.setInt(4, rs1.getInt("experience")); - insert1.setInt(5, rs1.getInt("level")); - insert1.addBatch(); - } - } - if (insert1 != null) - insert1.executeBatch(); - conn.commit(); - conn.setAutoCommit(true); - - rs1.close(); - pst11.close(); - if (insert1 != null) - insert1.close(); - - executeSQL("DROP TABLE IF EXISTS `" + getPrefix() + "archive`;"); - try { - executeSQL("ALTER TABLE `" + getPrefix() + "archive_temp` RENAME TO `" + getPrefix() + "archive`;"); - } catch (Exception e) { - } - } - - boolean convertLog = true; - PreparedStatement tempLogPst = conn.prepareStatement("SELECT * FROM `" + getPrefix() + "log`;"); - ResultSet tempLogRes = tempLogPst.executeQuery(); - - boolean nodata = true; - try { - while (tempLogRes.next()) { - nodata = false; - tempLogRes.getByte("player_uuid"); - break; - } - } catch (Exception e) { - convertLog = false; - } finally { - tempLogRes.close(); - tempLogPst.close(); - } - if (nodata) { - dropDataBase("log"); - createDefaultLogBase(); - convertLog = false; - } - - if (convertLog) { - Bukkit.getConsoleSender().sendMessage("Converting log database"); - // Converting log players byte uuid into string - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "log_temp` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `player_uuid` varchar(36) NOT NULL, `username` varchar(20), `time` bigint, `action` varchar(20), `itemname` varchar(60), `count` int, `money` double, `exp` double);"); - } catch (Exception e) { - } - - PreparedStatement pst111 = conn.prepareStatement("SELECT * FROM `" + getPrefix() + "log`;"); - ResultSet rs11 = pst111.executeQuery(); - PreparedStatement insert11 = null; - - conn.setAutoCommit(false); - - while (rs11.next()) { - String uuid = UUIDUtil.fromBytes(rs11.getBytes("player_uuid")).toString(); - if (uuid != null) { - insert11 = conn.prepareStatement("INSERT INTO `" + getPrefix() - + "log_temp` (`player_uuid`, `username`, `time`, `action`, `itemname`, `count`, `money`, `exp`) VALUES (?, ?, ?, ?, ?, ?, ?, ?);"); - insert11.setString(1, uuid); - insert11.setString(2, rs11.getString("username")); - insert11.setLong(3, rs11.getLong("time")); - insert11.setString(4, rs11.getString("action")); - insert11.setString(5, rs11.getString("itemname")); - insert11.setInt(6, rs11.getInt("count")); - insert11.setDouble(7, rs11.getDouble("money")); - insert11.setDouble(8, rs11.getDouble("exp")); - insert11.addBatch(); - } - } - if (insert11 != null) - insert11.executeBatch(); - conn.commit(); - conn.setAutoCommit(true); - - pst111.close(); - rs11.close(); - if (insert11 != null) - insert11.close(); - - executeSQL("DROP TABLE IF EXISTS `" + getPrefix() + "log`;"); - try { - executeSQL("ALTER TABLE `" + getPrefix() + "log_temp` RENAME TO `" + getPrefix() + "log`;"); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - @Override - protected synchronized void checkUpdate8() throws SQLException { - JobsConnection conn = getConnection(); - if (conn == null) { - Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); - return; - } - PreparedStatement prest = null; - ResultSet res = null; - int rows = 0; - try { - // Check for jobs table - prest = conn.prepareStatement("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = ? AND table_name = ?;"); - prest.setString(1, database); - prest.setString(2, getPrefix() + "explore"); - res = prest.executeQuery(); - if (res.next()) { - rows = res.getInt(1); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - close(res); - close(prest); - } - - try { - if (rows == 0) - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "explore` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `worldname` varchar(64), `chunkX` int, `chunkZ` int, `playerName` varchar(32));"); - } catch (SQLException e) { - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - } - } - - @Override - protected synchronized void checkUpdate9() throws SQLException { - JobsConnection conn = getConnection(); - if (conn == null) { - Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); - return; - } - - PreparedStatement tempPrest = null; - ResultSet res = null; - int rows = 0; - try { - // Check for jobs table - tempPrest = conn.prepareStatement("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = ? AND table_name = ?;"); - tempPrest.setString(1, database); - tempPrest.setString(2, getPrefix() + "users"); - res = tempPrest.executeQuery(); - if (res.next()) { - rows = res.getInt(1); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - close(res); - close(tempPrest); - } - // Create new points table - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "points` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `userid` int, `totalpoints` double, `currentpoints` double);"); - } catch (SQLException e) { - } - - // dropping 2 columns - PreparedStatement prestLogTemp = null; - ResultSet rsLogTemp = null; - boolean next = false; - try { - prestLogTemp = conn.prepareStatement("SELECT * FROM `" + getPrefix() + "log`;"); - rsLogTemp = prestLogTemp.executeQuery(); - while (rsLogTemp.next()) { - next = true; - rsLogTemp.getInt("userid"); - rsLogTemp.getLong("time"); - rsLogTemp.getString("action"); - rsLogTemp.getString("itemname"); - rsLogTemp.getInt("count"); - rsLogTemp.getDouble("money"); - rsLogTemp.getDouble("exp"); - break; - } - } catch (Exception ex) { - } finally { - close(rsLogTemp); - close(prestLogTemp); - } - - if (!next) { - dropDataBase("log"); - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "log` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `userid` int, `username` varchar(20), `time` bigint, `action` varchar(20), `itemname` varchar(60), `count` int, `money` double, `exp` double);"); - } catch (Exception e) { - } - } - - if (rows == 0) { - HashMap tempMap = new HashMap(); - PreparedStatement prestJobs = null; - ResultSet res1 = null; - try { - prestJobs = conn.prepareStatement("SELECT DISTINCT(player_uuid),username FROM " + getPrefix() + "jobs;"); - res1 = prestJobs.executeQuery(); - while (res1.next()) { - tempMap.put(res1.getString("player_uuid"), res1.getString("username")); - } - } catch (Exception e) { - } finally { - close(res1); - close(prestJobs); - } - - PreparedStatement prestArchive = null; - ResultSet res2 = null; - try { - prestArchive = conn.prepareStatement("SELECT DISTINCT(player_uuid),username FROM " + getPrefix() + "archive;"); - res2 = prestArchive.executeQuery(); - while (res2.next()) { - tempMap.put(res2.getString("player_uuid"), res2.getString("username")); - } - } catch (Exception e) { - } finally { - close(res2); - close(prestArchive); - } - - PreparedStatement prestLog = null; - ResultSet res3 = null; - try { - prestLog = conn.prepareStatement("SELECT DISTINCT(player_uuid),username FROM " + getPrefix() + "log;"); - res3 = prestLog.executeQuery(); - while (res3.next()) { - tempMap.put(res3.getString("player_uuid"), res3.getString("username")); - } - } catch (Exception e) { - } finally { - close(res3); - close(prestLog); - } - - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "users` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `player_uuid` varchar(36) NOT NULL, `username` varchar(20));"); - } catch (Exception e) { - e.printStackTrace(); - } - - PreparedStatement prestUsers = null; - try { - prestUsers = conn.prepareStatement("INSERT INTO `" + getPrefix() + "users` (`player_uuid`, `username`) VALUES (?, ?);"); - conn.setAutoCommit(false); - for (Entry users : tempMap.entrySet()) { - prestUsers.setString(1, users.getKey()); - prestUsers.setString(2, users.getValue()); - prestUsers.addBatch(); - } - prestUsers.executeBatch(); - conn.commit(); - conn.setAutoCommit(true); - } catch (Exception e) { - e.printStackTrace(); - } finally { - close(prestUsers); - } - - HashMap tempPlayerMap = new HashMap(); - - PreparedStatement prestUsersT = null; - ResultSet res4 = null; - try { - prestUsersT = conn.prepareStatement("SELECT * FROM " + getPrefix() + "users;"); - res4 = prestUsersT.executeQuery(); - while (res4.next()) { - tempPlayerMap.put(res4.getString("player_uuid"), new PlayerInfo(res4.getString("username"), res4.getInt("id"), UUID.fromString(res4.getString("player_uuid")), System - .currentTimeMillis())); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - close(res4); - close(prestUsersT); - } - - // Modifying jobs main table - try { - executeSQL("ALTER TABLE `" + getPrefix() + "jobs` ADD COLUMN `userid` int;"); - } catch (Exception e) { - } - PreparedStatement prestJobsT = null; - try { - prestJobsT = conn.prepareStatement("UPDATE `" + getPrefix() + "jobs` SET `userid` = ? WHERE `player_uuid` = ?;"); - conn.setAutoCommit(false); - for (Entry users : tempPlayerMap.entrySet()) { - prestJobsT.setInt(1, users.getValue().getID()); - prestJobsT.setString(2, users.getKey()); - prestJobsT.addBatch(); - } - prestJobsT.executeBatch(); - conn.commit(); - conn.setAutoCommit(true); - } catch (Exception e) { - e.printStackTrace(); - } finally { - close(prestJobsT); - } - - try { - executeSQL("ALTER TABLE `" + getPrefix() + "jobs` DROP COLUMN `player_uuid`, DROP COLUMN `username`;"); - } catch (Exception e) { - } - // Modifying jobs archive table - try { - executeSQL("ALTER TABLE `" + getPrefix() + "archive` ADD COLUMN `userid` int;"); - } catch (Exception e) { - } - - PreparedStatement prestArchiveT = null; - try { - prestArchiveT = conn.prepareStatement("UPDATE `" + getPrefix() + "archive` SET `userid` = ? WHERE `player_uuid` = ?;"); - conn.setAutoCommit(false); - for (Entry users : tempPlayerMap.entrySet()) { - prestArchiveT.setInt(1, users.getValue().getID()); - prestArchiveT.setString(2, users.getKey()); - prestArchiveT.addBatch(); - } - prestArchiveT.executeBatch(); - conn.commit(); - conn.setAutoCommit(true); - } catch (Exception e) { - e.printStackTrace(); - } finally { - close(prestArchiveT); - } - - try { - executeSQL("ALTER TABLE `" + getPrefix() + "archive` DROP COLUMN `player_uuid`, DROP COLUMN `username`;"); - } catch (Exception e) { - } - } - } - - @Override - protected synchronized void checkUpdate10() { - createDefaultBlockProtection(); - } - - @Override - protected synchronized void checkUpdate11() { - JobsConnection conn = getConnection(); - if (conn == null) { - Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); - return; - } - - try { - executeSQL("ALTER TABLE `" + getPrefix() + "users` ADD COLUMN `seen` bigint;"); - } catch (Exception e) { - return; - } finally { - } - - PreparedStatement prest = null; - try { - prest = conn.prepareStatement("UPDATE `" + getPrefix() + "users` SET `seen` = ?;"); - prest.setLong(1, System.currentTimeMillis()); - prest.execute(); - } catch (SQLException e) { - e.printStackTrace(); - } finally { - close(prest); - } - } - - private boolean createDefaultExploreBase() { - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "explore` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `worldname` varchar(64), `chunkX` int, `chunkZ` int, `playerName` varchar(32));"); - } catch (SQLException e) { - return false; - } - return true; - } - - private boolean createDefaultPointsBase() { - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "points` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `userid` int, `totalpoints` double, `currentpoints` double);"); - } catch (SQLException e) { - return false; - } - return true; - } - - @Override - protected boolean createDefaultLogBase() { - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "log` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `userid` int, `time` bigint, `action` varchar(20), `itemname` varchar(60), `count` int, `money` double, `exp` double);"); - } catch (SQLException e) { - return false; - } - return true; - } - - @Override - protected boolean createDefaultArchiveBase() { - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "archive` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `userid` int, `job` varchar(20), `experience` int, `level` int);"); - } catch (SQLException e) { - return false; - } - return true; - } - - private boolean createDefaultJobsBase() { - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "jobs` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `userid` int, `job` varchar(20), `experience` int, `level` int);"); - } catch (SQLException e) { - return false; - } - return true; - } - - private boolean createDefaultUsersBase() { - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "users` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `player_uuid` varchar(36) NOT NULL, `username` varchar(20), `seen` bigint);"); - } catch (SQLException e) { - return false; - } - return true; - } - - private boolean createDefaultBlockProtection() { - try { - executeSQL("CREATE TABLE IF NOT EXISTS `" + getPrefix() - + "blocks` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `world` varchar(36) NOT NULL, `x` int, `y` int, `z` int, `recorded` bigint, `resets` bigint);"); - } catch (SQLException e) { - return false; - } - return true; - } - - private boolean createDefaultLimitBase() { - try { - executeSQL("CREATE TABLE IF NOT EXISTS `" + getPrefix() - + "limits` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `userid` int, `type` varchar(36), `collected` double, `started` bigint);"); - } catch (SQLException e) { - return false; - } - return true; - } - - @Override - protected boolean dropDataBase(String name) { - try { - executeSQL("DROP TABLE IF EXISTS `" + getPrefix() + name + "`;"); - } catch (SQLException e) { - return false; - } - return true; - } -} diff --git a/src/main/java/com/gamingmesh/jobs/dao/JobsDAOSQLite.java b/src/main/java/com/gamingmesh/jobs/dao/JobsDAOSQLite.java deleted file mode 100644 index a743fcb2..00000000 --- a/src/main/java/com/gamingmesh/jobs/dao/JobsDAOSQLite.java +++ /dev/null @@ -1,893 +0,0 @@ -/** - * Jobs Plugin for Bukkit - * Copyright (C) 2011 Zak Ford - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.gamingmesh.jobs.dao; - -import java.io.File; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.HashMap; -import java.util.UUID; -import java.util.Map.Entry; -import com.gamingmesh.jobs.Jobs; -import com.gamingmesh.jobs.container.PlayerInfo; -import com.gamingmesh.jobs.stuff.UUIDUtil; - -public class JobsDAOSQLite extends JobsDAO { - public static JobsDAOSQLite initialize(Jobs plugin) { - JobsDAOSQLite dao = new JobsDAOSQLite(plugin); - File dir = Jobs.getFolder(); - if (!dir.exists()) - dir.mkdirs(); - try { - dao.setUp(); - } catch (SQLException e) { - e.printStackTrace(); - } - return dao; - } - - private JobsDAOSQLite(Jobs plugin) { - super(plugin, "org.sqlite.JDBC", "jdbc:sqlite:" + new File(Jobs.getFolder(), "jobs.sqlite.db").getPath(), null, null, ""); - } - - private static void close(ResultSet res) { - if (res != null) { - try { - res.close(); - } catch (SQLException e) { - } - } - } - - private static void close(PreparedStatement prest) { - if (prest != null) { - try { - prest.close(); - } catch (SQLException e) { - } - } - } - - @Override - protected synchronized void setupConfig() throws SQLException { - JobsConnection conn = getConnection(); - if (conn == null) { - Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); - return; - } - - PreparedStatement prest = null; - ResultSet res = null; - int rows = 0; - try { - // Check for config table - prest = conn.prepareStatement("SELECT COUNT(*) FROM sqlite_master WHERE name = ?;"); - prest.setString(1, getPrefix() + "config"); - res = prest.executeQuery(); - if (res.next()) { - rows = res.getInt(1); - } - } finally { - close(res); - close(prest); - } - - if (rows == 0) { - PreparedStatement insert = null; - try { - executeSQL("CREATE TABLE `" + getPrefix() + "config` (`key` varchar(50) NOT NULL PRIMARY KEY, `value` varchar(100) NOT NULL);"); - - insert = conn.prepareStatement("INSERT INTO `" + getPrefix() + "config` (`key`, `value`) VALUES (?, ?);"); - insert.setString(1, "version"); - insert.setString(2, "1"); - insert.execute(); - } finally { - close(insert); - } - } - } - - @Override - protected synchronized void checkUpdate() throws SQLException { - JobsConnection conn = getConnection(); - if (conn == null) { - Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); - return; - } - createDefaultJobsBase(); - createDefaultLogBase(); - createDefaultArchiveBase(); - createDefaultPointsBase(); - createDefaultExploreBase(); - createDefaultUsersBase(); - createDefaultBlockProtection(); - createDefaultLimitBase(); - } - - @Override - protected synchronized void checkUpdate2() throws SQLException { - JobsConnection conn = getConnection(); - if (conn == null) { - Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); - return; - } - PreparedStatement prest = null; - ResultSet res = null; - int rows = 0; - try { - // Check for jobs table - prest = conn.prepareStatement("SELECT COUNT(*) FROM sqlite_master WHERE name = ?;"); - prest.setString(1, getPrefix() + "jobs"); - res = prest.executeQuery(); - if (res.next()) { - rows = res.getInt(1); - } - } finally { - close(res); - close(prest); - } - - try { - if (rows > 0) { - executeSQL("ALTER TABLE `" + getPrefix() + "jobs` ADD COLUMN `username` varchar(20);"); - } - - } finally { - } - } - - @Override - protected synchronized void checkUpdate4() throws SQLException { - JobsConnection conn = getConnection(); - if (conn == null) { - Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); - return; - } - PreparedStatement prest = null; - ResultSet res = null; - int rows = 0; - try { - // Check for jobs table - prest = conn.prepareStatement("SELECT COUNT(*) FROM sqlite_master WHERE name = ?;"); - prest.setString(1, getPrefix() + "archive"); - res = prest.executeQuery(); - if (res.next()) { - rows = res.getInt(1); - } - } finally { - close(res); - close(prest); - } - - try { - if (rows == 0) { - executeSQL("CREATE TABLE `" + getPrefix() - + "archive` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `player_uuid` binary(16) NOT NULL, `username` varchar(20), `job` varchar(20), `experience` int, `level` int);"); - } - - } finally { - } - } - - @Override - protected synchronized void checkUpdate5() throws SQLException { - JobsConnection conn = getConnection(); - if (conn == null) { - Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); - return; - } - PreparedStatement prest = null; - ResultSet res = null; - int rows = 0; - try { - // Check for jobs table - prest = conn.prepareStatement("SELECT COUNT(*) FROM sqlite_master WHERE name = ?;"); - prest.setString(1, getPrefix() + "log"); - res = prest.executeQuery(); - if (res.next()) { - rows = res.getInt(1); - } - } finally { - close(res); - close(prest); - } - - try { - if (rows == 0) - executeSQL("CREATE TABLE `" + getPrefix() - + "log` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `player_uuid` binary(16) NOT NULL, `username` varchar(20), `time` bigint, `action` varchar(20), `itemname` varchar(60), `count` int, `money` double, `exp` double);"); - } finally { - } - } - - @Override - protected synchronized void checkUpdate6() throws SQLException { - JobsConnection conn = getConnection(); - if (conn == null) { - Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); - return; - } - - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "log_temp` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `player_uuid` binary(16) NOT NULL, `username` varchar(20), `time` bigint, `action` varchar(20), `itemname` varchar(60), `count` int, `money` double, `exp` double);"); - } catch (Exception e) { - } - try { - executeSQL("INSERT INTO `" + getPrefix() + "log_temp` SELECT `id`, `player_uuid`, `username`, `time`, `action`, `itemname`, `count`, `money`, `exp` FROM `" - + getPrefix() + "log`;"); - } catch (Exception e) { - } - executeSQL("DROP TABLE IF EXISTS `" + getPrefix() + "log`;"); - try { - executeSQL("ALTER TABLE `" + getPrefix() + "log_temp` RENAME TO `" + getPrefix() + "log`;"); - } catch (Exception e) { - } - } - - @Override - protected synchronized void checkUpdate7() throws SQLException { - JobsConnection conn = getConnection(); - if (conn == null) { - Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); - return; - } - - boolean convertJobs = true; - PreparedStatement tempPst = conn.prepareStatement("SELECT * FROM `" + getPrefix() + "jobs`;"); - ResultSet tempRes = tempPst.executeQuery(); - - boolean noJobsdata = true; - try { - while (tempRes.next()) { - noJobsdata = false; - tempRes.getByte("player_uuid"); - break; - } - } catch (Exception e) { - convertJobs = false; - } finally { - tempRes.close(); - tempPst.close(); - } - if (noJobsdata) { - dropDataBase("jobs"); - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "jobs` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `userid` int, `job` varchar(20), `experience` int, `level` int);"); - } catch (SQLException e) { - } - convertJobs = false; - } - - if (convertJobs) { - - Jobs.getPluginLogger().info("Converting byte uuids to string. This could take a long time!!!"); - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "jobs_temp` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `player_uuid` varchar(36) NOT NULL,`username` varchar(20), `job` varchar(20), `experience` int, `level` int);"); - } catch (Exception e) { - } - PreparedStatement pst1 = conn.prepareStatement("SELECT * FROM `" + getPrefix() + "jobs`;"); - ResultSet rs = pst1.executeQuery(); - PreparedStatement insert = null; - conn.setAutoCommit(false); - while (rs.next()) { - byte[] uuidBytes = rs.getBytes("player_uuid"); - - if (uuidBytes == null) - continue; - - String uuid = UUIDUtil.fromBytes(uuidBytes).toString(); - - if (uuid != null) { - insert = conn.prepareStatement("INSERT INTO `" + getPrefix() - + "jobs_temp` (`player_uuid`, `username`, `job`, `experience`, `level`) VALUES (?, ?, ?, ?, ?);"); - insert.setString(1, uuid); - insert.setString(2, rs.getString("username")); - insert.setString(3, rs.getString("job")); - insert.setInt(4, rs.getInt("experience")); - insert.setInt(5, rs.getInt("level")); - insert.addBatch(); - } - } - if (insert != null) - insert.executeBatch(); - conn.commit(); - conn.setAutoCommit(true); - - rs.close(); - pst1.close(); - if (insert != null) - insert.close(); - - executeSQL("DROP TABLE IF EXISTS `" + getPrefix() + "jobs`;"); - try { - executeSQL("ALTER TABLE `" + getPrefix() + "jobs_temp` RENAME TO `" + getPrefix() + "jobs`;"); - } catch (Exception e) { - } - } - - boolean convertArchive = true; - PreparedStatement tempArchivePst = conn.prepareStatement("SELECT * FROM `" + getPrefix() + "archive`;"); - ResultSet tempArchiveRes = tempArchivePst.executeQuery(); - - boolean noArchivedata = true; - try { - while (tempArchiveRes.next()) { - noArchivedata = false; - tempArchiveRes.getByte("player_uuid"); - break; - } - } catch (Exception e) { - convertArchive = false; - } finally { - tempArchiveRes.close(); - tempArchivePst.close(); - } - if (noArchivedata) { - dropDataBase("archive"); - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "archive` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `userid` int, `job` varchar(20), `experience` int, `level` int);"); - } catch (SQLException e) { - } - convertArchive = false; - } - - if (convertArchive) { - // Converting archive players byte uuid into string - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "archive_temp` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `player_uuid` varchar(36) NOT NULL, `username` varchar(20), `job` varchar(20), `experience` int, `level` int);"); - } catch (Exception e) { - } - PreparedStatement pst11 = conn.prepareStatement("SELECT * FROM `" + getPrefix() + "archive`;"); - ResultSet rs1 = pst11.executeQuery(); - PreparedStatement insert1 = null; - conn.setAutoCommit(false); - while (rs1.next()) { - - String uuid = UUIDUtil.fromBytes(rs1.getBytes("player_uuid")).toString(); - - if (uuid != null) { - insert1 = conn.prepareStatement("INSERT INTO `" + getPrefix() - + "archive_temp` (`player_uuid`, `username`, `job`, `experience`, `level`) VALUES (?, ?, ?, ?, ?);"); - insert1.setString(1, uuid); - insert1.setString(2, rs1.getString("username")); - insert1.setString(3, rs1.getString("job")); - insert1.setInt(4, rs1.getInt("experience")); - insert1.setInt(5, rs1.getInt("level")); - insert1.addBatch(); - } - } - if (insert1 != null) - insert1.executeBatch(); - conn.commit(); - conn.setAutoCommit(true); - - rs1.close(); - pst11.close(); - if (insert1 != null) - insert1.close(); - executeSQL("DROP TABLE IF EXISTS `" + getPrefix() + "archive`;"); - try { - executeSQL("ALTER TABLE `" + getPrefix() + "archive_temp` RENAME TO `" + getPrefix() + "archive`;"); - } catch (Exception e) { - - } - } - - // Converting log players byte uuid into string - boolean convertLog = true; - PreparedStatement tempLogPst = conn.prepareStatement("SELECT * FROM `" + getPrefix() + "log`;"); - ResultSet tempLogRes = tempLogPst.executeQuery(); - - boolean nodata = true; - try { - while (tempLogRes.next()) { - nodata = false; - tempLogRes.getByte("player_uuid"); - break; - } - - } catch (Exception e) { - convertLog = false; - } finally { - tempLogRes.close(); - tempLogPst.close(); - } - if (nodata) { - dropDataBase("log"); - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "log` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `userid` int, `time` bigint, `action` varchar(20), `itemname` varchar(60), `count` int, `money` double, `exp` double);"); - } catch (SQLException e) { - } - convertLog = false; - } - - if (convertLog) { - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "log_temp` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `player_uuid` varchar(36) NOT NULL, `username` varchar(20), `time` bigint, `action` varchar(20), `itemname` varchar(60), `count` int, `money` double, `exp` double);"); - } catch (Exception e) { - } - PreparedStatement pst111 = conn.prepareStatement("SELECT * FROM `" + getPrefix() + "log`;"); - ResultSet rs11 = pst111.executeQuery(); - PreparedStatement insert11 = null; - conn.setAutoCommit(false); - while (rs11.next()) { - - String uuid = UUIDUtil.fromBytes(rs11.getBytes("player_uuid")).toString(); - - if (uuid != null) { - insert11 = conn.prepareStatement("INSERT INTO `" + getPrefix() - + "log_temp` (`player_uuid`, `username`, `time`, `action`, `itemname`, `count`, `money`, `exp`) VALUES (?, ?, ?, ?, ?, ?, ?, ?);"); - insert11.setString(1, uuid); - insert11.setString(2, rs11.getString("username")); - insert11.setLong(3, rs11.getLong("time")); - insert11.setString(4, rs11.getString("action")); - insert11.setString(5, rs11.getString("itemname")); - insert11.setInt(6, rs11.getInt("count")); - insert11.setDouble(7, rs11.getDouble("money")); - insert11.setDouble(8, rs11.getDouble("exp")); - insert11.addBatch(); - } - } - if (insert11 != null) - insert11.executeBatch(); - conn.commit(); - conn.setAutoCommit(true); - - rs11.close(); - pst111.close(); - if (insert11 != null) - insert11.close(); - - executeSQL("DROP TABLE IF EXISTS `" + getPrefix() + "log`;"); - try { - executeSQL("ALTER TABLE `" + getPrefix() + "log_temp` RENAME TO `" + getPrefix() + "log`;"); - } catch (Exception e) { - } - } - } - - @Override - protected synchronized void checkUpdate8() throws SQLException { - JobsConnection conn = getConnection(); - if (conn == null) { - Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to MySQL!"); - return; - } - PreparedStatement prest = null; - ResultSet res = null; - int rows = 0; - try { - // Check for jobs table - prest = conn.prepareStatement("SELECT COUNT(*) FROM sqlite_master WHERE name = ?;"); - prest.setString(1, getPrefix() + "explore"); - res = prest.executeQuery(); - if (res.next()) { - rows = res.getInt(1); - } - } finally { - close(res); - close(prest); - } - - try { - if (rows == 0) - executeSQL("CREATE TABLE `" + getPrefix() - + "explore` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `worldname` varchar(64), `chunkX` int, `chunkZ` int, `playerName` varchar(32));"); - } catch (Exception e) { - } finally { - } - } - - @Override - protected synchronized void checkUpdate9() throws SQLException { - JobsConnection conn = getConnection(); - if (conn == null) { - Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to SQLite!"); - return; - } - PreparedStatement prestTemp = null; - ResultSet res1 = null; - int rows = 0; - try { - // Check for jobs table - prestTemp = conn.prepareStatement("SELECT COUNT(*) FROM sqlite_master WHERE name = ?;"); - prestTemp.setString(1, getPrefix() + "users"); - res1 = prestTemp.executeQuery(); - if (res1.next()) { - rows = res1.getInt(1); - } - } finally { - close(res1); - close(prestTemp); - } - - // Create new points table - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "points` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `userid` int, `totalpoints` double, `currentpoints` double);"); - } catch (Exception e) { - } - - // checking log table, recreating if old version present - PreparedStatement prestLogTemp = null; - ResultSet rsLogTemp = null; - boolean next = false; - try { - prestLogTemp = conn.prepareStatement("SELECT * FROM `" + getPrefix() + "log`;"); - rsLogTemp = prestLogTemp.executeQuery(); - while (rsLogTemp.next()) { - next = true; - rsLogTemp.getInt("userid"); - rsLogTemp.getLong("time"); - rsLogTemp.getString("action"); - rsLogTemp.getString("itemname"); - rsLogTemp.getInt("count"); - rsLogTemp.getDouble("money"); - rsLogTemp.getDouble("exp"); - break; - } - } catch (Exception ex) { - - } finally { - close(rsLogTemp); - close(prestLogTemp); - } - - if (!next) { - executeSQL("DROP TABLE IF EXISTS `" + getPrefix() + "log`;"); - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "log` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `userid` int, `time` bigint, `action` varchar(20), `itemname` varchar(60), `count` int, `money` double, `exp` double);"); - } catch (Exception e) { - e.printStackTrace(); - } - } - - if (rows != 0) - return; - - HashMap tempMap = new HashMap(); - PreparedStatement prestJobs = null; - ResultSet res2 = null; - try { - prestJobs = conn.prepareStatement("SELECT * FROM " + getPrefix() + "jobs;"); - res2 = prestJobs.executeQuery(); - while (res2.next()) { - tempMap.put(res2.getString("player_uuid"), res2.getString("username")); - } - } finally { - close(res2); - close(prestJobs); - } - - PreparedStatement prestArchive = null; - ResultSet res3 = null; - try { - prestArchive = conn.prepareStatement("SELECT * FROM " + getPrefix() + "archive;"); - res3 = prestArchive.executeQuery(); - while (res3.next()) { - tempMap.put(res3.getString("player_uuid"), res3.getString("username")); - } - } finally { - close(res3); - close(prestArchive); - } - - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "users` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `player_uuid` varchar(36) NOT NULL, `username` varchar(20));"); - } catch (Exception e) { - } - PreparedStatement prestUsers = null; - try { - prestUsers = conn.prepareStatement("INSERT INTO `" + getPrefix() + "users` (`player_uuid`, `username`) VALUES (?, ?);"); - conn.setAutoCommit(false); - for (Entry users : tempMap.entrySet()) { - prestUsers.setString(1, users.getKey()); - prestUsers.setString(2, users.getValue()); - prestUsers.addBatch(); - } - prestUsers.executeBatch(); - conn.commit(); - conn.setAutoCommit(true); - } finally { - close(prestUsers); - } - - HashMap tempPlayerMap = new HashMap(); - - PreparedStatement prestUsers2 = null; - ResultSet res4 = null; - try { - prestUsers2 = conn.prepareStatement("SELECT * FROM " + getPrefix() + "users;"); - res4 = prestUsers2.executeQuery(); - while (res4.next()) { - tempPlayerMap.put(res4.getString("player_uuid"), new PlayerInfo(res4.getString("username"), res4.getInt("id"), UUID.fromString(res4.getString("player_uuid")), System.currentTimeMillis())); - } - } finally { - close(res4); - close(prestUsers2); - } - - // Modifying jobs main table - try { - executeSQL("ALTER TABLE `" + getPrefix() + "jobs` ADD COLUMN `userid` int;"); - } catch (Exception e) { - } - PreparedStatement prestJobsT = null; - try { - prestJobsT = conn.prepareStatement("UPDATE `" + getPrefix() + "jobs` SET `userid` = ? WHERE `player_uuid` = ?;"); - conn.setAutoCommit(false); - for (Entry users : tempPlayerMap.entrySet()) { - prestJobsT.setInt(1, users.getValue().getID()); - prestJobsT.setString(2, users.getKey()); - prestJobsT.addBatch(); - } - prestJobsT.executeBatch(); - conn.commit(); - conn.setAutoCommit(true); - } catch (Exception e) { - } finally { - close(prestJobsT); - } - - // dropping 2 columns - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "jobs_temp` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `userid` int, `job` varchar(20), `experience` int, `level` int);"); - } catch (Exception e) { - } - - PreparedStatement pst111 = conn.prepareStatement("SELECT * FROM `" + getPrefix() + "jobs`;"); - ResultSet rs11 = pst111.executeQuery(); - PreparedStatement insert11 = null; - while (rs11.next()) { - String uuid = UUIDUtil.fromBytes(rs11.getBytes("player_uuid")).toString(); - if (uuid != null) { - insert11 = conn.prepareStatement("INSERT INTO `" + getPrefix() + "jobs_temp` (`userid`, `job`, `experience`, `level`) VALUES (?, ?, ?, ?);"); - insert11.setInt(1, rs11.getInt("userid")); - insert11.setString(2, rs11.getString("job")); - insert11.setInt(3, rs11.getInt("experience")); - insert11.setInt(4, rs11.getInt("level")); - insert11.execute(); - } - } - rs11.close(); - pst111.close(); - if (insert11 != null) - insert11.close(); - try { - executeSQL("DROP TABLE IF EXISTS `" + getPrefix() + "jobs`;"); - executeSQL("ALTER TABLE `" + getPrefix() + "jobs_temp` RENAME TO `" + getPrefix() + "jobs`;"); - } catch (Exception e) { - } - - // Modifying jobs archive table - try { - executeSQL("ALTER TABLE `" + getPrefix() + "archive` ADD COLUMN `userid` int;"); - } catch (Exception e) { - } - PreparedStatement prestArchiveT = null; - try { - prestArchiveT = conn.prepareStatement("UPDATE `" + getPrefix() + "archive` SET `userid` = ? WHERE `player_uuid` = ?;"); - conn.setAutoCommit(false); - for (Entry users : tempPlayerMap.entrySet()) { - prestArchiveT.setInt(1, users.getValue().getID()); - prestArchiveT.setString(2, users.getKey()); - prestArchiveT.addBatch(); - } - prestArchiveT.executeBatch(); - conn.commit(); - conn.setAutoCommit(true); - } finally { - close(prestArchiveT); - } - - // dropping 2 columns - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "archive_temp` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `userid` int, `job` varchar(20), `experience` int, `level` int);"); - } catch (Exception e) { - } - - PreparedStatement pstArchive = null; - ResultSet rsArchive = null; - PreparedStatement insertArchive = null; - try { - pstArchive = conn.prepareStatement("SELECT * FROM `" + getPrefix() + "archive`;"); - rsArchive = pstArchive.executeQuery(); - while (rsArchive.next()) { - String uuid = UUIDUtil.fromBytes(rsArchive.getBytes("player_uuid")).toString(); - if (uuid != null) { - insertArchive = conn.prepareStatement("INSERT INTO `" + getPrefix() + "archive_temp` (`userid`, `job`, `experience`, `level`) VALUES (?, ?, ?, ?);"); - insertArchive.setInt(1, rsArchive.getInt("userid")); - insertArchive.setString(2, rsArchive.getString("job")); - insertArchive.setInt(3, rsArchive.getInt("experience")); - insertArchive.setInt(4, rsArchive.getInt("level")); - insertArchive.execute(); - } - } - } catch (Exception e) { - } finally { - if (rsArchive != null) - rsArchive.close(); - if (insertArchive != null) - insertArchive.close(); - if (pstArchive != null) - pstArchive.close(); - } - - executeSQL("DROP TABLE IF EXISTS `" + getPrefix() + "archive`;"); - try { - executeSQL("ALTER TABLE `" + getPrefix() + "archive_temp` RENAME TO `" + getPrefix() + "archive`;"); - } catch (Exception e) { - } - // Modifying jobs log table - PreparedStatement prestPreLog = null; - try { - executeSQL("ALTER TABLE `" + getPrefix() + "log` ADD COLUMN `userid` int;"); - prestPreLog = conn.prepareStatement("UPDATE `" + getPrefix() + "log` SET `userid` = ? WHERE `player_uuid` = ?;"); - conn.setAutoCommit(false); - for (Entry users : tempPlayerMap.entrySet()) { - prestPreLog.setInt(1, users.getValue().getID()); - prestPreLog.setString(2, users.getKey()); - prestPreLog.addBatch(); - } - prestPreLog.executeBatch(); - conn.commit(); - conn.setAutoCommit(true); - } finally { - close(prestPreLog); - } - - } - - @Override - protected synchronized void checkUpdate10() { - createDefaultBlockProtection(); - } - - @Override - protected synchronized void checkUpdate11() { - JobsConnection conn = getConnection(); - if (conn == null) { - Jobs.getPluginLogger().severe("Could not run database updates! Could not connect to SQLITE!"); - return; - } - - try { - executeSQL("ALTER TABLE `" + getPrefix() + "users` ADD COLUMN `seen` bigint;"); - } catch (Exception e) { - return; - } finally { - } - - PreparedStatement prest = null; - try { - prest = conn.prepareStatement("UPDATE `" + getPrefix() + "users` SET `seen` = ?;"); - prest.setLong(1, System.currentTimeMillis()); - prest.execute(); - } catch (SQLException e) { - e.printStackTrace(); - } finally { - close(prest); - } - - } - - private boolean createDefaultExploreBase() { - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "explore` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `worldname` varchar(64), `chunkX` int, `chunkZ` int, `playerName` varchar(32));"); - } catch (SQLException e) { - return false; - } - return true; - } - - private boolean createDefaultPointsBase() { - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "points` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `userid` int, `totalpoints` double, `currentpoints` double);"); - } catch (SQLException e) { - return false; - } - return true; - } - - private boolean createDefaultUsersBase() { - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "users` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `player_uuid` varchar(36) NOT NULL, `username` varchar(20), `seen` bigint);"); - } catch (SQLException e) { - return false; - } - return true; - } - - @Override - protected boolean createDefaultLogBase() { - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "log` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `userid` int, `time` bigint, `action` varchar(20), `itemname` varchar(60), `count` int, `money` double, `exp` double);"); - } catch (SQLException e) { - return false; - } - return true; - } - - @Override - protected boolean createDefaultArchiveBase() { - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "archive` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `userid` int, `job` varchar(20), `experience` int, `level` int);"); - } catch (SQLException e) { - return false; - } - return true; - } - - private boolean createDefaultJobsBase() { - try { - executeSQL("CREATE TABLE `" + getPrefix() - + "jobs` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `userid` int, `job` varchar(20), `experience` int, `level` int);"); - } catch (SQLException e) { - return false; - } - return true; - } - - private boolean createDefaultBlockProtection() { - try { - executeSQL("CREATE TABLE IF NOT EXISTS `" + getPrefix() - + "blocks` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `world` varchar(36) NOT NULL, `x` int, `y` int, `z` int, `recorded` bigint, `resets` bigint);"); - } catch (SQLException e) { - return false; - } - return true; - } - - private boolean createDefaultLimitBase() { - try { - executeSQL("CREATE TABLE IF NOT EXISTS `" + getPrefix() - + "limits` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `userid` int, `type` varchar(36), `collected` double, `started` bigint);"); - } catch (SQLException e) { - return false; - } - return true; - } - - @Override - protected boolean dropDataBase(String name) { - try { - executeSQL("DROP TABLE IF EXISTS `" + getPrefix() + name + "`;"); - } catch (SQLException e) { - return false; - } - return true; - } -} diff --git a/src/main/java/com/gamingmesh/jobs/dao/JobsDriver.java b/src/main/java/com/gamingmesh/jobs/dao/JobsDriver.java deleted file mode 100644 index 8d2b27ca..00000000 --- a/src/main/java/com/gamingmesh/jobs/dao/JobsDriver.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.gamingmesh.jobs.dao; - -import java.sql.Connection; -import java.sql.Driver; -import java.sql.DriverPropertyInfo; -import java.sql.SQLException; -import java.sql.SQLFeatureNotSupportedException; -import java.util.Properties; -import java.util.logging.Logger; - -public class JobsDriver - implements Driver { - private Driver driver; - - public JobsDriver(Driver driver) { - this.driver = driver; - } - - @Override - public Connection connect(String url, Properties info) - throws SQLException { - return this.driver.connect(url, info); - } - - @Override - public boolean acceptsURL(String url) - throws SQLException { - return this.driver.acceptsURL(url); - } - - @Override - public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) - throws SQLException { - return this.driver.getPropertyInfo(url, info); - } - - @Override - public int getMajorVersion() { - return this.driver.getMajorVersion(); - } - - @Override - public int getMinorVersion() { - return this.driver.getMinorVersion(); - } - - @Override - public boolean jdbcCompliant() { - return this.driver.jdbcCompliant(); - } - - @Override - public Logger getParentLogger() throws SQLFeatureNotSupportedException { - return this.driver.getParentLogger(); - } -} diff --git a/src/main/java/com/gamingmesh/jobs/dao/JobsManager.java b/src/main/java/com/gamingmesh/jobs/dao/JobsManager.java new file mode 100644 index 00000000..fe8bcd30 --- /dev/null +++ b/src/main/java/com/gamingmesh/jobs/dao/JobsManager.java @@ -0,0 +1,111 @@ +package com.gamingmesh.jobs.dao; + +import java.io.File; + +import org.bukkit.configuration.file.YamlConfiguration; + +import com.gamingmesh.jobs.Jobs; +import com.gamingmesh.jobs.container.LocaleReader; + +public class JobsManager { + private JobsDAO dao; + private Jobs plugin; + private DataBaseType DbType = DataBaseType.SqLite; + + public enum DataBaseType { + MySQL, SqLite + } + + public JobsManager(Jobs plugin) { + this.plugin = plugin; + } + + public JobsDAO getDB() { + return dao; + } + + public void switchDataBase() { + if (dao != null) + dao.closeConnections(); + switch (DbType) { + case MySQL: + DbType = DataBaseType.SqLite; + dao = startSqlite(); + dao.setDbType(DbType); + break; + case SqLite: + DbType = DataBaseType.MySQL; + dao = startMysql(); + dao.setDbType(DbType); + break; + } + Jobs.setDAO(dao); + } + + public void start(LocaleReader c) { + c.getW().addComment("storage.method", "storage method, can be MySQL or sqlite"); + String storageMethod = c.get("storage.method", "sqlite"); + c.getW().addComment("mysql-username", "Requires Mysql."); + c.get("mysql-username", "root"); + c.get("mysql-password", ""); + c.get("mysql-hostname", "localhost:3306"); + c.get("mysql-database", "minecraft"); + c.get("mysql-table-prefix", "jobs_"); + + if (storageMethod.equalsIgnoreCase("mysql")) { + DbType = DataBaseType.MySQL; + dao = startMysql(); + } else if (storageMethod.equalsIgnoreCase("sqlite")) { + DbType = DataBaseType.SqLite; + dao = startSqlite(); + } else { + Jobs.consoleMsg("&cInvalid storage method! Changing method to sqlite!"); + c.getC().set("storage.method", "sqlite"); + DbType = DataBaseType.SqLite; + dao = startSqlite(); + } + Jobs.setDAO(dao); + } + + private synchronized JobsMySQL startMysql() { + File f = new File(plugin.getDataFolder(), "generalConfig.yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration(f); + String legacyUrl = config.getString("mysql-url"); + if (legacyUrl != null) { + String jdbcString = "jdbc:mysql://"; + if (legacyUrl.toLowerCase().startsWith(jdbcString)) { + legacyUrl = legacyUrl.substring(jdbcString.length()); + String[] parts = legacyUrl.split("/"); + if (parts.length >= 2) { + config.set("mysql-hostname", parts[0]); + config.set("mysql-database", parts[1]); + } + } + } + String username = config.getString("mysql-username"); + if (username == null) { + Jobs.getPluginLogger().severe("mysql-username property invalid or missing"); + } + String password = config.getString("mysql-password"); + String hostname = config.getString("mysql-hostname"); + String database = config.getString("mysql-database"); + String prefix = config.getString("mysql-table-prefix"); + if (plugin.isEnabled()) { + JobsMySQL data = new JobsMySQL(plugin, hostname, database, username, password, prefix); + data.initialize(); + return data; + } + return null; + } + + private synchronized JobsSQLite startSqlite() { + JobsSQLite data = new JobsSQLite(plugin, plugin.getDataFolder()); + data.initialize(); + return data; + } + + public DataBaseType getDbType() { + return DbType; + } + +} diff --git a/src/main/java/com/gamingmesh/jobs/dao/JobsMySQL.java b/src/main/java/com/gamingmesh/jobs/dao/JobsMySQL.java new file mode 100644 index 00000000..ed542cfa --- /dev/null +++ b/src/main/java/com/gamingmesh/jobs/dao/JobsMySQL.java @@ -0,0 +1,250 @@ +package com.gamingmesh.jobs.dao; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import com.gamingmesh.jobs.Jobs; +import com.gamingmesh.jobs.dao.JobsManager.DataBaseType; + +public class JobsMySQL extends JobsDAO { + private String database; + private Jobs plugin; + + JobsMySQL(Jobs plugin, String hostname, String database, String username, String password, String prefix) { + super(plugin, "com.mysql.jdbc.Driver", "jdbc:mysql://" + hostname + "/" + database + "?autoReconnect=true&useSSL=false", username, password, prefix); + this.plugin = plugin; + this.database = database; + this.setDbType(DataBaseType.MySQL); + } + + public void initialize() { + try { + setUp(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + public JobsMySQL initialize(Jobs plugin, String hostname, String database, String username, String password, String prefix) { + this.plugin = plugin; + JobsMySQL dao = new JobsMySQL(plugin, hostname, database, username, password, prefix); + try { + dao.setUp(); + } catch (SQLException e) { + e.printStackTrace(); + } + return dao; + } + + @Override + protected synchronized void setupConfig() throws SQLException { + JobsConnection conn = getConnection(); + if (conn == null) { + Jobs.consoleMsg("&cCould not run database updates! Could not connect to MySQL!"); + return; + } + PreparedStatement prest = null; + int rows = 0; + ResultSet res = null; + try { + // Check for config table + prest = conn.prepareStatement("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = ? AND table_name = ?;"); + prest.setString(1, database); + prest.setString(2, getPrefix() + "config"); + res = prest.executeQuery(); + if (res.next()) { + rows = res.getInt(1); + } + } finally { + close(res); + close(prest); + } + + if (rows == 0) { + PreparedStatement insert = null; + try { + executeSQL("CREATE TABLE `" + getPrefix() + "config` (`key` varchar(50) NOT NULL PRIMARY KEY, `value` int NOT NULL);"); + + insert = conn.prepareStatement("INSERT INTO `" + getPrefix() + "config` (`key`, `value`) VALUES (?, ?);"); + insert.setString(1, "version"); + insert.setInt(2, 1); + insert.execute(); + } finally { + close(insert); + } + } + } + + @Override + protected synchronized void checkUpdate() throws SQLException { + JobsConnection conn = getConnection(); + if (conn == null) { + Jobs.consoleMsg("&cCould not run database updates! Could not connect to MySQL!"); + return; + } + createDefaultUsersBase(); + } + + private boolean createDefaultUsersBase() { + try { + executeSQL("CREATE TABLE `" + getPrefix() + + "users` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `player_uuid` varchar(36) NOT NULL, `username` varchar(20), `seen` bigint);"); + } catch (SQLException e) { + e.printStackTrace(); + return false; + } + return true; + } + + @Override + public Statement prepareStatement(String query) throws SQLException { + JobsConnection conn = getConnection(); + if (conn == null) + return null; + PreparedStatement prest = null; + try { + prest = conn.prepareStatement(query); + } catch (SQLException | NumberFormatException e) { + e.printStackTrace(); + } + return prest; + } + + @SuppressWarnings("resource") + @Override + public boolean createTable(String query) { + Jobs.consoleMsg(query); + Statement statement = null; + if (query == null || query.equals("")) { + Jobs.consoleMsg("&cCould not create table: query is empty or null."); + return false; + } + + try { + statement = getConnection().createStatement(); + statement.execute(query); + statement.close(); + } catch (SQLException e) { + Jobs.consoleMsg("&cCould not create table, SQLException: " + e.getMessage()); + close(statement); + return false; + } finally { + close(statement); + } + return true; + } + + @SuppressWarnings("resource") + @Override + public boolean isTable(String table) { + Statement statement; + try { + statement = getConnection().createStatement(); + } catch (SQLException e) { + Jobs.consoleMsg("&cCould not check if its table, SQLException: " + e.getMessage()); + return false; + } + try { + statement.executeQuery("SELECT * FROM " + table); + statement.close(); + return true; + } catch (SQLException e) { + Jobs.consoleMsg("Not a table |" + "SELECT * FROM " + table + "|"); + close(statement); + return false; + } + } + + @SuppressWarnings("resource") + @Override + public boolean isCollumn(String table, String collumn) { + Statement statement; + try { + statement = getConnection().createStatement(); + } catch (SQLException e) { + Jobs.consoleMsg("&cCould not check if its collumn, SQLException: " + e.getMessage()); + return false; + } + try { + statement.executeQuery("SELECT " + collumn + " FROM " + table); + statement.close(); + return true; + } catch (SQLException e) { + Jobs.consoleMsg("Not a culumn |" + "SELECT " + collumn + " FROM " + table + "|"); + close(statement); + return false; + } + } + + @SuppressWarnings("resource") + @Override + public boolean addCollumn(String table, String collumn, String type) { + Statement statement; + try { + statement = getConnection().createStatement(); + } catch (SQLException e) { + Jobs.consoleMsg("&cCould not add new collumn, SQLException: " + e.getMessage()); + return false; + } + try { + Jobs.consoleMsg("Creating culumn |" + "ALTER TABLE `" + table + "` ADD COLUMN `" + collumn + "` " + type + ";" + "|"); + statement.executeUpdate("ALTER TABLE `" + table + "` ADD COLUMN `" + collumn + "` " + type + ";"); + statement.close(); + return true; + } catch (SQLException e) { + close(statement); + e.printStackTrace(); + return false; + } + } + + @SuppressWarnings("resource") + @Override + public boolean truncate(String table) { + Statement statement = null; + String query = null; + try { + if (!this.isTable(table)) { + Jobs.consoleMsg("&cTable \"" + table + "\" does not exist."); + return false; + } + statement = getConnection().createStatement(); + query = "DELETE FROM " + table + ";"; + statement.executeUpdate(query); + statement.close(); + + return true; + } catch (SQLException e) { + Jobs.consoleMsg("&cCould not wipe table, SQLException: " + e.getMessage()); + close(statement); + e.printStackTrace(); + return false; + } + } + + @SuppressWarnings("resource") + @Override + public boolean drop(String table) { + Statement statement = null; + String query = null; + try { + if (!this.isTable(table)) { + Jobs.consoleMsg("&cTable \"" + table + "\" does not exist."); + return false; + } + statement = getConnection().createStatement(); + query = "DROP TABLE IF EXISTS `" + table + "`;"; + statement.executeUpdate(query); + statement.close(); + + return true; + } catch (SQLException e) { + Jobs.consoleMsg("&cCould not wipe table, SQLException: " + e.getMessage()); + close(statement); + e.printStackTrace(); + return false; + } + } +} diff --git a/src/main/java/com/gamingmesh/jobs/dao/JobsSQLite.java b/src/main/java/com/gamingmesh/jobs/dao/JobsSQLite.java new file mode 100644 index 00000000..c8ffb499 --- /dev/null +++ b/src/main/java/com/gamingmesh/jobs/dao/JobsSQLite.java @@ -0,0 +1,240 @@ +package com.gamingmesh.jobs.dao; + +import java.io.File; +import java.sql.DatabaseMetaData; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import com.gamingmesh.jobs.Jobs; +import com.gamingmesh.jobs.dao.JobsManager.DataBaseType; + +public class JobsSQLite extends JobsDAO { + private Jobs plugin; + + public void initialize() { + try { + this.setUp(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + public JobsSQLite initialize(Jobs plugin, File dir) { + this.plugin = plugin; + if (!dir.exists()) + dir.mkdirs(); + try { + this.setUp(); + } catch (SQLException e) { + e.printStackTrace(); + } + return this; + } + + JobsSQLite(Jobs plugin, File file) { + super(plugin, "org.sqlite.JDBC", "jdbc:sqlite:" + new File(file, "jobs.sqlite.db").getPath(), null, null, ""); + if (!file.exists()) + file.mkdirs(); + this.setDbType(DataBaseType.SqLite); + } + + @Override + protected synchronized void setupConfig() throws SQLException { + JobsConnection conn = getConnection(); + if (conn == null) { + Jobs.consoleMsg("&cCould not run database updates! Could not connect to MySQL!"); + return; + } + + PreparedStatement prest = null; + ResultSet res = null; + int rows = 0; + try { + // Check for config table + prest = conn.prepareStatement("SELECT COUNT(*) FROM sqlite_master WHERE name = ?;"); + prest.setString(1, getPrefix() + "config"); + res = prest.executeQuery(); + if (res.next()) { + rows = res.getInt(1); + } + } finally { + close(res); + close(prest); + } + + if (rows == 0) { + PreparedStatement insert = null; + try { + executeSQL("CREATE TABLE `" + getPrefix() + "config` (`key` varchar(50) NOT NULL PRIMARY KEY, `value` int NOT NULL);"); + insert = conn.prepareStatement("INSERT INTO `" + getPrefix() + "config` (`key`, `value`) VALUES (?, ?);"); + insert.setString(1, "version"); + insert.setInt(2, 1); + insert.execute(); + } finally { + close(insert); + } + } + } + + @Override + protected synchronized void checkUpdate() throws SQLException { + JobsConnection conn = getConnection(); + if (conn == null) { + Jobs.consoleMsg("&cCould not run database updates! Could not connect to MySQL!"); + return; + } + createDefaultUsersBase(); + } + + private boolean createDefaultUsersBase() { + try { + executeSQL("CREATE TABLE `" + getPrefix() + + "users` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `player_uuid` varchar(36) NOT NULL, `username` varchar(20), `data` text);"); + } catch (SQLException e) { + return false; + } + return true; + } + + @Override + public Statement prepareStatement(String query) throws SQLException { + JobsConnection conn = getConnection(); + if (conn == null) + return null; + PreparedStatement prest = null; + try { + prest = conn.prepareStatement(query); + } catch (SQLException | NumberFormatException e) { + e.printStackTrace(); + } + return prest; + } + + @SuppressWarnings("resource") + @Override + public boolean createTable(String query) { + Statement statement = null; + try { + if (query == null || query.equals("")) { + Jobs.consoleMsg("&cCould not create table: query is empty or null."); + return false; + } + + statement = getConnection().createStatement(); + statement.execute(query); + statement.close(); + return true; + } catch (SQLException e) { + Jobs.consoleMsg("&cCould not create table, SQLException: " + e.getMessage()); + close(statement); + return false; + } + } + + @Override + public boolean isTable(String table) { + DatabaseMetaData md = null; + try { + md = this.getConnection().getMetaData(); + ResultSet tables = md.getTables(null, null, table, null); + if (tables.next()) { + tables.close(); + return true; + } + tables.close(); + return false; + } catch (SQLException e) { + Jobs.consoleMsg("&cCould not check if table \"" + table + "\" exists, SQLException: " + e.getMessage()); + return false; + } + } + + @Override + public boolean isCollumn(String table, String collumn) { + DatabaseMetaData md = null; + try { + md = this.getConnection().getMetaData(); + ResultSet tables = md.getColumns(null, null, table, collumn); + if (tables.next()) { + tables.close(); + return true; + } + tables.close(); + return false; + } catch (SQLException e) { + Jobs.consoleMsg("&cCould not check if table \"" + table + "\" exists, SQLException: " + e.getMessage()); + return false; + } + } + + @SuppressWarnings("resource") + @Override + public boolean addCollumn(String table, String collumn, String type) { + Statement statement; + try { + statement = getConnection().createStatement(); + } catch (SQLException e) { + Jobs.consoleMsg("&cCould not add new collumn, SQLException: " + e.getMessage()); + return false; + } + try { + statement.executeQuery("ALTER TABLE " + table + " ADD " + collumn + " " + type); + statement.close(); + return true; + } catch (SQLException e) { + close(statement); + return false; + } + } + + @SuppressWarnings("resource") + @Override + public boolean truncate(String table) { + Statement statement = null; + String query = null; + try { + if (!this.isTable(table)) { + Jobs.consoleMsg("&cTable \"" + table + "\" does not exist."); + return false; + } + statement = getConnection().createStatement(); + query = "DELETE FROM " + table + ";"; + statement.executeQuery(query); + statement.close(); + return true; + } catch (SQLException e) { + if (!(e.getMessage().toLowerCase().contains("locking") || e.getMessage().toLowerCase().contains("locked")) && + !e.toString().contains("not return ResultSet")) + Jobs.consoleMsg("&cError in wipeTable() query: " + e); + close(statement); + return false; + } + } + + @Override + public boolean drop(String table) { + Statement statement = null; + String query = null; + try { + if (!this.isTable(table)) { + Jobs.consoleMsg("&cTable \"" + table + "\" does not exist."); + return false; + } + statement = getConnection().createStatement(); + query = "DROP TABLE IF EXISTS `" + table + "`;"; + statement.executeQuery(query); + statement.close(); + return true; + } catch (SQLException e) { + if (!(e.getMessage().toLowerCase().contains("locking") || e.getMessage().toLowerCase().contains("locked")) && + !e.toString().contains("not return ResultSet")) + Jobs.consoleMsg("&cError in dropTable() query: " + e); + close(statement); + return false; + } finally { + close(statement); + } + } +} diff --git a/src/main/java/com/gamingmesh/jobs/dao/JobsTableInterface.java b/src/main/java/com/gamingmesh/jobs/dao/JobsTableInterface.java new file mode 100644 index 00000000..0581426e --- /dev/null +++ b/src/main/java/com/gamingmesh/jobs/dao/JobsTableInterface.java @@ -0,0 +1,13 @@ +package com.gamingmesh.jobs.dao; + +import com.gamingmesh.jobs.dao.JobsDAO.TablesFieldsType; + +public interface JobsTableInterface { + + String getCollumn(); + + String getType(); + + TablesFieldsType getFieldType(); + +} diff --git a/src/main/java/com/gamingmesh/jobs/stuff/JobsClassLoader.java b/src/main/java/com/gamingmesh/jobs/stuff/JobsClassLoader.java deleted file mode 100644 index 652f27c0..00000000 --- a/src/main/java/com/gamingmesh/jobs/stuff/JobsClassLoader.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Jobs Plugin for Bukkit - * Copyright (C) 2011 Zak Ford - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.gamingmesh.jobs.stuff; - -import java.io.File; -import java.io.IOException; -import java.net.URL; -import java.net.URLClassLoader; - -import com.gamingmesh.jobs.Jobs; - -public class JobsClassLoader extends URLClassLoader { - - public JobsClassLoader(Jobs core) { - super(new URL[0], core.getClass().getClassLoader()); - } - - public void addFile(File f) throws IOException { - addURL(f.toURI().toURL()); - } - - @Override - public void addURL(URL url) { - for (URL u : getURLs()) - if (url.sameFile(u)) return; - - super.addURL(url); - } -} diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 821e3be8..1efad21c 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,10 +1,10 @@ name: Jobs description: Jobs Plugin for the BukkitAPI main: com.gamingmesh.jobs.Jobs -version: 3.9.7 +version: 3.9.8 website: https://www.spigotmc.org/resources/jobs-reborn.4216/ author: phrstbrn -softdepend: [Vault, iConomy, MythicMobs, McMMO, WorldGuard] +softdepend: [Vault, iConomy, MythicMobs, McMMO, WorldGuard, MyPet] commands: jobs: description: Jobs