Ongoing fee

Former-commit-id: 10e0f9943e56ff9359d1ce86ee192295f9003215
This commit is contained in:
Ghost_chu committed 2018-10-20 19:30:25 +08:00
1 parent 6b7194a9d2
commit d28a43be0e
12 files changed
+364 -92

No files matched your search

@@ -12,8 +12,24 @@ public class DatabaseHelper {
if (!db.hasTable("messages")) {
createMessagesTable(db);
}
if (!db.hasTable("schedule")) {
createScheduleTable(db);
}
checkColumns(db);
}
/**
* Creates the database table 'schedule'.
*
* @throws SQLException
* If the connection is invalid.
*/
public static void createScheduleTable(Database db) throws SQLException {
Statement st = db.getConnection().createStatement();
//String createTable = "CREATE TABLE shops (" + "owner TEXT(32) NOT NULL, " + "price double(32, 2) NOT NULL, " + "itemConfig TEXT CHARSET utf8 NOT NULL, " + "x INTEGER(32) NOT NULL, " + "y INTEGER(32) NOT NULL, " + "z INTEGER(32) NOT NULL, " + "world VARCHAR(32) NOT NULL, " + "unlimited boolean, " + "type boolean, " + "PRIMARY KEY (x, y, z, world) " + ");";
String createTable ="CREATE TABLE schedule (owner TEXT(32) NOT NULL, world VARCHAR(32) NOT NULL, x INT NOT NULL, y INT NOT NULL, z INT NOT NULL, timestamp INT NOT NULL, PRIMARY KEY (owner, world, x, y, z, timestamp) );";
st.execute(createTable);
}
/**
* Verifies that all required columns exist.
@@ -59,4 +75,5 @@ public class DatabaseHelper {
String createTable = "CREATE TABLE messages (" + "owner TEXT(32) NOT NULL, " + "message TEXT(200) NOT NULL, " + "time BIGINT(32) NOT NULL " + ");";
st.execute(createTable);
}
}
@@ -8,6 +8,7 @@ import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.maxgamer.quickshop.QuickShop;
import org.maxgamer.quickshop.Util.Util;
public class Economy_Vault implements EconomyCore {
private Economy vault;
@@ -32,6 +33,7 @@ public class Economy_Vault implements EconomyCore {
@Deprecated
public boolean deposit(String name, double amount) {
Util.sendDeprecatedMethodWarn();
boolean result = this.vault.depositPlayer(name, amount).transactionSuccess();
return result;
}
@@ -44,6 +46,7 @@ public class Economy_Vault implements EconomyCore {
@Deprecated
public boolean transfer(String from, String to, double amount) {
Util.sendDeprecatedMethodWarn();
if (this.vault.getBalance(from) >= amount) {
if (this.vault.withdrawPlayer(from, amount).transactionSuccess()) {
if (!this.vault.depositPlayer(to, amount).transactionSuccess()) {
@@ -59,6 +62,7 @@ public class Economy_Vault implements EconomyCore {
@Deprecated
public double getBalance(String name) {
Util.sendDeprecatedMethodWarn();
return this.vault.getBalance(name);
}
@@ -1,17 +1,15 @@
package org.maxgamer.quickshop;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
@@ -19,11 +17,8 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.UUID;
import javax.net.ssl.HttpsURLConnection;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
@@ -62,29 +57,25 @@ import org.maxgamer.quickshop.Shop.ShopType;
import org.maxgamer.quickshop.Util.MsgUtil;
//import org.maxgamer.quickshop.Util.NMS;
import org.maxgamer.quickshop.Util.Permissions;
import org.maxgamer.quickshop.Util.Updater;
import org.maxgamer.quickshop.Util.Util;
import org.maxgamer.quickshop.Watcher.ItemWatcher;
import org.maxgamer.quickshop.Watcher.LogWatcher;
import org.maxgamer.quickshop.Watcher.OngoineFeeWatcher;
import org.maxgamer.quickshop.Watcher.UpdateWatcher;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.sun.deploy.uitoolkit.impl.fx.Utils;
@SuppressWarnings("deprecation")
public class QuickShop extends JavaPlugin {
/** The active instance of QuickShop */
public static QuickShop instance;
OngoineFeeWatcher ongoineFeeWatcher = new OngoineFeeWatcher();
/** The economy we hook into for transactions */
private Economy economy;
/** The Shop Manager used to store shops */
private ShopManager shopManager;
/**
* A set of players who have been warned
* ("Your shop isn't automatically locked")
* A set of players who have been warned ("Your shop isn't automatically
* locked")
*/
public HashSet<String> warnings = new HashSet<String>();
/** The database for storing all our data for persistence */
@@ -108,23 +99,23 @@ public class QuickShop extends JavaPlugin {
/** Whether we should use display items or not */
public boolean display = true;
/**
* Whether we players are charged a fee to change the price on their shop
* (To help deter endless undercutting
* Whether we players are charged a fee to change the price on their shop (To
* help deter endless undercutting
*/
public boolean priceChangeRequiresFee = false;
/** Whether or not to limit players shop amounts */
public boolean limit = false;
/** The plugin OpenInv (null if not present) */
public Plugin openInvPlugin;
private HashMap<String, Integer> limits = new HashMap<String, Integer>();
/** Use SpoutPlugin to get item / block names */
public boolean useSpout = false;
// private Metrics metrics;
MultiverseCore mPlugin = null;
private int displayItemCheckTicks;
/** The plugin metrics from Hidendra */
@@ -345,6 +336,8 @@ public class QuickShop extends JavaPlugin {
} catch (IllegalArgumentException e) {
// This could be old data to be converted... check if it's a player
step = "Update owner to UUID";
// Because need update database, so use crossed method, Set ignore.
@SuppressWarnings("deprecation")
OfflinePlayer player = Bukkit.getOfflinePlayer(owner);
if (player.hasPlayedBefore()) {
ownerUUID = player.getUniqueId();
@@ -358,6 +351,10 @@ public class QuickShop extends JavaPlugin {
.executeUpdate("DELETE FROM shops WHERE x = " + x + " AND y = " + y + " AND z = "
+ z + " AND world = \"" + worldName + "\""
+ (getDB().getCore() instanceof MySQLCore ? " LIMIT 1" : ""));
getDB().getConnection().createStatement()
.executeUpdate("DELETE FROM schedule WHERE x = " + x + " AND y = " + y + " AND z = "
+ z + " AND world = \"" + worldName + "\""
+ (getDB().getCore() instanceof MySQLCore ? " LIMIT 1" : ""));
continue;
}
}
@@ -375,6 +372,10 @@ public class QuickShop extends JavaPlugin {
.executeUpdate("DELETE FROM shops WHERE x = " + x + " AND y = " + y + " AND z = " + z
+ " AND world = \"" + worldName + "\""
+ (getDB().getCore() instanceof MySQLCore ? " LIMIT 1" : ""));
getDB().getConnection().createStatement()
.executeUpdate("DELETE FROM schedule WHERE x = " + x + " AND y = " + y + " AND z = " + z
+ " AND world = \"" + worldName + "\""
+ (getDB().getCore() instanceof MySQLCore ? " LIMIT 1" : ""));
continue;
}
step = "Loading shop type";
@@ -387,6 +388,33 @@ public class QuickShop extends JavaPlugin {
shop.setShopType(ShopType.fromID(type));
step = "Loading shop to memory";
shopManager.loadShop(rs.getString("world"), shop);
if(getConfig().getBoolean("ongoingfee.reset-on-startup")) {
step = "Reset schedule data";
getDB().getConnection().createStatement()
.executeUpdate("DELETE FROM schedule WHERE x = " + x + " AND y = " + y + " AND z = " + z
+ " AND world = \"" + worldName + "\""
+ (getDB().getCore() instanceof MySQLCore ? " LIMIT 1" : ""));
}
step = "Checking shop schedule data";
//Check shop is or not exist in schedule table
Statement st = getDB().getConnection().createStatement();
String checkq = "SELECT * FROM schedule WHERE owner ='{owner}' and world ='{world}' and x ='{x}' and y ='{y}' and z='{z}' and timestamp ='%'";
checkq.replace("{x}", String.valueOf(loc.getBlockX()));
checkq.replace("{y}", String.valueOf(loc.getBlockY()));
checkq.replace("{z}", String.valueOf(loc.getBlockZ()));
checkq.replace("{world}", String.valueOf(loc.getWorld().getName()));
checkq.replace("{owner}", shop.getOwner().toString());
ResultSet resultSet = st.executeQuery(checkq);
if(!resultSet.next()) {
//Not exist, write in
step = "Writeing shop schedule data";
String scheduleq = "INSERT INTO schedule (owner, world, x, y, z, timestamp) VALUES (?, ?, ?, ?, ?, ?)";
getDB().execute(scheduleq , shop.getOwner().toString(), loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), System.currentTimeMillis());
getLogger().info("Adding shop at world:"+loc.getWorld().getName()+" x:"+loc.getBlockX()+" y:"+loc.getBlockY()+" z:"+loc.getBlockZ()+" into schedule table");
}
if (loc.getWorld() != null && loc.getChunk().isLoaded()) {
step = "Loading shop to memory >> Chunk loaded, Loaded to memory";
shop.onLoad();
@@ -426,7 +454,12 @@ public class QuickShop extends JavaPlugin {
getLogger().severe("Connected:" + !getDB().getConnection().isClosed());
getLogger().severe("Read Only:" + getDB().getConnection().isReadOnly());
getLogger().severe("Client Info:" + getDB().getConnection().getClientInfo().toString());
if(getDB().getConnection().getClientInfo()!=null) {
getLogger().severe("Client Info: " + getDB().getConnection().getClientInfo().toString());
}else {
getLogger().severe("Client Info: null");
}
getLogger().severe("Read Only:" + getDB().getConnection().isReadOnly());
getLogger().severe("#Debuging >>");
@@ -447,7 +480,6 @@ public class QuickShop extends JavaPlugin {
try {
bksqlfile.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
getLogger().severe("Failed to backup! (Create)");
}
@@ -482,6 +514,14 @@ public class QuickShop extends JavaPlugin {
delps.setInt(3, z);
delps.setString(4, worldName);
delps.execute();
PreparedStatement scdelps = getDB().getConnection()
.prepareStatement("DELETE FROM schedule WHERE x = ? AND y = ? and z = ? and world = ?");
scdelps.setInt(1, x);
scdelps.setInt(2, y);
scdelps.setInt(3, z);
scdelps.setString(4, worldName);
scdelps.execute();
getLogger().info("Trying keep loading...");
} else {
getLogger().severe(
@@ -494,6 +534,14 @@ public class QuickShop extends JavaPlugin {
delps.setInt(3, z);
delps.setString(4, worldName);
delps.execute();
PreparedStatement scdelps = getDB().getConnection()
.prepareStatement("DELETE FROM schedule WHERE x = ? AND y = ? and z = ? and world = ?");
scdelps.setInt(1, x);
scdelps.setInt(2, y);
scdelps.setInt(3, z);
scdelps.setString(4, worldName);
scdelps.execute();
e.printStackTrace();
}
}
@@ -625,19 +673,19 @@ public class QuickShop extends JavaPlugin {
} else {
use_protect_hopper = "Disabled";
}
String shop_find_distance = getConfig().getString("shop.find-distance");
String float_filter_enable = boolean2String(getConfig().getBoolean("float.enable"));
String float_filter_item_enable = boolean2String(getConfig().getBoolean("float.item.enable"));
String float_filter_lore_enable = boolean2String(getConfig().getBoolean("float.lore.enable"));
String float_filter_displayname_enable = boolean2String(getConfig().getBoolean("float.displayname.enable"));
String float_filter_item_blacklist = boolean2String(getConfig().getBoolean("float.item.blacklist"));
String float_filter_lore_blacklist = boolean2String(getConfig().getBoolean("float.lore.blacklist"));
String float_filter_displayname_blacklist = boolean2String(getConfig().getBoolean("float.displayname.blacklist"));
String float_filter_displayname_blacklist = boolean2String(
getConfig().getBoolean("float.displayname.blacklist"));
// Version
metrics.addCustomChart(new Metrics.SimplePie("server_version", () -> serverVer));
metrics.addCustomChart(new Metrics.SimplePie("bukkit_version", () -> bukkitVer));
@@ -652,40 +700,45 @@ public class QuickShop extends JavaPlugin {
metrics.addCustomChart(new Metrics.SimplePie("use_protect_explode", () -> use_protect_explode));
metrics.addCustomChart(new Metrics.SimplePie("use_protect_hopper", () -> use_protect_hopper));
metrics.addCustomChart(new Metrics.SimplePie("shop_find_distance", () -> shop_find_distance));
//Exp for stats, maybe i need improve this, so i add this.
// Exp for stats, maybe i need improve this, so i add this.
metrics.addCustomChart(new Metrics.SimplePie("float_filter_enable", () -> float_filter_enable));
metrics.addCustomChart(new Metrics.SimplePie("float_filter_item_enable", () -> float_filter_item_enable));
metrics.addCustomChart(new Metrics.SimplePie("float_filter_lore_enable", () -> float_filter_lore_enable));
metrics.addCustomChart(new Metrics.SimplePie("float_filter_displayname_enable", () -> float_filter_displayname_enable));
metrics.addCustomChart(new Metrics.SimplePie("float_filter_item_blacklist", () -> float_filter_item_blacklist));
metrics.addCustomChart(new Metrics.SimplePie("float_filter_lore_blacklist", () -> float_filter_lore_blacklist));
metrics.addCustomChart(new Metrics.SimplePie("float_filter_displayname_blacklist", () -> float_filter_displayname_blacklist));
metrics.addCustomChart(
new Metrics.SimplePie("float_filter_displayname_enable", () -> float_filter_displayname_enable));
metrics.addCustomChart(
new Metrics.SimplePie("float_filter_item_blacklist", () -> float_filter_item_blacklist));
metrics.addCustomChart(
new Metrics.SimplePie("float_filter_lore_blacklist", () -> float_filter_lore_blacklist));
metrics.addCustomChart(new Metrics.SimplePie("float_filter_displayname_blacklist",
() -> float_filter_displayname_blacklist));
metrics.submitData(); // Submit now!
getLogger().info("Mertics submited.");
} else {
getLogger().info("You have disabled mertics, Skipping...");
}
UpdateWatcher.init();
ongoineFeeWatcher.init();
}
public String boolean2String(boolean bool) {
if(bool) {
if (bool) {
return "Enabled";
}else {
} else {
return "Disabled";
}
}
public boolean updateConfig(int oldConfigVersion, int currentConfigVersion) {
updateConfig(oldConfigVersion);
getLogger().info("Complete config update!.");
getLogger().info("Complete config update!");
return true;
}
public void updateConfig(int selectedVersion) {
getLogger().info("Auto updateing config.yml ...");
if (selectedVersion == 1) {
@@ -693,7 +746,7 @@ public class QuickShop extends JavaPlugin {
getConfig().set("config-version", 2);
selectedVersion = 2;
}
if (selectedVersion == 2) {
if (selectedVersion == 2) {
getConfig().set("protect.minecart", true);
getConfig().set("protect.entity", true);
getConfig().set("protect.redstone", true);
@@ -708,7 +761,7 @@ public class QuickShop extends JavaPlugin {
getConfig().set("config-version", 4);
selectedVersion = 4;
}
if(selectedVersion == 4) {
if (selectedVersion == 4) {
getConfig().set("updater", true);
getConfig().set("config-version", 5);
selectedVersion = 5;
@@ -733,25 +786,25 @@ public class QuickShop extends JavaPlugin {
* Tries to load the economy and its core. If this fails, it will try to use
* vault. If that fails, it will return false.
*
* @return true if successful, false if the core is invalid or is not found,
* and vault cannot be used.
* @return true if successful, false if the core is invalid or is not found, and
* vault cannot be used.
*/
public boolean loadEcon() {
try {
EconomyCore core = new Economy_Vault();
if (core == null || !core.isValid()) {
// getLogger().severe("Economy is not valid!");
getLogger().severe("QuickShop could not hook an economy/Not found Vault!");
getLogger().severe("QuickShop CANNOT start!");
this.getPluginLoader().disablePlugin(this);
// if(econ.equals("Vault"))
// getLogger().severe("(Does Vault have an Economy to hook into?!)");
return false;
} else {
this.economy = new Economy(core);
return true;
}
}catch (Exception e) {
EconomyCore core = new Economy_Vault();
if (core == null || !core.isValid()) {
// getLogger().severe("Economy is not valid!");
getLogger().severe("QuickShop could not hook an economy/Not found Vault!");
getLogger().severe("QuickShop CANNOT start!");
this.getPluginLoader().disablePlugin(this);
// if(econ.equals("Vault"))
// getLogger().severe("(Does Vault have an Economy to hook into?!)");
return false;
} else {
this.economy = new Economy(core);
return true;
}
} catch (Exception e) {
e.printStackTrace();
getLogger().severe("QuickShop could not hook an economy/Not found Vault!");
getLogger().severe("QuickShop CANNOT start!");
@@ -767,11 +820,13 @@ public class QuickShop extends JavaPlugin {
logWatcher.task.cancel();
logWatcher.close(); // Closes the file
}
/* Unload UpdateWatcher */
UpdateWatcher.uninit();
/* Remove all display items, and any dupes we can find */
shopManager.clear();
/* Empty the buffer */
database.close();
/* Close Database */
try {
this.database.getConnection().close();
} catch (SQLException e) {
@@ -779,6 +834,7 @@ public class QuickShop extends JavaPlugin {
}
this.warnings.clear();
this.reloadConfig();
ongoineFeeWatcher.uninit();
}
/**
@@ -793,8 +849,7 @@ public class QuickShop extends JavaPlugin {
/**
* Logs the given string to qs.log, if QuickShop is configured to do so.
*
* @param s
* The string to log. It will be prefixed with the date and time.
* @param s The string to log. It will be prefixed with the date and time.
*/
public void log(String s) {
if (this.logWatcher == null)
@@ -810,6 +865,7 @@ public class QuickShop extends JavaPlugin {
public Database getDB() {
return this.database;
}
/**
* Returns the ShopManager. This is used for fetching, adding and removing
* shops.
@@ -819,5 +875,5 @@ public class QuickShop extends JavaPlugin {
public ShopManager getShopManager() {
return this.shopManager;
}
}
@@ -578,6 +578,7 @@ public class ContainerShop implements Shop {
int z = this.getLocation().getBlockZ();
String world = this.getLocation().getWorld().getName();
plugin.getDB().execute("DELETE FROM shops WHERE x = '" + x + "' AND y = '" + y + "' AND z = '" + z + "' AND world = '" + world + "'");
plugin.getDB().execute("DELETE FROM schedule WHERE x = '" + x + "' AND y = '" + y + "' AND z = '" + z + "' AND world = '" + world + "'");
// Refund if necessary
if (plugin.getConfig().getBoolean("shop.refund")) {
plugin.getEcon().deposit(this.getOwner(), plugin.getConfig().getDouble("shop.cost"));
@@ -8,18 +8,22 @@ public class ShopLoadEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private boolean cancelled;
private Shop shop;
/**Getting loading shops**/
/** Getting loading shops **/
public ShopLoadEvent(Shop shop) {
this.shop = shop;
}
public Shop getShop() {
return shop;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
@@ -29,6 +29,7 @@ import org.maxgamer.quickshop.Database.Database;
import org.maxgamer.quickshop.Util.MsgUtil;
import org.maxgamer.quickshop.Util.Permissions;
import org.maxgamer.quickshop.Util.Util;
public class ShopManager {
QuickShop plugin = QuickShop.instance;
private HashMap<UUID, Info> actions = new HashMap<UUID, Info>();
@@ -60,6 +61,9 @@ public class ShopManager {
// Write it to the database
String q = "INSERT INTO shops (owner, price, itemConfig, x, y, z, world, unlimited, type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
plugin.getDB().execute(q, shop.getOwner().toString(), shop.getPrice(), Util.serialize(item), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), loc.getWorld().getName(), (shop.isUnlimited() ? 1 : 0), shop.getShopType().toID());
// Reremake write in schedule data
String scheduleq = "INSERT INTO schedule (owner, world, x, y, z, timestamp) VALUES (?, ?, ?, ?, ?, ?)";
plugin.getDB().execute(scheduleq , shop.getOwner().toString(), loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), System.currentTimeMillis());
// Add it to the world
addShop(loc.getWorld().getName(), shop);
} catch (Exception error) {
@@ -146,21 +150,19 @@ public class ShopManager {
}
/**
* Adds a shop to the world. Does NOT require the chunk or world to be
* loaded
* Adds a shop to the world. Does NOT require the chunk or world to be loaded
*
* @param world
* The name of the world
* @param shop
* The shop to add
* @param world The name of the world
* @param shop The shop to add
*/
private void addShop(String world, Shop shop) {
ShopLoadEvent shopLoadEvent = new ShopLoadEvent(shop);
Bukkit.getPluginManager().callEvent(shopLoadEvent);
if(shopLoadEvent.isCancelled()) {
if (shopLoadEvent.isCancelled()) {
return;
}
HashMap<ShopChunk, HashMap<Location, Shop>> inWorld = this.getShops().get(world);
// There's no world storage yet. We need to create that hashmap.
if (inWorld == null) {
@@ -47,7 +47,12 @@ public class MsgUtil {
messages = YamlConfiguration.loadConfiguration(messageFile);
messages.options().copyDefaults(true);
// Load default messages
YamlConfiguration defMessages = YamlConfiguration.loadConfiguration(new InputStreamReader(plugin.getResource("messages.yml")));
YamlConfiguration defMessages = null;
try {
defMessages = YamlConfiguration.loadConfiguration(new InputStreamReader(plugin.getResource("messages.yml")));
}catch (Exception e) {
}
messages.setDefaults(defMessages);
// Parse colour codes
Util.parseColours(messages);
@@ -41,6 +41,10 @@ import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
/**
* @author MACHENIKE
*
*/
@SuppressWarnings("deprecation")
public class Util {
private static HashSet<Material> tools = new HashSet<Material>();
@@ -594,7 +598,7 @@ public class Util {
public static void sendMessageToOps(String message) {
for (Player player : Bukkit.getOnlinePlayers()) {
if (player.isOp()) {
if (player.isOp() || player.hasPermission("quickshop.alert")) {
player.sendMessage(message);
}
}
@@ -618,6 +622,7 @@ public class Util {
}
}
// Without NMS
public static void sendItemholochatAsNormaly(ItemStack itemStack, Player player, String normalText) {
try {
String Itemname = null;
@@ -705,6 +710,10 @@ public class Util {
}
}
/**
* @param iStack
* @return
*/
public static String getPotiondata(ItemStack iStack) {
if((iStack.getType() != Material.POTION)==true && (iStack.getType() !=Material.LINGERING_POTION)==true && (iStack.getType() !=Material.SPLASH_POTION)==true){
return null;
@@ -733,7 +742,10 @@ public class Util {
return result;
}else {
return null;
}
}
}
public static void sendDeprecatedMethodWarn() {
QuickShop.instance.getLogger().warning("Some plugin calling Deprecated method, Please contact author to use new api!");
}
}
@@ -0,0 +1,148 @@
package org.maxgamer.quickshop.Watcher;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
import org.maxgamer.quickshop.QuickShop;
import org.maxgamer.quickshop.Database.MySQLCore;
import org.maxgamer.quickshop.Economy.Economy;
import org.maxgamer.quickshop.Shop.ContainerShop;
import org.maxgamer.quickshop.Shop.Shop;
import org.maxgamer.quickshop.Util.MsgUtil;
import org.maxgamer.quickshop.Util.Util;
public class OngoineFeeWatcher {
BukkitTask task = null;
int shops_price;
boolean pass_offline_players;
Economy eco = null;
public void init() {
int checkTime = 0;
checkTime = QuickShop.instance.getConfig().getInt("ongoingfee.checkTime");
shops_price = QuickShop.instance.getConfig().getInt("ongoingfee.shops-price");
pass_offline_players = QuickShop.instance.getConfig().getBoolean("ongoingfee.pass-offline-player");
eco = new Economy( QuickShop.instance.getEcon());
task = new BukkitRunnable() {
@Override
public void run() {
if(!QuickShop.instance.getConfig().getBoolean("ongoingfee.enable")) {
return;
}
try {
doit();
} catch (SQLException | InvalidConfigurationException e) {
e.printStackTrace();
}
}
}.runTaskTimerAsynchronously(QuickShop.instance, 80, checkTime);
}
public void uninit() {
if(task!=null) {
task.cancel();
}
try {
if(QuickShop.instance.getConfig().getBoolean("ongoingfee.reset-on-startup")) {
QuickShop.instance.getLogger().info("Cleaning up database schedule table...");
QuickShop.instance.getDB().getConnection().createStatement().execute("delete from schedule");
QuickShop.instance.getLogger().info("Finished database cleanup.");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public void doit() throws SQLException, InvalidConfigurationException {
//Begin!
Statement st = QuickShop.instance.getDB().getConnection().createStatement();
String checkq = "SELECT * FROM schedule";
ResultSet resultSet = st.executeQuery(checkq);
// Stupid SQLite...
if(resultSet.getString(1)!=null) {
withdrawMoney(resultSet.getString(1), resultSet.getString(2), resultSet.getInt(3), resultSet.getInt(4), resultSet.getInt(5), resultSet.getInt(6));
while (resultSet.next()) {
withdrawMoney(resultSet.getString(1), resultSet.getString(2), resultSet.getInt(3), resultSet.getInt(4), resultSet.getInt(5), resultSet.getInt(6));
}
}
//Finish check, reset all shops time...
QuickShop.instance.getLogger().info("Finished Ongoingfee checking.");
}
public void withdrawMoney(String argUUID, String World, int X, int Y, int Z ,int timeStamp) throws SQLException, InvalidConfigurationException {
if(pass_offline_players) {
boolean online = false;
UUID uuid = java.util.UUID.fromString(argUUID);
Collection<? extends Player> onlines = Bukkit.getServer().getOnlinePlayers();
for (Player onlinePlayer : onlines) {
if(onlinePlayer.getUniqueId().equals(uuid)) {
online = true;
break;
}
}
if(!online) {
QuickShop.instance.getDB().getConnection().createStatement()
.executeUpdate("DELETE FROM schedule WHERE x = " + X + " AND y = " + Y + " AND z = " + Z
+ " AND world = \"" + World + "\""
+ (QuickShop.instance.getDB().getCore() instanceof MySQLCore ? " LIMIT 1" : ""));
String scheduleq = "INSERT INTO schedule (owner, world, x, y, z, timestamp) VALUES (?, ?, ?, ?, ?, ?)";
QuickShop.instance.getDB().execute(scheduleq , argUUID, World, X, Y, Z, System.currentTimeMillis());
return;
//Not online and turn on it from config, Return
}
double moneyRemining = eco.getBalance(uuid);
if(moneyRemining<shops_price) {
MsgUtil.send(uuid, MsgUtil.getMessage("no-enough-money-to-keep-shops"));
//Start scanning player's all shops in database
java.sql.Connection con = QuickShop.instance.getDB().getConnection();
PreparedStatement ps = con.prepareStatement("SELECT * FROM shops");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
int x = 0;
int y = 0;
int z = 0;
String worldName = null;
ItemStack item = null;
UUID ownerUUID = null;
String owner;
x = rs.getInt("x");
y = rs.getInt("y");
z = rs.getInt("z");
owner = rs.getString("owner");
worldName = rs.getString("world");
World world = Bukkit.getWorld(worldName);
item = Util.deserialize(rs.getString("itemConfig"));
ownerUUID = java.util.UUID.fromString(owner);
double price = rs.getDouble("price");
Location loc = new Location(world, x, y, z);
item = Util.deserialize(rs.getString("itemConfig"));
Shop shop = new ContainerShop(loc, price, item, ownerUUID);
if(shop.getOwner().equals(uuid)) {
shop.delete();
}
QuickShop.instance.getLogger().info("Removed "+Bukkit.getOfflinePlayer(uuid)+"'s all shops, because no enough money to keep it.");
}
}else {
eco.withdraw(uuid, shops_price);
}
//Finished and reset shops time
QuickShop.instance.getDB().getConnection().createStatement()
.executeUpdate("DELETE FROM schedule WHERE x = " + X + " AND y = " + Y + " AND z = " + Z
+ " AND world = \"" + World + "\""
+ (QuickShop.instance.getDB().getCore() instanceof MySQLCore ? " LIMIT 1" : ""));
if(!(moneyRemining < shops_price)) {
// Reset time
String scheduleq = "INSERT INTO schedule (owner, world, x, y, z, timestamp) VALUES (?, ?, ?, ?, ?, ?)";
QuickShop.instance.getDB().execute(scheduleq , argUUID, World, X, Y, Z, System.currentTimeMillis());
}
}
}
}
@@ -11,41 +11,45 @@ import org.maxgamer.quickshop.Util.Updater;
public class UpdateWatcher implements Listener {
static BukkitTask cronTask = null;
static boolean hasNewUpdate=false;
static boolean hasNewUpdate = false;
public static void init() {
cronTask = new BukkitRunnable() {
@Override
public void run() {
if(!Updater.checkUpdate()) {
hasNewUpdate=false;
if (!Updater.checkUpdate()) {
hasNewUpdate = false;
return;
}
QuickShop.instance.getLogger().info("New QuickShop release now updated on SpigotMC.org!");
QuickShop.instance.getLogger().info("Update plugin in there:https://www.spigotmc.org/resources/59134/");
hasNewUpdate=true;
QuickShop.instance.getLogger().info("New QuickShop release now updated on SpigotMC.org!");
QuickShop.instance.getLogger().info("Update plugin in there: https://www.spigotmc.org/resources/59134/");
hasNewUpdate = true;
}
}.runTaskTimerAsynchronously(QuickShop.instance, 1, 20*60*10);
}.runTaskTimerAsynchronously(QuickShop.instance, 1, 20 * 60 * 10);
}
public static void uninit() {
hasNewUpdate=false;
if(cronTask==null) {
hasNewUpdate = false;
if (cronTask == null) {
return;
}
cronTask.cancel();
}
@EventHandler
public void PlayerJoin(PlayerJoinEvent e) {
new BukkitRunnable() {
@Override
public void run() {
if(e.getPlayer().hasPermission("quickshop.alert") && hasNewUpdate) {
e.getPlayer().sendMessage(ChatColor.GREEN+"New QuickShop release now updated on SpigotMC.org!");
e.getPlayer().sendMessage(ChatColor.GREEN+"Update plugin in there:https://www.spigotmc.org/resources/59134/");
if (e.getPlayer().hasPermission("quickshop.alert") && hasNewUpdate) {
e.getPlayer().sendMessage(ChatColor.GREEN + "New QuickShop release now updated on SpigotMC.org!");
e.getPlayer().sendMessage(
ChatColor.GREEN + "Update plugin in there: https://www.spigotmc.org/resources/59134/");
}
}
}.runTaskLaterAsynchronously(QuickShop.instance, 80);
}
}