Code sort

Former-commit-id: 9cfc97eb7f247f12e688776d879be05a83bc188e [formerly 60194df8646944c7e1a4d05358abdbcfbf3d8f74]
Former-commit-id: 15842b30f5298431b75778c6cd75d822e1192f9e
This commit is contained in:
Ghost_chu committed 2019-07-16 22:19:01 +08:00
1 parent d462f772de
commit 88dc80f02d
62 files changed
+4817 -4792

No files matched your search

@@ -21,10 +21,6 @@ public class BootError {
}
}
public String[] getErrors() {
return errors;
}
/**
* Print the errors.
* #####################################################
@@ -46,4 +42,8 @@ public class BootError {
}
public String[] getErrors() {
return errors;
}
}
@@ -8,6 +8,16 @@ import org.bukkit.ChatColor;
*/
class BuiltInSolution {
private static QuickShop plugin = QuickShop.instance;
/**
* Call when failed load database, and use this to check the reason.
*
* @return The reason of error.
*/
static BootError databaseError() {
return new BootError("Error connecting to the database", "Make sure your database service is running.", "Or check the configuration in your config.yml");
}
/**
* Call when failed load economy system, and use this to check the reason.
*
@@ -31,13 +41,4 @@ class BuiltInSolution {
return new BootError("No Economy plugin detected, did you installed and loaded them? Make sure they loaded before QuickShop.", "Install an economy plugin to get Vault or Reserve working.");
}
/**
* Call when failed load database, and use this to check the reason.
*
* @return The reason of error.
*/
static BootError databaseError() {
return new BootError("Error connecting to the database", "Make sure your database service is running.", "Or check the configuration in your config.yml");
}
}
@@ -7,8 +7,8 @@ import lombok.*;
@Data
@Builder
public class CommandContainer {
private String prefix; // E.g /qs <prefix>
@Singular private List<String> permissions; // E.g quickshop.unlimited
private boolean hidden; // Hide from help, tabcomplete
private CommandProcesser executor;
private boolean hidden; // Hide from help, tabcomplete
@Singular private List<String> permissions; // E.g quickshop.unlimited
private String prefix; // E.g /qs <prefix>
}
@@ -87,50 +87,6 @@ public class CommandManager implements TabCompleter, CommandExecutor {
.build());
}
private void registerCmd(CommandContainer container) {
if (!cmds.contains(container))
cmds.add(container);
}
@Override
public @Nullable List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String commandLabel, @NotNull String[] cmdArg) {
//No args, it shouldn't happend
if (sender instanceof Player) {
if (QuickShop.instance.getConfig().getBoolean("effect.sound.ontabcomplete")) {
Player player = (Player) sender;
((Player) sender).playSound(player.getLocation(), Sound.BLOCK_DISPENSER_FAIL, 80.0F, 1.0F);
}
}
if (cmdArg.length == 0 || cmdArg.length == 1) {
//No args
return getRootContainer().getExecutor().onTabComplete(sender, commandLabel, cmdArg);
}
//Main args/more args
String[] passthroughArgs;
passthroughArgs = new String[cmdArg.length - 1];
System.arraycopy(cmdArg, 1, passthroughArgs, 0, passthroughArgs.length);
for (CommandContainer container : cmds) {
Util.debugLog("Checking prefix with container: " + container.getPrefix() + " - " + cmdArg[0]);
if (!container.getPrefix().toLowerCase().startsWith(cmdArg[0]))
continue;
Util.debugLog("Checking permission with container: " + container.getPrefix() + " - " + cmdArg[0]);
List<String> requirePermissions = container.getPermissions();
if (container.getPermissions() != null)
for (String requirePermission : requirePermissions) {
if (requirePermission != null && !requirePermission.isEmpty() && !sender.hasPermission(requirePermission)) {
Util.debugLog("Sender " + sender
.getName() + " trying tab-complete the command: " + commandLabel + " " + Util
.array2String(cmdArg) + ", but no permission " + requirePermission);
return null;
}
}
Util.debugLog("Execute container: " + container.getPrefix());
return container.getExecutor().onTabComplete(sender, commandLabel, passthroughArgs);
}
return null;
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String commandLabel, @NotNull String[] cmdArg) {
if (QuickShop.instance.getBootError() != null) {
@@ -181,4 +137,48 @@ public class CommandManager implements TabCompleter, CommandExecutor {
rootContainer.getExecutor().onCommand(sender, commandLabel, passthroughArgs);
return true;
}
@Override
public @Nullable List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String commandLabel, @NotNull String[] cmdArg) {
//No args, it shouldn't happend
if (sender instanceof Player) {
if (QuickShop.instance.getConfig().getBoolean("effect.sound.ontabcomplete")) {
Player player = (Player) sender;
((Player) sender).playSound(player.getLocation(), Sound.BLOCK_DISPENSER_FAIL, 80.0F, 1.0F);
}
}
if (cmdArg.length == 0 || cmdArg.length == 1) {
//No args
return getRootContainer().getExecutor().onTabComplete(sender, commandLabel, cmdArg);
}
//Main args/more args
String[] passthroughArgs;
passthroughArgs = new String[cmdArg.length - 1];
System.arraycopy(cmdArg, 1, passthroughArgs, 0, passthroughArgs.length);
for (CommandContainer container : cmds) {
Util.debugLog("Checking prefix with container: " + container.getPrefix() + " - " + cmdArg[0]);
if (!container.getPrefix().toLowerCase().startsWith(cmdArg[0]))
continue;
Util.debugLog("Checking permission with container: " + container.getPrefix() + " - " + cmdArg[0]);
List<String> requirePermissions = container.getPermissions();
if (container.getPermissions() != null)
for (String requirePermission : requirePermissions) {
if (requirePermission != null && !requirePermission.isEmpty() && !sender.hasPermission(requirePermission)) {
Util.debugLog("Sender " + sender
.getName() + " trying tab-complete the command: " + commandLabel + " " + Util
.array2String(cmdArg) + ", but no permission " + requirePermission);
return null;
}
}
Util.debugLog("Execute container: " + container.getPrefix());
return container.getExecutor().onTabComplete(sender, commandLabel, passthroughArgs);
}
return null;
}
private void registerCmd(CommandContainer container) {
if (!cmds.contains(container))
cmds.add(container);
}
}
@@ -6,6 +6,23 @@ import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.*;
public interface CommandProcesser {
/**
* Accept the onCommand, it will call when have Command Event
* cmdArg not contains CommandContainer's prefix.
* E.g:
* Register the CommandContainer with
* Prefix: unlimited
* Permission: quickshop.unlimited
* <p>
* When player type /qs unlimited 123
* cmdArg's content is 123
*
* @param sender Sender
* @param cmdArg Args
* @param commandLabel The command prefix /qs is qs
*/
void onCommand(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] cmdArg);
/**
* Accept the onTabComplete, it will call when have Tab Event
* cmdArg not contains CommandContainer's prefix.
@@ -23,21 +40,4 @@ public interface CommandProcesser {
* @return The result for tab-complete lists
*/
@Nullable List<String> onTabComplete(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] cmdArg);
/**
* Accept the onCommand, it will call when have Command Event
* cmdArg not contains CommandContainer's prefix.
* E.g:
* Register the CommandContainer with
* Prefix: unlimited
* Permission: quickshop.unlimited
* <p>
* When player type /qs unlimited 123
* cmdArg's content is 123
*
* @param sender Sender
* @param cmdArg Args
* @param commandLabel The command prefix /qs is qs
*/
void onCommand(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] cmdArg);
}
@@ -10,8 +10,8 @@ import org.maxgamer.quickshop.Util.Util;
public class BufferStatement {
private Object[] values;
private String query;
private Object[] values;
/**
* Represents a PreparedStatement in a state before preparing it (E.g. No
@@ -40,57 +40,6 @@ public class Database {
this.core = core;
}
/**
* Returns the database core object, that this database runs on.
*
* @return the database core object, that this database runs on.
*/
public DatabaseCore getCore() {
return core;
}
/**
* Fetches the connection to this database for querying. Try to avoid doing
* this in the main thread.
*
* @return Fetches the connection to this database for querying.
*/
public Connection getConnection() {
return core.getConnection();
}
/**
* Executes the given statement either immediately, or soon.
*
* @param query The query
* @param objs The string values for each ? in the given query.
*/
public void execute(@NotNull String query, @NotNull Object... objs) {
Util.debugLog(query);
BufferStatement bs = new BufferStatement(query, objs);
core.queue(bs);
}
/**
* Returns true if the table exists
*
* @param table The table to check for
* @return True if the table is found
* @throws SQLException Throw exception when failed execute somethins on SQL
*/
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
boolean hasTable(@NotNull String table) throws SQLException {
ResultSet rs = getConnection().getMetaData().getTables(null, null, "%", null);
while (rs.next()) {
if (table.equalsIgnoreCase(rs.getString("TABLE_NAME"))) {
rs.close();
return true;
}
}
rs.close();
return false;
}
/**
* Closes the database
*/
@@ -98,43 +47,6 @@ public class Database {
this.core.close();
}
/**
* Returns true if the given table has the given column
*
* @param table The table
* @param column The column
* @return True if the given table has the given column
* @throws SQLException If the database isn't connected
*/
public boolean hasColumn(@NotNull String table, @NotNull String column) throws SQLException {
if (!hasTable(table))
return false;
String query = "SELECT * FROM " + table + " LIMIT 0,1";
try {
PreparedStatement ps = this.getConnection().prepareStatement(query);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
if (rs.getString(column) != null)
return true;
}
} catch (SQLException e) {
return false;
}
return false; // Uh, wtf.
}
/**
* Represents a connection error, generally when the server can't connect to
* MySQL or something.
*/
public static class ConnectionException extends Exception {
private static final long serialVersionUID = 8348749992936357317L;
private ConnectionException(String msg) {
super(msg);
}
}
/**
* Copies the contents of this database into the given database. Does not
* delete the contents of this database, or change any settings. This may
@@ -206,4 +118,92 @@ public class Database {
db.getConnection().close();
this.getConnection().close();
}
/**
* Executes the given statement either immediately, or soon.
*
* @param query The query
* @param objs The string values for each ? in the given query.
*/
public void execute(@NotNull String query, @NotNull Object... objs) {
Util.debugLog(query);
BufferStatement bs = new BufferStatement(query, objs);
core.queue(bs);
}
/**
* Returns true if the given table has the given column
*
* @param table The table
* @param column The column
* @return True if the given table has the given column
* @throws SQLException If the database isn't connected
*/
public boolean hasColumn(@NotNull String table, @NotNull String column) throws SQLException {
if (!hasTable(table))
return false;
String query = "SELECT * FROM " + table + " LIMIT 0,1";
try {
PreparedStatement ps = this.getConnection().prepareStatement(query);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
if (rs.getString(column) != null)
return true;
}
} catch (SQLException e) {
return false;
}
return false; // Uh, wtf.
}
/**
* Returns true if the table exists
*
* @param table The table to check for
* @return True if the table is found
* @throws SQLException Throw exception when failed execute somethins on SQL
*/
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
boolean hasTable(@NotNull String table) throws SQLException {
ResultSet rs = getConnection().getMetaData().getTables(null, null, "%", null);
while (rs.next()) {
if (table.equalsIgnoreCase(rs.getString("TABLE_NAME"))) {
rs.close();
return true;
}
}
rs.close();
return false;
}
/**
* Fetches the connection to this database for querying. Try to avoid doing
* this in the main thread.
*
* @return Fetches the connection to this database for querying.
*/
public Connection getConnection() {
return core.getConnection();
}
/**
* Returns the database core object, that this database runs on.
*
* @return the database core object, that this database runs on.
*/
public DatabaseCore getCore() {
return core;
}
/**
* Represents a connection error, generally when the server can't connect to
* MySQL or something.
*/
public static class ConnectionException extends Exception {
private static final long serialVersionUID = 8348749992936357317L;
private ConnectionException(String msg) {
super(msg);
}
}
}
@@ -3,11 +3,11 @@ package org.maxgamer.quickshop.Database;
import java.sql.Connection;
public interface DatabaseCore {
Connection getConnection();
void queue(BufferStatement bs);
void close();
void flush();
void close();
void queue(BufferStatement bs);
Connection getConnection();
}
@@ -60,17 +60,29 @@ public class DatabaseHelper {
}
}
/**
* Creates the database table 'shops'.
*
* @param db The database you want create at.
* @throws SQLException If the connection is invalid.
*/
private void createShopsTable(@NotNull Database db) throws SQLException {
Statement st = db.getConnection().createStatement();
String createTable = "CREATE TABLE " + QuickShop.instance
.getDbPrefix() + "shops (owner VARCHAR(255) 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) );";
st.execute(createTable);
public void cleanMessage(@NotNull Database db, long weekAgo) {
try {
//QuickShop.instance.getDB().execute("DELETE FROM " + QuickShop.instance
// .getDbPrefix() + "messages WHERE time < ?", weekAgo);
String sqlString = "DELETE FROM " + QuickShop.instance
.getDbPrefix() + "messages WHERE time < ?";
PreparedStatement ps = db.getConnection().prepareStatement(sqlString);
ps.setLong(1, weekAgo);
plugin.getDatabaseManager().add(ps);
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
public void cleanMessageForPlayer(@NotNull Database db, @NotNull UUID player) {
try {
String sqlString = "DELETE FROM " + QuickShop.instance.getDbPrefix() + "messages WHERE owner = ?";
PreparedStatement ps = db.getConnection().prepareStatement(sqlString);
ps.setString(1, player.toString());
plugin.getDatabaseManager().add(ps);
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
/**
@@ -87,16 +99,35 @@ public class DatabaseHelper {
return st.execute(createTable);
}
public ResultSet selectAllShops(Database db) throws SQLException {
Statement st = db.getConnection().createStatement();
String selectAllShops = "SELECT * FROM " + QuickShop.instance.getDbPrefix() + "shops";
return st.executeQuery(selectAllShops);
public void createShop(@NotNull Database db, @NotNull String owner, double price, @NotNull ItemStack item, int unlimited, int shopType, @NotNull String world, int x, int y, int z)
throws SQLException {
String sqlString = "INSERT INTO " + QuickShop.instance
.getDbPrefix() + "shops (owner, price, itemConfig, x, y, z, world, unlimited, type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
//QuickShop.instance.getDB().execute(q, owner, price, Util.serialize(item), x, y, z, world, unlimited, shopType);
PreparedStatement ps = db.getConnection().prepareStatement(sqlString);
ps.setString(1, owner);
ps.setDouble(2, price);
ps.setString(3, Util.serialize(item));
ps.setInt(4, x);
ps.setInt(5, y);
ps.setInt(6, z);
ps.setString(7, world);
ps.setInt(8, unlimited);
ps.setInt(9, shopType);
plugin.getDatabaseManager().add(ps);
}
public ResultSet selectAllMessages(Database db) throws SQLException {
/**
* Creates the database table 'shops'.
*
* @param db The database you want create at.
* @throws SQLException If the connection is invalid.
*/
private void createShopsTable(@NotNull Database db) throws SQLException {
Statement st = db.getConnection().createStatement();
String selectAllShops = "SELECT * FROM " + QuickShop.instance.getDbPrefix() + "messages";
return st.executeQuery(selectAllShops);
String createTable = "CREATE TABLE " + QuickShop.instance
.getDbPrefix() + "shops (owner VARCHAR(255) 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) );";
st.execute(createTable);
}
public boolean removeShop(@NotNull Database db, int x, int y, int z, @NotNull String worldName) throws SQLException {
@@ -117,6 +148,33 @@ public class DatabaseHelper {
return ps.execute();
}
public ResultSet selectAllMessages(Database db) throws SQLException {
Statement st = db.getConnection().createStatement();
String selectAllShops = "SELECT * FROM " + QuickShop.instance.getDbPrefix() + "messages";
return st.executeQuery(selectAllShops);
}
public ResultSet selectAllShops(Database db) throws SQLException {
Statement st = db.getConnection().createStatement();
String selectAllShops = "SELECT * FROM " + QuickShop.instance.getDbPrefix() + "shops";
return st.executeQuery(selectAllShops);
}
public void sendMessage(@NotNull Database db, @NotNull UUID player, @NotNull String message, long time) {
try {
String sqlString = "INSERT INTO " + QuickShop.instance
.getDbPrefix() + "messages (owner, message, time) VALUES (?, ?, ?)";
//QuickShop.instance.getDB().execute(q, player.toString(), message, System.currentTimeMillis());
PreparedStatement ps = db.getConnection().prepareStatement(sqlString);
ps.setString(1, player.toString());
ps.setString(2, message);
ps.setLong(3, time);
plugin.getDatabaseManager().add(ps);
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
public void updateOwner2UUID(@NotNull Database db, @NotNull String ownerUUID, int x, int y, int z, @NotNull String worldName)
throws SQLException {
//QuickShop.instance.getDB().getConnection().createStatement()
@@ -157,62 +215,4 @@ public class DatabaseHelper {
}
}
public void createShop(@NotNull Database db, @NotNull String owner, double price, @NotNull ItemStack item, int unlimited, int shopType, @NotNull String world, int x, int y, int z)
throws SQLException {
String sqlString = "INSERT INTO " + QuickShop.instance
.getDbPrefix() + "shops (owner, price, itemConfig, x, y, z, world, unlimited, type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
//QuickShop.instance.getDB().execute(q, owner, price, Util.serialize(item), x, y, z, world, unlimited, shopType);
PreparedStatement ps = db.getConnection().prepareStatement(sqlString);
ps.setString(1, owner);
ps.setDouble(2, price);
ps.setString(3, Util.serialize(item));
ps.setInt(4, x);
ps.setInt(5, y);
ps.setInt(6, z);
ps.setString(7, world);
ps.setInt(8, unlimited);
ps.setInt(9, shopType);
plugin.getDatabaseManager().add(ps);
}
public void sendMessage(@NotNull Database db, @NotNull UUID player, @NotNull String message, long time) {
try {
String sqlString = "INSERT INTO " + QuickShop.instance
.getDbPrefix() + "messages (owner, message, time) VALUES (?, ?, ?)";
//QuickShop.instance.getDB().execute(q, player.toString(), message, System.currentTimeMillis());
PreparedStatement ps = db.getConnection().prepareStatement(sqlString);
ps.setString(1, player.toString());
ps.setString(2, message);
ps.setLong(3, time);
plugin.getDatabaseManager().add(ps);
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
public void cleanMessage(@NotNull Database db, long weekAgo) {
try {
//QuickShop.instance.getDB().execute("DELETE FROM " + QuickShop.instance
// .getDbPrefix() + "messages WHERE time < ?", weekAgo);
String sqlString = "DELETE FROM " + QuickShop.instance
.getDbPrefix() + "messages WHERE time < ?";
PreparedStatement ps = db.getConnection().prepareStatement(sqlString);
ps.setLong(1, weekAgo);
plugin.getDatabaseManager().add(ps);
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
public void cleanMessageForPlayer(@NotNull Database db, @NotNull UUID player) {
try {
String sqlString = "DELETE FROM " + QuickShop.instance.getDbPrefix() + "messages WHERE owner = ?";
PreparedStatement ps = db.getConnection().prepareStatement(sqlString);
ps.setString(1, player.toString());
plugin.getDatabaseManager().add(ps);
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
}
@@ -18,11 +18,11 @@ import org.maxgamer.quickshop.Util.WarningSender;
* Use queue to solve run SQL make server lagg issue.
*/
public class DatabaseManager {
private QuickShop plugin;
private Database database;
private boolean useQueue;
private QuickShop plugin;
private Queue<PreparedStatement> sqlQueue = new LinkedBlockingQueue<>();
private BukkitTask task;
private boolean useQueue;
private WarningSender warningSender;
/**
@@ -48,13 +48,19 @@ public class DatabaseManager {
}
/**
* Unload the DatabaseManager, run at onDisable()
* Add preparedStatement to queue waiting flush to database,
* @param ps The ps you want add in queue.
*/
public void uninit() {
if (task != null && !task.isCancelled())
task.cancel();
plugin.getLogger().info("Please wait for the data to flush its data...");
runTask();
public void add(@NotNull PreparedStatement ps) {
if (useQueue) {
sqlQueue.offer(ps);
} else {
try {
ps.execute();
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
}
/**
@@ -98,18 +104,12 @@ public class DatabaseManager {
}
/**
* Add preparedStatement to queue waiting flush to database,
* @param ps The ps you want add in queue.
* Unload the DatabaseManager, run at onDisable()
*/
public void add(@NotNull PreparedStatement ps) {
if (useQueue) {
sqlQueue.offer(ps);
} else {
try {
ps.execute();
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
public void uninit() {
if (task != null && !task.isCancelled())
task.cancel();
plugin.getLogger().info("Please wait for the data to flush its data...");
runTask();
}
}
@@ -10,11 +10,11 @@ import java.util.Properties;
import org.jetbrains.annotations.*;
public class MySQLCore implements DatabaseCore {
private String url;
/** The connection properties... user, pass, autoReconnect.. */
private Properties info;
private static final int MAX_CONNECTIONS = 8;
private static ArrayList<Connection> pool = new ArrayList<>();
/** The connection properties... user, pass, autoReconnect.. */
private Properties info;
private String url;
public MySQLCore(@NotNull String host, @NotNull String user, @NotNull String pass, @NotNull String database, @NotNull String port, boolean useSSL) {
info = new Properties();
@@ -29,6 +29,37 @@ public class MySQLCore implements DatabaseCore {
pool.add(null);
}
@Override
public void close() {
// Nothing, because queries are executed immediately for MySQL
}
@Override
public void flush() {
// Nothing, because queries are executed immediately for MySQL
}
@Override
public void queue(@NotNull BufferStatement bs) {
try {
Connection con = this.getConnection();
while (con == null) {
try {
Thread.sleep(15);
} catch (InterruptedException e) {
//ignore
}
// Try again
con = this.getConnection();
}
PreparedStatement ps = bs.prepareStatement(con);
ps.execute();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Gets the database connection for executing queries on.
*
@@ -54,35 +85,4 @@ public class MySQLCore implements DatabaseCore {
}
return null;
}
@Override
public void queue(@NotNull BufferStatement bs) {
try {
Connection con = this.getConnection();
while (con == null) {
try {
Thread.sleep(15);
} catch (InterruptedException e) {
//ignore
}
// Try again
con = this.getConnection();
}
PreparedStatement ps = bs.prepareStatement(con);
ps.execute();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void close() {
// Nothing, because queries are executed immediately for MySQL
}
@Override
public void flush() {
// Nothing, because queries are executed immediately for MySQL
}
}
@@ -11,15 +11,50 @@ import java.util.LinkedList;
import org.jetbrains.annotations.*;
public class SQLiteCore implements DatabaseCore {
private Connection connection;
private final File dbFile;
private volatile Thread watcher;
private final LinkedList<BufferStatement> queue = new LinkedList<>();
private Connection connection;
private volatile Thread watcher;
public SQLiteCore(@NotNull File dbFile) {
this.dbFile = dbFile;
}
@Override
public void close() {
flush();
}
@Override
public void flush() {
while (!queue.isEmpty()) {
BufferStatement bs;
synchronized (queue) {
bs = queue.removeFirst();
}
synchronized (dbFile) {
try {
PreparedStatement ps = bs.prepareStatement(getConnection());
ps.execute();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
@Override
public void queue(@NotNull BufferStatement bs) {
synchronized (queue) {
queue.add(bs);
}
if (watcher == null || !watcher.isAlive()) {
startWatcher();
}
}
/**
* Gets the database connection for executing queries on.
*
@@ -59,41 +94,6 @@ public class SQLiteCore implements DatabaseCore {
}
}
@Override
public void queue(@NotNull BufferStatement bs) {
synchronized (queue) {
queue.add(bs);
}
if (watcher == null || !watcher.isAlive()) {
startWatcher();
}
}
@Override
public void flush() {
while (!queue.isEmpty()) {
BufferStatement bs;
synchronized (queue) {
bs = queue.removeFirst();
}
synchronized (dbFile) {
try {
PreparedStatement ps = bs.prepareStatement(getConnection());
ps.execute();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
@Override
public void close() {
flush();
}
private void startWatcher() {
watcher = new Thread(() -> {
try {
@@ -1,69 +1,69 @@
package org.maxgamer.quickshop.Economy;
import java.util.UUID;
import lombok.*;
import org.jetbrains.annotations.*;
import org.maxgamer.quickshop.QuickShop;
import org.maxgamer.quickshop.Util.Util;
public class Economy implements EconomyCore {
@Getter
@Setter
private EconomyCore core;
private QuickShop plugin = QuickShop.instance;
public Economy(EconomyCore core) {
this.core = core;
}
/**
* Checks that this economy is valid. Returns false if it is not valid.
*
* @return True if this economy will work, false if it will not.
*/
public boolean isValid() {
return core.isValid();
}
/**
* Formats the given number... E.g. 50.5 becomes $50.5 Dollars, or 50
* Dollars 5 Cents
*
* @param balance The given number
* @return The balance in human readable text.
*/
public String format(double balance) {
return Util.parseColours(core.format(balance));
//Fix color issue from some stupid economy plugin....
}
@Override
public String toString() {
return core.getClass().getName().split("_")[1];
}
@Override
public boolean deposit(@NotNull UUID name, double amount) {
return core.deposit(name, amount);
}
@Override
public boolean withdraw(@NotNull UUID name, double amount) {
return core.withdraw(name, amount);
}
@Override
public boolean transfer(@NotNull UUID from, UUID to, double amount) {
return core.transfer(from, to, amount);
}
@Override
public double getBalance(@NotNull UUID name) {
return core.getBalance(name);
}
public EconomyType getNowUsing() {
return EconomyType.fromID(plugin.getConfig().getInt("economy-type"));
}
package org.maxgamer.quickshop.Economy;
import java.util.UUID;
import lombok.*;
import org.jetbrains.annotations.*;
import org.maxgamer.quickshop.QuickShop;
import org.maxgamer.quickshop.Util.Util;
public class Economy implements EconomyCore {
@Getter
@Setter
private EconomyCore core;
private QuickShop plugin = QuickShop.instance;
public Economy(EconomyCore core) {
this.core = core;
}
@Override
public String toString() {
return core.getClass().getName().split("_")[1];
}
public EconomyType getNowUsing() {
return EconomyType.fromID(plugin.getConfig().getInt("economy-type"));
}
/**
* Checks that this economy is valid. Returns false if it is not valid.
*
* @return True if this economy will work, false if it will not.
*/
public boolean isValid() {
return core.isValid();
}
/**
* Formats the given number... E.g. 50.5 becomes $50.5 Dollars, or 50
* Dollars 5 Cents
*
* @param balance The given number
* @return The balance in human readable text.
*/
public String format(double balance) {
return Util.parseColours(core.format(balance));
//Fix color issue from some stupid economy plugin....
}
@Override
public boolean deposit(@NotNull UUID name, double amount) {
return core.deposit(name, amount);
}
@Override
public boolean withdraw(@NotNull UUID name, double amount) {
return core.withdraw(name, amount);
}
@Override
public boolean transfer(@NotNull UUID from, UUID to, double amount) {
return core.transfer(from, to, amount);
}
@Override
public double getBalance(@NotNull UUID name) {
return core.getBalance(name);
}
}
@@ -7,11 +7,13 @@ import java.util.UUID;
*/
public interface EconomyCore {
/**
* Checks that this economy is valid. Returns false if it is not valid.
* Deposits a given amount of money from thin air to the given username.
*
* @return True if this economy will work, false if it will not.
* @param name The exact (case insensitive) username to give money to
* @param amount The amount to give them
* @return True if success (Should be almost always)
*/
boolean isValid();
boolean deposit(UUID name, double amount);
/**
* Formats the given number... E.g. 50.5 becomes $50.5 Dollars, or 50
@@ -23,23 +25,12 @@ public interface EconomyCore {
String format(double balance);
/**
* Deposits a given amount of money from thin air to the given username.
* Fetches the balance of the given account name
*
* @param name The exact (case insensitive) username to give money to
* @param amount The amount to give them
* @return True if success (Should be almost always)
* @param name The name of the account
* @return Their current balance.
*/
boolean deposit(UUID name, double amount);
/**
* Withdraws a given amount of money from the given username and turns it to
* thin air.
*
* @param name The exact (case insensitive) username to take money from
* @param amount The amount to take from them
* @return True if success, false if they didn't have enough cash
*/
boolean withdraw(UUID name, double amount);
double getBalance(UUID name);
/**
* Transfers the given amount of money from Player1 to Player2
@@ -53,11 +44,20 @@ public interface EconomyCore {
boolean transfer(UUID from, UUID to, double amount);
/**
* Fetches the balance of the given account name
* Withdraws a given amount of money from the given username and turns it to
* thin air.
*
* @param name The name of the account
* @return Their current balance.
* @param name The exact (case insensitive) username to take money from
* @param amount The amount to take from them
* @return True if success, false if they didn't have enough cash
*/
double getBalance(UUID name);
boolean withdraw(UUID name, double amount);
/**
* Checks that this economy is valid. Returns false if it is not valid.
*
* @return True if this economy will work, false if it will not.
*/
boolean isValid();
}
@@ -4,12 +4,6 @@ import org.jetbrains.annotations.*;
public enum EconomyType {
UNKNOWN(-1), VAULT(0), RESERVE(1);
private int id;
EconomyType(int id) {
this.id = id;
}
public static EconomyType fromID(int id) {
for (EconomyType type : EconomyType.values()) {
if (type.id == id) {
@@ -23,6 +17,12 @@ public enum EconomyType {
return economyType.id;
}
private int id;
EconomyType(int id) {
this.id = id;
}
public int toID() {
return id;
}
@@ -13,16 +13,24 @@ import org.maxgamer.quickshop.QuickShop;
* @author creatorfromhell
*/
public class Economy_Reserve implements EconomyCore {
final private String errorMsg = "QuickShop got an error when calling your Economy system, this is NOT a QuickShop error, please do not report this issue to the QuickShop's Issue tracker, ask your Economy plugin's author.";
private QuickShop plugin = QuickShop.instance;
@Getter
@Setter
private EconomyAPI reserve = null;
private QuickShop plugin = QuickShop.instance;
final private String errorMsg = "QuickShop got an error when calling your Economy system, this is NOT a QuickShop error, please do not report this issue to the QuickShop's Issue tracker, ask your Economy plugin's author.";
public Economy_Reserve() {
setup();
}
private String formatInternal(double balance) {
try {
return String.valueOf(QuickShop.instance.getConfig().getString("shop.alternate-currency-symbol") + balance);
} catch (Exception e) {
return String.valueOf('$' + balance);
}
}
@SuppressWarnings("ConstantConditions")
private void setup() {
try {
@@ -62,14 +70,6 @@ public class Economy_Reserve implements EconomyCore {
}
}
private String formatInternal(double balance) {
try {
return String.valueOf(QuickShop.instance.getConfig().getString("shop.alternate-currency-symbol") + balance);
} catch (Exception e) {
return String.valueOf('$' + balance);
}
}
/**
* Deposits a given amount of money from thin air to the given username.
*
@@ -16,15 +16,49 @@ import org.maxgamer.quickshop.QuickShop;
import org.maxgamer.quickshop.Util.Util;
public class Economy_Vault implements EconomyCore, Listener {
private QuickShop plugin = QuickShop.instance;
@Getter
@Setter
private Economy vault;
private QuickShop plugin = QuickShop.instance;
public Economy_Vault() {
setupEconomy();
}
public boolean checkValid() {
if (this.vault == null) {
Bukkit.getPluginManager().disablePlugin(plugin);
plugin.getLogger().severe("FATAL: Economy system not ready.");
return false;
} else {
return true;
}
}
private String formatInternal(double balance) {
if (!checkValid())
return "Error";
try {
return QuickShop.instance.getConfig().getString("shop.alternate-currency-symbol") + balance;
} catch (Exception e) {
return String.valueOf('$' + balance);
}
}
@EventHandler
public void onServiceRegister(ServiceRegisterEvent event) {
if (!(event.getProvider() instanceof Economy))
return;
setupEconomy();
}
@EventHandler
public void onServiceRegister(ServiceUnregisterEvent event) {
if (!(event.getProvider() instanceof Economy))
return;
setupEconomy();
}
private boolean setupEconomy() {
RegisteredServiceProvider<Economy> economyProvider;
try {
@@ -58,35 +92,11 @@ public class Economy_Vault implements EconomyCore, Listener {
return String.valueOf(this.vault.getName());
}
@EventHandler
public void onServiceRegister(ServiceRegisterEvent event) {
if (!(event.getProvider() instanceof Economy))
return;
setupEconomy();
}
@EventHandler
public void onServiceRegister(ServiceUnregisterEvent event) {
if (!(event.getProvider() instanceof Economy))
return;
setupEconomy();
}
@Override
public boolean isValid() {
return this.vault != null;
}
public boolean checkValid() {
if (this.vault == null) {
Bukkit.getPluginManager().disablePlugin(plugin);
plugin.getLogger().severe("FATAL: Economy system not ready.");
return false;
} else {
return true;
}
}
@Override
public String format(double balance) {
if (!checkValid())
@@ -102,16 +112,6 @@ public class Economy_Vault implements EconomyCore, Listener {
}
private String formatInternal(double balance) {
if (!checkValid())
return "Error";
try {
return QuickShop.instance.getConfig().getString("shop.alternate-currency-symbol") + balance;
} catch (Exception e) {
return String.valueOf('$' + balance);
}
}
@Override
public boolean deposit(@NotNull UUID name, double amount) {
if (!checkValid())
@@ -10,13 +10,13 @@ import org.maxgamer.quickshop.Shop.Shop;
public class ShopCreateEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
@Getter
@NotNull
private Shop shop;
private boolean cancelled;
@Getter
@NotNull
private Player player;
@Getter
@NotNull
private Shop shop;
/**
* Call when have a new shop was createing.
@@ -9,11 +9,11 @@ import org.maxgamer.quickshop.Shop.Shop;
public class ShopDeleteEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private boolean cancelled;
@Getter private boolean fromMemory;
@Getter
@NotNull
private Shop shop;
private boolean cancelled;
@Getter private boolean fromMemory;
/**
* Call the event when shop is deleteing.
@@ -19,13 +19,13 @@ public class ShopDisplayItemSpawnEvent extends Event implements Cancellable {
private boolean cancelled;
@Getter
@NotNull
private Shop shop;
private DisplayType displayType;
@Getter
@NotNull
private ItemStack itemStack;
@Getter
@NotNull
private DisplayType displayType;
private Shop shop;
/**
* This event is called before the shop display item created
@@ -14,10 +14,10 @@ public class ShopInventoryPreviewEvent extends Event implements Cancellable {
private boolean cancelled;
@Getter
@NotNull
private Player player;
private ItemStack itemStack;
@Getter
@NotNull
private ItemStack itemStack;
private Player player;
/**
* Build a event when player using GUI preview
@@ -26,6 +26,9 @@ public class ShopLoadEvent extends Event implements Cancellable {
this.shop = shop;
}
public static HandlerList getHandlerList() {
return handlers;
}
@NotNull
@Override
@@ -33,10 +36,6 @@ public class ShopLoadEvent extends Event implements Cancellable {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
@Override
public boolean isCancelled() {
return this.cancelled;
@@ -13,10 +13,10 @@ public class ShopModeratorChangedEvent extends Event {
private static final HandlerList handlers = new HandlerList();
@Getter
@NotNull
private Shop shop;
private ShopModerator moderator;
@Getter
@NotNull
private ShopModerator moderator;
private Shop shop;
/**
* Will call when shop price was changed.
@@ -19,10 +19,10 @@ public class ShopPreCreateEvent extends Event implements Cancellable {
private boolean cancelled;
@Getter
@NotNull
private Player player;
private Location location;
@Getter
@NotNull
private Location location;
private Player player;
/**
* Calling when shop pre-creating.
@@ -10,11 +10,11 @@ import org.maxgamer.quickshop.Shop.Shop;
public class ShopPriceChangedEvent extends Event {
private static final HandlerList handlers = new HandlerList();
@Getter private double newPrice;
@Getter private double oldPrice;
@Getter
@NotNull
private Shop shop;
@Getter private double oldPrice;
@Getter private double newPrice;
/**
* Will call when shop price was changed.
@@ -10,16 +10,16 @@ import org.maxgamer.quickshop.Shop.Shop;
public class ShopSuccessPurchaseEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
@Getter
@NotNull
private Shop shop;
@Getter private int amount;
private boolean cancelled;
@Getter
@NotNull
private Player player;
@Getter private int amount;
private double total;
@Getter
@NotNull
private Shop shop;
@Getter private double tax;
private boolean cancelled;
private double total;
/**
* Builds a new shop purchase event
@@ -56,13 +56,13 @@ public class ShopSuccessPurchaseEvent extends Event implements Cancellable {
*/
public double getBalanceWithoutTax() {return this.total;}
@NotNull
@Override
public HandlerList getHandlers() {
public static HandlerList getHandlerList() {
return handlers;
}
public static HandlerList getHandlerList() {
@NotNull
@Override
public HandlerList getHandlers() {
return handlers;
}
@@ -9,9 +9,9 @@ import org.maxgamer.quickshop.Shop.Shop;
public class ShopUpdateEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private boolean cancelled;
@Getter
private @NotNull Shop shop;
private boolean cancelled;
/**
* Call when shop is trying updated to database
@@ -21,13 +21,14 @@ public class ShopUpdateEvent extends Event implements Cancellable {
public ShopUpdateEvent(@NotNull Shop shop) {
this.shop = shop;
}
@NotNull
@Override
public HandlerList getHandlers() {
public static HandlerList getHandlerList() {
return handlers;
}
public static HandlerList getHandlerList() {
@NotNull
@Override
public HandlerList getHandlers() {
return handlers;
}
@@ -20,10 +20,9 @@ public class InternalListener implements Listener {
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void shopPurchase(ShopSuccessPurchaseEvent event) {
plugin.log("Player " + event.getPlayer().getName() + " purchased " + event.getShop().ownerName() + " shop item x" + event
.getAmount() + " for " + plugin.getEconomy().format(event.getBalance()) + " (" + plugin.getEconomy()
.format(event.getTax()) + " tax).");
public void shopModeratorChanges(ShopModeratorChangedEvent event) {
plugin.log("Shop at location " + event.getShop().getLocation() + " moderator was changed to " + event.getModerator()
.toString());
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
@@ -33,9 +32,10 @@ public class InternalListener implements Listener {
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void shopModeratorChanges(ShopModeratorChangedEvent event) {
plugin.log("Shop at location " + event.getShop().getLocation() + " moderator was changed to " + event.getModerator()
.toString());
public void shopPurchase(ShopSuccessPurchaseEvent event) {
plugin.log("Player " + event.getPlayer().getName() + " purchased " + event.getShop().ownerName() + " shop item x" + event
.getAmount() + " for " + plugin.getEconomy().format(event.getBalance()) + " (" + plugin.getEconomy()
.format(event.getTax()) + " tax).");
}
}
@@ -26,24 +26,18 @@ import org.maxgamer.quickshop.Util.Util;
public class BlockListener implements Listener {
private QuickShop plugin;
/*
* Listens for chest placement, so a doublechest shop can't be created.
/**
* Gets the shop a sign is attached to
*
* @param loc The location of the sign
* @return The shop
*/
@EventHandler(ignoreCancelled = true)
public void onPlace(BlockPlaceEvent e) {
if (ListenerHelper.isDisabled(e.getClass()))
return;
BlockState bs = e.getBlock().getState();
if (!(bs instanceof DoubleChest))
return;
Block b = e.getBlock();
Player p = e.getPlayer();
Block chest = Util.getSecondHalf(b);
if (chest != null && plugin.getShopManager().getShop(chest.getLocation()) != null && !p
.hasPermission("quickshop.create.double")) {
e.setCancelled(true);
p.sendMessage(MsgUtil.getMessage("no-double-chests"));
}
private Shop getShopNextTo(Location loc) {
Block b = Util.getAttached(loc.getBlock());
// Util.getAttached(b)
if (b == null)
return null;
return plugin.getShopManager().getShop(b.getLocation());
}
/*
@@ -130,21 +124,6 @@ public class BlockListener implements Listener {
}
}
/**
* Gets the shop a sign is attached to
*
* @param loc The location of the sign
* @return The shop
*/
private Shop getShopNextTo(Location loc) {
Block b = Util.getAttached(loc.getBlock());
// Util.getAttached(b)
if (b == null)
return null;
return plugin.getShopManager().getShop(b.getLocation());
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onInventoryMove(InventoryMoveItemEvent event) {
if (ListenerHelper.isDisabled(event.getClass()))
@@ -157,4 +136,24 @@ public class BlockListener implements Listener {
return;
shop.setSignText();
}
/*
* Listens for chest placement, so a doublechest shop can't be created.
*/
@EventHandler(ignoreCancelled = true)
public void onPlace(BlockPlaceEvent e) {
if (ListenerHelper.isDisabled(e.getClass()))
return;
BlockState bs = e.getBlock().getState();
if (!(bs instanceof DoubleChest))
return;
Block b = e.getBlock();
Player p = e.getPlayer();
Block chest = Util.getSecondHalf(b);
if (chest != null && plugin.getShopManager().getShop(chest.getLocation()) != null && !p
.hasPermission("quickshop.create.double")) {
e.setCancelled(true);
p.sendMessage(MsgUtil.getMessage("no-double-chests"));
}
}
}
@@ -31,57 +31,48 @@ public class LockListener implements Listener {
private QuickShop plugin;
@EventHandler(ignoreCancelled = true)
public void onClick(PlayerInteractEvent e) {
if (ListenerHelper.isDisabled(e.getClass()))
public void invEvent(InventoryMoveItemEvent e) {
if (!InventoryPreview.isPreviewItem(e.getItem()))
return;
Block b = e.getClickedBlock();
if (b == null)
return;
if (!Util.canBeShop(b))
return;
Player p = e.getPlayer();
if (e.getAction() != Action.RIGHT_CLICK_BLOCK)
return; // Didn't right click it, we dont care.
Shop shop = plugin.getShopManager().getShop(b.getLocation());
// Make sure they're not using the non-shop half of a double chest.
if (shop == null) {
b = Util.getSecondHalf(b);
if (b == null)
return;
shop = plugin.getShopManager().getShop(b.getLocation());
if (shop == null)
return;
}
if (!shop.getModerator().isModerator(p.getUniqueId())) {
if (p.hasPermission("quickshop.other.open")) {
p.sendMessage(MsgUtil.getMessage("bypassing-lock"));
return;
}
p.sendMessage(MsgUtil.getMessage("that-is-locked"));
e.setCancelled(true);
}
@EventHandler
public void invEvent(InventoryClickEvent e) {
if (InventoryPreview.isPreviewItem(e.getCursor())) {
e.setCancelled(true);
e.setResult(Event.Result.DENY);
}
if (InventoryPreview.isPreviewItem(e.getCurrentItem())) {
e.setCancelled(true);
e.setResult(Event.Result.DENY);
}
}
/*
* Handles hopper placement
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlace(BlockPlaceEvent e) {
if (ListenerHelper.isDisabled(e.getClass()))
return;
Block b = e.getBlock();
if (b.getType() != Material.HOPPER)
return;
Player p = e.getPlayer();
if (!Util.isOtherShopWithinHopperReach(b, p))
return;
if (p.hasPermission("quickshop.other.open")) {
p.sendMessage(MsgUtil.getMessage("bypassing-lock"));
return;
@EventHandler
public void invEvent(InventoryDragEvent e) {
if (InventoryPreview.isPreviewItem(e.getCursor())) {
e.setCancelled(true);
e.setResult(Event.Result.DENY);
}
if (InventoryPreview.isPreviewItem(e.getOldCursor())) {
e.setCancelled(true);
e.setResult(Event.Result.DENY);
}
}
@EventHandler
public void invEvent(InventoryPickupItemEvent e) {
Inventory inventory = e.getInventory();
ItemStack[] stacks = inventory.getContents();
for (ItemStack itemStack : stacks) {
if (itemStack == null)
continue;
if (InventoryPreview.isPreviewItem(itemStack)) {
e.setCancelled(true);
}
}
p.sendMessage(MsgUtil.getMessage("that-is-locked"));
e.setCancelled(true);
}
/*
@@ -135,6 +126,38 @@ public class LockListener implements Listener {
}
}
@EventHandler(ignoreCancelled = true)
public void onClick(PlayerInteractEvent e) {
if (ListenerHelper.isDisabled(e.getClass()))
return;
Block b = e.getClickedBlock();
if (b == null)
return;
if (!Util.canBeShop(b))
return;
Player p = e.getPlayer();
if (e.getAction() != Action.RIGHT_CLICK_BLOCK)
return; // Didn't right click it, we dont care.
Shop shop = plugin.getShopManager().getShop(b.getLocation());
// Make sure they're not using the non-shop half of a double chest.
if (shop == null) {
b = Util.getSecondHalf(b);
if (b == null)
return;
shop = plugin.getShopManager().getShop(b.getLocation());
if (shop == null)
return;
}
if (!shop.getModerator().isModerator(p.getUniqueId())) {
if (p.hasPermission("quickshop.other.open")) {
p.sendMessage(MsgUtil.getMessage("bypassing-lock"));
return;
}
p.sendMessage(MsgUtil.getMessage("that-is-locked"));
e.setCancelled(true);
}
}
/*
* Handles shops breaking through explosions
*/
@@ -156,48 +179,25 @@ public class LockListener implements Listener {
}
}
@EventHandler(ignoreCancelled = true)
public void invEvent(InventoryMoveItemEvent e) {
if (!InventoryPreview.isPreviewItem(e.getItem()))
/*
* Handles hopper placement
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlace(BlockPlaceEvent e) {
if (ListenerHelper.isDisabled(e.getClass()))
return;
Block b = e.getBlock();
if (b.getType() != Material.HOPPER)
return;
Player p = e.getPlayer();
if (!Util.isOtherShopWithinHopperReach(b, p))
return;
if (p.hasPermission("quickshop.other.open")) {
p.sendMessage(MsgUtil.getMessage("bypassing-lock"));
return;
}
p.sendMessage(MsgUtil.getMessage("that-is-locked"));
e.setCancelled(true);
}
@EventHandler
public void invEvent(InventoryClickEvent e) {
if (InventoryPreview.isPreviewItem(e.getCursor())) {
e.setCancelled(true);
e.setResult(Event.Result.DENY);
}
if (InventoryPreview.isPreviewItem(e.getCurrentItem())) {
e.setCancelled(true);
e.setResult(Event.Result.DENY);
}
}
@EventHandler
public void invEvent(InventoryDragEvent e) {
if (InventoryPreview.isPreviewItem(e.getCursor())) {
e.setCancelled(true);
e.setResult(Event.Result.DENY);
}
if (InventoryPreview.isPreviewItem(e.getOldCursor())) {
e.setCancelled(true);
e.setResult(Event.Result.DENY);
}
}
@EventHandler
public void invEvent(InventoryPickupItemEvent e) {
Inventory inventory = e.getInventory();
ItemStack[] stacks = inventory.getContents();
for (ItemStack itemStack : stacks) {
if (itemStack == null)
continue;
if (InventoryPreview.isPreviewItem(itemStack)) {
e.setCancelled(true);
}
}
}
}
@@ -169,6 +169,42 @@ public class PlayerListener implements Listener {
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onInventoryClose(InventoryCloseEvent e) {
if (ListenerHelper.isDisabled(e.getClass()))
return;
try {
Inventory inventory = e.getInventory();
if (inventory == null)
return;
Location location = inventory.getLocation();
if (location == null)
return;
Shop shop = plugin.getShopManager().getShop(location);
if (shop == null)
return;
shop.setSignText();
} catch (Throwable t) {
//Ignore
}
}
@EventHandler(ignoreCancelled = true)
public void onJoin(PlayerJoinEvent e) {
if (ListenerHelper.isDisabled(e.getClass()))
return;
// Notify the player any messages they were sent
if (plugin.getConfig().getBoolean("shop.auto-fetch-shop-messages")) {
new BukkitRunnable() {
@Override
public void run() {
MsgUtil.flush(e.getPlayer());
}
}.runTaskAsynchronously(plugin);
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
/*
* Waits for a player to move too far from a shop, then cancels the menu.
@@ -199,30 +235,6 @@ public class PlayerListener implements Listener {
}
@EventHandler(ignoreCancelled = true)
public void onTeleport(PlayerTeleportEvent e) {
if (ListenerHelper.isDisabled(e.getClass()))
return;
PlayerMoveEvent me = new PlayerMoveEvent(e.getPlayer(), e.getFrom(), e.getTo());
onMove(me);
}
@EventHandler(ignoreCancelled = true)
public void onJoin(PlayerJoinEvent e) {
if (ListenerHelper.isDisabled(e.getClass()))
return;
// Notify the player any messages they were sent
if (plugin.getConfig().getBoolean("shop.auto-fetch-shop-messages")) {
new BukkitRunnable() {
@Override
public void run() {
MsgUtil.flush(e.getPlayer());
}
}.runTaskAsynchronously(plugin);
}
}
@EventHandler(ignoreCancelled = true)
public void onPlayerQuit(PlayerQuitEvent e) {
if (ListenerHelper.isDisabled(e.getClass()))
@@ -231,24 +243,12 @@ public class PlayerListener implements Listener {
plugin.getShopManager().getActions().remove(e.getPlayer().getUniqueId());
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onInventoryClose(InventoryCloseEvent e) {
@EventHandler(ignoreCancelled = true)
public void onTeleport(PlayerTeleportEvent e) {
if (ListenerHelper.isDisabled(e.getClass()))
return;
try {
Inventory inventory = e.getInventory();
if (inventory == null)
return;
Location location = inventory.getLocation();
if (location == null)
return;
Shop shop = plugin.getShopManager().getShop(location);
if (shop == null)
return;
shop.setSignText();
} catch (Throwable t) {
//Ignore
}
PlayerMoveEvent me = new PlayerMoveEvent(e.getPlayer(), e.getFrom(), e.getTo());
onMove(me);
}
}
@@ -25,6 +25,81 @@ public class ShopProtectionListener implements Listener {
this.plugin = plugin;
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockExplode(BlockExplodeEvent e) {
if (ListenerHelper.isDisabled(e.getClass()))
return;
for (int i = 0; i < e.blockList().size(); i++) {
Block b = e.blockList().get(i);
Shop shop = plugin.getShopManager().getShop(b.getLocation());
if (shop != null) {
if (plugin.getConfig().getBoolean("protect.explode"))
e.setCancelled(true);
else
shop.delete();
}
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockFromTo(BlockFromToEvent e) {
if (ListenerHelper.isDisabled(e.getClass()))
return;
if (!plugin.getConfig().getBoolean("protect.fromto"))
return;
Shop shop = plugin.getShopManager().getShop(e.getToBlock().getLocation());
if (shop == null)
return;
e.setCancelled(true);
}
//Protect Redstone active shop
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockRedstoneChange(BlockRedstoneEvent event) {
if (ListenerHelper.isDisabled(event.getClass()))
return;
if (!plugin.getConfig().getBoolean("protect.redstone"))
return;
Shop shop = plugin.getShopManager().getShop(event.getBlock().getLocation());
if (shop == null)
return;
event.setNewCurrent(event.getOldCurrent());
//plugin.getLogger().warning("[Exploit Alert] a Redstone tried to active of " + shop);
//Util.debugLog(ChatColor.RED + "[QuickShop][Exploit alert] Redstone was activated on the following shop " + shop);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockSpread(BlockSpreadEvent e) {
if (ListenerHelper.isDisabled(e.getClass()))
return;
Block newBlock = e.getNewState().getBlock();
Shop thisBlockShop = plugin.getShopManager().getShop(newBlock.getLocation());
Shop underBlockShop = plugin.getShopManager().getShop(newBlock.getRelative(BlockFace.DOWN).getLocation());
if (thisBlockShop == null && underBlockShop == null)
return;
if (plugin.getConfig().getBoolean("protect.spread"))
e.setCancelled(true);
}
/*
* Handles shops breaking through explosions
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onExplode(EntityExplodeEvent e) {
if (ListenerHelper.isDisabled(e.getClass()))
return;
for (int i = 0; i < e.blockList().size(); i++) {
Block b = e.blockList().get(i);
Shop shop = plugin.getShopManager().getShop(b.getLocation());
if (shop != null) {
if (plugin.getConfig().getBoolean("protect.explode"))
e.setCancelled(true);
else
shop.delete();
}
}
}
//Protect Minecart steal shop
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onInventoryMove(InventoryMoveItemEvent event) {
@@ -55,21 +130,6 @@ public class ShopProtectionListener implements Listener {
shop.delete();
}
//Protect Redstone active shop
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockRedstoneChange(BlockRedstoneEvent event) {
if (ListenerHelper.isDisabled(event.getClass()))
return;
if (!plugin.getConfig().getBoolean("protect.redstone"))
return;
Shop shop = plugin.getShopManager().getShop(event.getBlock().getLocation());
if (shop == null)
return;
event.setNewCurrent(event.getOldCurrent());
//plugin.getLogger().warning("[Exploit Alert] a Redstone tried to active of " + shop);
//Util.debugLog(ChatColor.RED + "[QuickShop][Exploit alert] Redstone was activated on the following shop " + shop);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onStructureGrow(StructureGrowEvent event) {
if (ListenerHelper.isDisabled(event.getClass()))
@@ -86,64 +146,4 @@ public class ShopProtectionListener implements Listener {
//Util.sendMessageToOps(ChatColor.RED + "[QuickShop][Exploit alert] A StructureGrowing tried to break the shop of " + shop);
}
}
/*
* Handles shops breaking through explosions
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onExplode(EntityExplodeEvent e) {
if (ListenerHelper.isDisabled(e.getClass()))
return;
for (int i = 0; i < e.blockList().size(); i++) {
Block b = e.blockList().get(i);
Shop shop = plugin.getShopManager().getShop(b.getLocation());
if (shop != null) {
if (plugin.getConfig().getBoolean("protect.explode"))
e.setCancelled(true);
else
shop.delete();
}
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockExplode(BlockExplodeEvent e) {
if (ListenerHelper.isDisabled(e.getClass()))
return;
for (int i = 0; i < e.blockList().size(); i++) {
Block b = e.blockList().get(i);
Shop shop = plugin.getShopManager().getShop(b.getLocation());
if (shop != null) {
if (plugin.getConfig().getBoolean("protect.explode"))
e.setCancelled(true);
else
shop.delete();
}
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockSpread(BlockSpreadEvent e) {
if (ListenerHelper.isDisabled(e.getClass()))
return;
Block newBlock = e.getNewState().getBlock();
Shop thisBlockShop = plugin.getShopManager().getShop(newBlock.getLocation());
Shop underBlockShop = plugin.getShopManager().getShop(newBlock.getRelative(BlockFace.DOWN).getLocation());
if (thisBlockShop == null && underBlockShop == null)
return;
if (plugin.getConfig().getBoolean("protect.spread"))
e.setCancelled(true);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockFromTo(BlockFromToEvent e) {
if (ListenerHelper.isDisabled(e.getClass()))
return;
if (!plugin.getConfig().getBoolean("protect.fromto"))
return;
Shop shop = plugin.getShopManager().getShop(e.getToBlock().getLocation());
if (shop == null)
return;
e.setCancelled(true);
}
}
File diff suppressed because it is too large. Load diff
@@ -34,84 +34,83 @@ import org.maxgamer.quickshop.Watcher.UpdateWatcher;
public class QuickShop extends JavaPlugin {
/** The active instance of QuickShop */
public static QuickShop instance;
/** 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")
*/
private HashSet<String> warnings = new HashSet<>();
/** The database for storing all our data for persistence */
private Database database;
// Listeners - We decide which one to use at runtime
private ChatListener chatListener;
// Listeners (These don't)
private BlockListener blockListener;
private PlayerListener playerListener;
private DisplayProtectionListener inventoryListener;
/** The BootError, if it not NULL, plugin will stop loading and show setted errors when use /qs **/
private BootError bootError;
// Listeners - We decide which one to use at runtime
private ChatListener chatListener;
private ChunkListener chunkListener;
private WorldListener worldListener;
//private BukkitTask itemWatcherTask;
private LogWatcher logWatcher;
private ItemMatcher itemMatcher;
private CommandManager commandManager;
private Tab commandTabCompleter;
/** WIP **/
private Compatibility compatibilityTool = new Compatibility(this);
private CustomInventoryListener customInventoryListener;
/** The database for storing all our data for persistence */
private Database database;
/** Contains all SQL tasks **/
private DatabaseHelper databaseHelper;
/** Queued database manager **/
private DatabaseManager databaseManager;
/** Default database prefix, can overwrite by config **/
private String dbPrefix = "";
/** Whether we should use display items or not */
private boolean display = true;
private DisplayBugFixListener displayBugFixListener;
private LockListener lockListener;
// /** Whether players are required to sneak to create/buy from a shop */
// public boolean sneak;
// /** Whether players are required to sneak to create a shop */
// public boolean sneakCreate;
// /** Whether players are required to sneak to trade with a shop */
// public boolean sneakTrade;
/** Whether we should use display items or not */
private boolean display = true;
// private Metrics metrics;
private int displayItemCheckTicks;
private DisplayWatcher displayWatcher;
/** The economy we hook into for transactions */
private Economy economy;
private DisplayProtectionListener inventoryListener;
private ItemMatcher itemMatcher;
/** Language manager, to select which language will loaded. **/
private Language language;
/** Whether or not to limit players shop amounts */
private boolean limit = false;
/** The shop limites. **/
private HashMap<String, Integer> limits = new HashMap<>();
private LockListener lockListener;
//private BukkitTask itemWatcherTask;
private LogWatcher logWatcher;
/** bStats, good helper for metrics. **/
private Metrics metrics;
private boolean noopDisable;
/** The plugin OpenInv (null if not present) */
private Plugin openInvPlugin;
/** A util to call to check some actions permission **/
private PermissionChecker permissionChecker;
private PlayerListener playerListener;
/**
* Whether we players are charged a fee to change the price on their shop (To
* help deter endless undercutting
*/
private boolean priceChangeRequiresFee = false;
/** Whether or not to limit players shop amounts */
private boolean limit = false;
/** The plugin OpenInv (null if not present) */
private Plugin openInvPlugin;
/** The shop limites. **/
private HashMap<String, Integer> limits = new HashMap<>();
/** Use SpoutPlugin to get item / block names */
private boolean useSpout = false;
// private Metrics metrics;
private int displayItemCheckTicks;
private boolean noopDisable;
private boolean setupDBonEnableding = false;
/** Default database prefix, can overwrite by config **/
private String dbPrefix = "";
private Tab commandTabCompleter;
/** bStats, good helper for metrics. **/
private Metrics metrics;
/** Language manager, to select which language will loaded. **/
private Language language;
/** The BootError, if it not NULL, plugin will stop loading and show setted errors when use /qs **/
private BootError bootError;
private CustomInventoryListener customInventoryListener;
/** WIP **/
private Compatibility compatibilityTool = new Compatibility(this);
/** Rewrited shoploader, more faster. **/
private ShopLoader shopLoader;
/** Contains all SQL tasks **/
private DatabaseHelper databaseHelper;
/** Queued database manager **/
private DatabaseManager databaseManager;
/** A util to call to check some actions permission **/
private PermissionChecker permissionChecker;
/** The server UniqueID, use to the ErrorReporter **/
private UUID serverUniqueID;
/** The error reporter to help devs report errors to Sentry.io **/
private SentryErrorReporter sentryErrorReporter;
private CommandManager commandManager;
/** The server UniqueID, use to the ErrorReporter **/
private UUID serverUniqueID;
private boolean setupDBonEnableding = false;
/** Rewrited shoploader, more faster. **/
private ShopLoader shopLoader;
/** The Shop Manager used to store shops */
private ShopManager shopManager;
private ShopProtectionListener shopProtectListener;
private DisplayWatcher displayWatcher;
private SyncTaskWatcher syncTaskWatcher;
/** Use SpoutPlugin to get item / block names */
private boolean useSpout = false;
/**
* A set of players who have been warned ("Your shop isn't automatically
* locked")
*/
private HashSet<String> warnings = new HashSet<>();
private WorldListener worldListener;
/**
* Get the Player's Shop limit.
@@ -128,45 +127,6 @@ public class QuickShop extends JavaPlugin {
return max;
}
/**
* Check the env plugin running.
*
* @throws RuntimeException The error message, use this to create a BootError.
*/
private void runtimeCheck() throws RuntimeException {
try {
getServer().spigot();
} catch (Throwable e) {
getLogger().severe("FATAL: QSRR can only be run on Spigot servers and forks of Spigot!");
throw new RuntimeException("Server must be Spigot based, Don't use CraftBukkit!");
}
if (getServer().getName().toLowerCase().contains("catserver")) {
// Send FATAL ERROR TO CatServer's users.
getLogger().severe("FATAL: QSRR can't run on CatServer Community/Personal/Pro");
throw new RuntimeException("QuickShop doen't support CatServer");
}
if (Util.isDevEdition()) {
getLogger().severe("WARNING: You are running QSRR in dev-mode");
getLogger().severe("WARNING: Keep backup and DO NOT run this in a production environment!");
getLogger().severe("WARNING: Test version may destroy everything!");
getLogger().severe(
"WARNING: QSRR won't start without your confirmation, nothing will change before you turn on dev allowed.");
if (!getConfig().getBoolean("dev-mode")) {
getLogger().severe(
"WARNING: Set dev-mode: true in config.yml to allow qs load in dev mode(You may need add this line to the config yourself).");
noopDisable = true;
throw new RuntimeException("Snapshot cannot run when dev-mode is false in the config");
}
}
String nmsVersion = Util.getNMSVersion();
IncompatibleChecker incompatibleChecker = new IncompatibleChecker();
getLogger().info("Running QuickShop-Reremake on Minecraft version " + nmsVersion);
if (incompatibleChecker.isIncompatible(nmsVersion))
throw new RuntimeException("Your Minecraft version is nolonger supported: " + nmsVersion);
}
/**
* Load 3rdParty plugin support module.
*/
@@ -180,6 +140,80 @@ 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.
*/
private boolean loadEcon() {
try {
//EconomyCore core = new Economy_Vault();
EconomyCore core = null;
switch (EconomyType.fromID(getConfig().getInt("economy-type"))) {
case UNKNOWN:
bootError = new BootError("Can't load the Economy provider, invaild value in config.yml.");
return false;
case VAULT:
core = new Economy_Vault();
Util.debugLog("Now using the Vault economy system.");
break;
case RESERVE:
core = new Economy_Reserve();
Util.debugLog("Now using the Reserve economy system.");
break;
}
if (!core.isValid()) {
// getLogger().severe("Economy is not valid!");
bootError = BuiltInSolution.econError();
// 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) {
this.getSentryErrorReporter().ignoreThrow();
e.printStackTrace();
getLogger().severe("QuickShop could not hook into a economy/Not found Vault or Reserve!");
getLogger().severe("QuickShop CANNOT start!");
bootError = BuiltInSolution.econError();
HandlerList.unregisterAll(this);
getLogger().severe("Plugin listeners was disabled, please fix the economy issue.");
return false;
}
}
/**
* 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.
*/
public void log(@NotNull String s) {
if (this.getLogWatcher() == null)
return;
this.getLogWatcher().log(s);
}
/** Reloads QuickShops config */
@Override
public void reloadConfig() {
super.reloadConfig();
// Load quick variables
this.display = this.getConfig().getBoolean("shop.display-items");
this.priceChangeRequiresFee = this.getConfig().getBoolean("shop.price-change-requires-fee");
this.displayItemCheckTicks = this.getConfig().getInt("shop.display-items-check-ticks");
language = new Language(this); //Init locale
if (this.getConfig().getBoolean("log-actions")) {
logWatcher = new LogWatcher(this, new File(getDataFolder(), "qs.log"));
} else {
logWatcher = null;
}
MsgUtil.loadCfgMessages();
}
/**
* Early than onEnable, make sure instance was loaded in first time.
*/
@@ -189,6 +223,51 @@ public class QuickShop extends JavaPlugin {
bootError = null;
}
@Override
public void onDisable() {
if (noopDisable)
return;
getLogger().info("QuickShop is finishing remaining work, this may need a while...");
Util.debugLog("Closing all GUIs...");
for (Player player : Bukkit.getOnlinePlayers()) {
player.closeInventory();
}
Util.debugLog("Cleaning up database queues...");
if (this.getShopManager() != null)
this.getDatabaseManager().uninit();
Util.debugLog("Unregistering tasks...");
//if (itemWatcherTask != null)
// itemWatcherTask.cancel();
if (logWatcher != null) {
logWatcher.close(); // Closes the file
}
/* Unload UpdateWatcher */
UpdateWatcher.uninit();
Util.debugLog("Cleaning up resources and unloading all shops...");
/* Remove all display items, and any dupes we can find */
if (shopManager != null)
shopManager.clear();
/* Empty the buffer */
if (databaseManager != null)
database.close();
/* Close Database */
if (database != null)
try {
this.database.getConnection().close();
} catch (SQLException e) {
if (getSentryErrorReporter() != null)
this.getSentryErrorReporter().ignoreThrow();
e.printStackTrace();
}
if (warnings != null)
warnings.clear();
//this.reloadConfig();
Util.debugLog("All shutdown work is finished.");
}
@Override
public void onEnable() {
Timer enableTimer = new Timer(true);
@@ -309,56 +388,43 @@ public class QuickShop extends JavaPlugin {
}.runTaskLater(this, 1);
}
private void submitMeritcs() {
if (!getConfig().getBoolean("disabled-metrics")) {
String serverVer = Bukkit.getVersion();
String bukkitVer = Bukkit.getBukkitVersion();
String serverName = Bukkit.getServer().getName();
String vaultVer;
Plugin vault = Bukkit.getPluginManager().getPlugin("Vault");
if (vault != null) {
vaultVer = vault.getDescription().getVersion();
} else {
vaultVer = "Vault not found";
}
// Use internal Metric class not Maven for solve plugin name issues
String display_Items;
if (getConfig().getBoolean("shop.display-items")) { // Maybe mod server use this plugin more? Or have big
// number items need disabled?
display_Items = "Enabled";
} else {
display_Items = "Disabled";
}
String locks;
if (getConfig().getBoolean("shop.lock")) {
locks = "Enabled";
} else {
locks = "Disabled";
}
String sneak_action;
if (getConfig().getBoolean("shop.sneak-to-create") || getConfig().getBoolean("shop.sneak-to-trade")) {
sneak_action = "Enabled";
} else {
sneak_action = "Disabled";
}
String shop_find_distance = getConfig().getString("shop.find-distance");
// Version
metrics.addCustomChart(new Metrics.SimplePie("server_version", () -> serverVer));
metrics.addCustomChart(new Metrics.SimplePie("bukkit_version", () -> bukkitVer));
metrics.addCustomChart(new Metrics.SimplePie("vault_version", () -> vaultVer));
metrics.addCustomChart(new Metrics.SimplePie("server_name", () -> serverName));
metrics.addCustomChart(new Metrics.SimplePie("use_display_items", () -> display_Items));
metrics.addCustomChart(new Metrics.SimplePie("use_locks", () -> locks));
metrics.addCustomChart(new Metrics.SimplePie("use_sneak_action", () -> sneak_action));
metrics.addCustomChart(new Metrics.SimplePie("shop_find_distance", () -> shop_find_distance));
// Exp for stats, maybe i need improve this, so i add this.
metrics.submitData(); // Submit now!
getLogger().info("Metrics submitted.");
} else {
getLogger().info("You have disabled mertics, Skipping...");
/**
* Check the env plugin running.
*
* @throws RuntimeException The error message, use this to create a BootError.
*/
private void runtimeCheck() throws RuntimeException {
try {
getServer().spigot();
} catch (Throwable e) {
getLogger().severe("FATAL: QSRR can only be run on Spigot servers and forks of Spigot!");
throw new RuntimeException("Server must be Spigot based, Don't use CraftBukkit!");
}
if (getServer().getName().toLowerCase().contains("catserver")) {
// Send FATAL ERROR TO CatServer's users.
getLogger().severe("FATAL: QSRR can't run on CatServer Community/Personal/Pro");
throw new RuntimeException("QuickShop doen't support CatServer");
}
if (Util.isDevEdition()) {
getLogger().severe("WARNING: You are running QSRR in dev-mode");
getLogger().severe("WARNING: Keep backup and DO NOT run this in a production environment!");
getLogger().severe("WARNING: Test version may destroy everything!");
getLogger().severe(
"WARNING: QSRR won't start without your confirmation, nothing will change before you turn on dev allowed.");
if (!getConfig().getBoolean("dev-mode")) {
getLogger().severe(
"WARNING: Set dev-mode: true in config.yml to allow qs load in dev mode(You may need add this line to the config yourself).");
noopDisable = true;
throw new RuntimeException("Snapshot cannot run when dev-mode is false in the config");
}
}
String nmsVersion = Util.getNMSVersion();
IncompatibleChecker incompatibleChecker = new IncompatibleChecker();
getLogger().info("Running QuickShop-Reremake on Minecraft version " + nmsVersion);
if (incompatibleChecker.isIncompatible(nmsVersion))
throw new RuntimeException("Your Minecraft version is nolonger supported: " + nmsVersion);
}
/**
@@ -412,6 +478,58 @@ public class QuickShop extends JavaPlugin {
return true;
}
private void submitMeritcs() {
if (!getConfig().getBoolean("disabled-metrics")) {
String serverVer = Bukkit.getVersion();
String bukkitVer = Bukkit.getBukkitVersion();
String serverName = Bukkit.getServer().getName();
String vaultVer;
Plugin vault = Bukkit.getPluginManager().getPlugin("Vault");
if (vault != null) {
vaultVer = vault.getDescription().getVersion();
} else {
vaultVer = "Vault not found";
}
// Use internal Metric class not Maven for solve plugin name issues
String display_Items;
if (getConfig().getBoolean("shop.display-items")) { // Maybe mod server use this plugin more? Or have big
// number items need disabled?
display_Items = "Enabled";
} else {
display_Items = "Disabled";
}
String locks;
if (getConfig().getBoolean("shop.lock")) {
locks = "Enabled";
} else {
locks = "Disabled";
}
String sneak_action;
if (getConfig().getBoolean("shop.sneak-to-create") || getConfig().getBoolean("shop.sneak-to-trade")) {
sneak_action = "Enabled";
} else {
sneak_action = "Disabled";
}
String shop_find_distance = getConfig().getString("shop.find-distance");
// Version
metrics.addCustomChart(new Metrics.SimplePie("server_version", () -> serverVer));
metrics.addCustomChart(new Metrics.SimplePie("bukkit_version", () -> bukkitVer));
metrics.addCustomChart(new Metrics.SimplePie("vault_version", () -> vaultVer));
metrics.addCustomChart(new Metrics.SimplePie("server_name", () -> serverName));
metrics.addCustomChart(new Metrics.SimplePie("use_display_items", () -> display_Items));
metrics.addCustomChart(new Metrics.SimplePie("use_locks", () -> locks));
metrics.addCustomChart(new Metrics.SimplePie("use_sneak_action", () -> sneak_action));
metrics.addCustomChart(new Metrics.SimplePie("shop_find_distance", () -> shop_find_distance));
// Exp for stats, maybe i need improve this, so i add this.
metrics.submitData(); // Submit now!
getLogger().info("Metrics submitted.");
} else {
getLogger().info("You have disabled mertics, Skipping...");
}
}
@SuppressWarnings("UnusedAssignment")
private void updateConfig(int selectedVersion) {
String serverUUID = getConfig().getString("server-uuid");
@@ -675,124 +793,12 @@ public class QuickShop extends JavaPlugin {
reloadConfig();
}
/** Reloads QuickShops config */
@Override
public void reloadConfig() {
super.reloadConfig();
// Load quick variables
this.display = this.getConfig().getBoolean("shop.display-items");
this.priceChangeRequiresFee = this.getConfig().getBoolean("shop.price-change-requires-fee");
this.displayItemCheckTicks = this.getConfig().getInt("shop.display-items-check-ticks");
language = new Language(this); //Init locale
if (this.getConfig().getBoolean("log-actions")) {
logWatcher = new LogWatcher(this, new File(getDataFolder(), "qs.log"));
} else {
logWatcher = null;
}
MsgUtil.loadCfgMessages();
}
/**
* 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 the QSRR's fork edition name, you can modify this if you want create yourself fork.
*
* @return true if successful, false if the core is invalid or is not found, and
* vault cannot be used.
* @return The fork name.
*/
private boolean loadEcon() {
try {
//EconomyCore core = new Economy_Vault();
EconomyCore core = null;
switch (EconomyType.fromID(getConfig().getInt("economy-type"))) {
case UNKNOWN:
bootError = new BootError("Can't load the Economy provider, invaild value in config.yml.");
return false;
case VAULT:
core = new Economy_Vault();
Util.debugLog("Now using the Vault economy system.");
break;
case RESERVE:
core = new Economy_Reserve();
Util.debugLog("Now using the Reserve economy system.");
break;
}
if (!core.isValid()) {
// getLogger().severe("Economy is not valid!");
bootError = BuiltInSolution.econError();
// 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) {
this.getSentryErrorReporter().ignoreThrow();
e.printStackTrace();
getLogger().severe("QuickShop could not hook into a economy/Not found Vault or Reserve!");
getLogger().severe("QuickShop CANNOT start!");
bootError = BuiltInSolution.econError();
HandlerList.unregisterAll(this);
getLogger().severe("Plugin listeners was disabled, please fix the economy issue.");
return false;
}
}
@Override
public void onDisable() {
if (noopDisable)
return;
getLogger().info("QuickShop is finishing remaining work, this may need a while...");
Util.debugLog("Closing all GUIs...");
for (Player player : Bukkit.getOnlinePlayers()) {
player.closeInventory();
}
Util.debugLog("Cleaning up database queues...");
if (this.getShopManager() != null)
this.getDatabaseManager().uninit();
Util.debugLog("Unregistering tasks...");
//if (itemWatcherTask != null)
// itemWatcherTask.cancel();
if (logWatcher != null) {
logWatcher.close(); // Closes the file
}
/* Unload UpdateWatcher */
UpdateWatcher.uninit();
Util.debugLog("Cleaning up resources and unloading all shops...");
/* Remove all display items, and any dupes we can find */
if (shopManager != null)
shopManager.clear();
/* Empty the buffer */
if (databaseManager != null)
database.close();
/* Close Database */
if (database != null)
try {
this.database.getConnection().close();
} catch (SQLException e) {
if (getSentryErrorReporter() != null)
this.getSentryErrorReporter().ignoreThrow();
e.printStackTrace();
}
if (warnings != null)
warnings.clear();
//this.reloadConfig();
Util.debugLog("All shutdown work is finished.");
}
/**
* 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.
*/
public void log(@NotNull String s) {
if (this.getLogWatcher() == null)
return;
this.getLogWatcher().log(s);
}
public String getFork() { return "Reremake"; }
/**
* Returns QS version, this method only exist on QSRR forks If running other
@@ -805,11 +811,4 @@ public class QuickShop extends JavaPlugin {
return QuickShop.instance.getDescription().getVersion();
}
/**
* Return the QSRR's fork edition name, you can modify this if you want create yourself fork.
*
* @return The fork name.
*/
public String getFork() { return "Reremake"; }
}
@@ -21,10 +21,14 @@ import org.maxgamer.quickshop.Util.Util;
@ToString
public class ArmorStandDisplayItem implements DisplayItem {
private QuickShop plugin = QuickShop.instance;
private ItemStack originalItemStack;
private ItemStack guardedIstack;
private static boolean isTool(Material material) {
String nlc = material.name().toLowerCase();
return nlc.contains("sword") || nlc.contains("shovel") || nlc.contains("axe");
}
private ArmorStand armorStand;
private ItemStack guardedIstack;
private ItemStack originalItemStack;
private QuickShop plugin = QuickShop.instance;
private Shop shop;
ArmorStandDisplayItem(@NotNull Shop shop) {
@@ -33,6 +37,13 @@ public class ArmorStandDisplayItem implements DisplayItem {
this.originalItemStack.setAmount(1);
}
@Override
public boolean checkIsShopEntity(@NotNull Entity entity) {
if (!(entity instanceof ArmorStand))
return false;
return DisplayItem.checkIsGuardItemStack(((ArmorStand) entity).getItemInHand());
}
@Override
public void spawn() {
if (shop.getLocation().getWorld() == null) {
@@ -77,6 +88,30 @@ public class ArmorStandDisplayItem implements DisplayItem {
Util.debugLog("Spawned a new ArmorStand DisplayItem for a shop " + shop.getLocation().toString());
}
@Override
public boolean removeDupe() {
if (this.armorStand == null) {
Util.debugLog("Warning: Trying to removeDupe for a null display shop.");
return false;
}
boolean removed = false;
for (Entity entity : armorStand.getNearbyEntities(1, 1, 1)) {
if (!(entity instanceof ArmorStand))
continue;
ArmorStand eArmorStand = (ArmorStand) entity;
if (!eArmorStand.getUniqueId().equals(this.armorStand.getUniqueId())) {
if (DisplayItem.checkIsTargetShopDisplay(eArmorStand.getItemInHand(), this.shop)) {
Util.debugLog("Removing dupes ArmorEntity " + eArmorStand.getUniqueId().toString() + " at " + eArmorStand
.getLocation().toString());
entity.remove();
removed = true;
}
}
}
return removed;
}
@Override
public void safeGuard(@NotNull Entity entity) {
if (!(entity instanceof ArmorStand)) {
@@ -90,11 +125,15 @@ public class ArmorStandDisplayItem implements DisplayItem {
Util.debugLog("Successfully safeGuard ArmorStand: " + armorStand.getLocation().toString());
}
private void setPoseForArmorStand() {
if (this.originalItemStack.getType().isBlock())
this.armorStand.setRightArmPose(new EulerAngle(-0.2, 0, 0));
else
this.armorStand.setRightArmPose(new EulerAngle(-89.5, 0, 0));
@Override
public void respawn() {
remove();
spawn();
}
@Override
public Entity getDisplay() {
return this.armorStand;
}
@Override
@@ -110,17 +149,6 @@ public class ArmorStandDisplayItem implements DisplayItem {
Bukkit.getPluginManager().callEvent(shopDisplayItemDespawnEvent);
}
@Override
public void respawn() {
remove();
spawn();
}
@Override
public Entity getDisplay() {
return this.armorStand;
}
@Override
public Location getDisplayLocation() {
BlockFace containerBlockFace = BlockFace.NORTH; //Set default vaule
@@ -182,6 +210,13 @@ public class ArmorStandDisplayItem implements DisplayItem {
return asloc;
}
private void setPoseForArmorStand() {
if (this.originalItemStack.getType().isBlock())
this.armorStand.setRightArmPose(new EulerAngle(-0.2, 0, 0));
else
this.armorStand.setRightArmPose(new EulerAngle(-89.5, 0, 0));
}
@Override
public boolean checkDisplayIsMoved() {
if (this.armorStand == null)
@@ -196,37 +231,6 @@ public class ArmorStandDisplayItem implements DisplayItem {
return !this.armorStand.isValid() || this.armorStand.isDead();
}
@Override
public boolean checkIsShopEntity(@NotNull Entity entity) {
if (!(entity instanceof ArmorStand))
return false;
return DisplayItem.checkIsGuardItemStack(((ArmorStand) entity).getItemInHand());
}
@Override
public boolean removeDupe() {
if (this.armorStand == null) {
Util.debugLog("Warning: Trying to removeDupe for a null display shop.");
return false;
}
boolean removed = false;
for (Entity entity : armorStand.getNearbyEntities(1, 1, 1)) {
if (!(entity instanceof ArmorStand))
continue;
ArmorStand eArmorStand = (ArmorStand) entity;
if (!eArmorStand.getUniqueId().equals(this.armorStand.getUniqueId())) {
if (DisplayItem.checkIsTargetShopDisplay(eArmorStand.getItemInHand(), this.shop)) {
Util.debugLog("Removing dupes ArmorEntity " + eArmorStand.getUniqueId().toString() + " at " + eArmorStand
.getLocation().toString());
entity.remove();
removed = true;
}
}
}
return removed;
}
@Override
public void fixDisplayMoved() {
for (Entity entity : this.shop.getLocation().getWorld().getEntities()) {
@@ -253,9 +257,4 @@ public class ArmorStandDisplayItem implements DisplayItem {
return false;
return this.armorStand.isValid();
}
private static boolean isTool(Material material) {
String nlc = material.name().toLowerCase();
return nlc.contains("sword") || nlc.contains("shovel") || nlc.contains("axe");
}
}
@@ -34,26 +34,15 @@ import org.maxgamer.quickshop.Util.Util;
@EqualsAndHashCode
@ToString
public class ContainerShop implements Shop {
private Location loc;
private double price;
private ShopModerator moderator;
private ItemStack item;
private DisplayItem displayItem;
private boolean unlimited;
private ShopType shopType;
private QuickShop plugin;
@EqualsAndHashCode.Exclude private boolean isLoaded = false;
/**
* Returns a clone of this shop. References to the same display item,
* itemstack, location and owner as this shop does. Do not modify them or
* you will modify this shop.
* <p>
* **NOT A DEEP CLONE**
*/
public ContainerShop clone() {
return new ContainerShop(this);
}
private ItemStack item;
private Location loc;
private ShopModerator moderator;
private QuickShop plugin;
private double price;
private ShopType shopType;
private boolean unlimited;
private ContainerShop(@NotNull ContainerShop s) {
this.displayItem = s.displayItem;
@@ -110,6 +99,16 @@ public class ContainerShop implements Shop {
}
@Override
public boolean addStaff(@NotNull UUID player) {
boolean result = this.moderator.addStaff(player);
update();
if (result == false)
return result;
Bukkit.getPluginManager().callEvent(new ShopModeratorChangedEvent(this, this.moderator));
return result;
}
/**
* Returns the number of items this shop has in stock.
*
@@ -142,47 +141,6 @@ public class ContainerShop implements Shop {
return plugin.getItemMatcher().matches(this.item, item);
}
/**
* Returns the shop that shares it's inventory with this one.
*
* @return the shop that shares it's inventory with this one. Will return
* null if this shop is not attached to another.
*/
public ContainerShop getAttachedShop() {
Block c = Util.getSecondHalf(this.getLocation().getBlock());
if (c == null)
return null;
Shop shop = plugin.getShopManager().getShop(c.getLocation());
return shop == null ? null : (ContainerShop) shop;
}
/**
* Returns true if this shop is a double chest, and the other half is
* selling/buying the same as this is buying/selling.
*
* @return true if this shop is a double chest, and the other half is
* selling/buying the same as this is buying/selling.
*/
public boolean isDoubleShop() {
ContainerShop nextTo = this.getAttachedShop();
if (nextTo == null) {
return false;
}
if (nextTo.matches(this.getItem())) {
// They're both trading the same item
if (this.getShopType() == nextTo.getShopType()) {
// They're both buying or both selling => Not a double shop,
// just two shops.
return false;
} else {
// One is buying, one is selling.
return true;
}
} else {
return false;
}
}
/**
* @return The location of the shops chest
*/
@@ -209,13 +167,6 @@ public class ContainerShop implements Shop {
update();
}
/**
* @return The ItemStack type of this shop
*/
public Material getMaterial() {
return this.item.getType();
}
/**
* Upates the shop into the database.
*/
@@ -249,32 +200,6 @@ public class ContainerShop implements Shop {
return (short) ((Damageable) this.item.getItemMeta()).getDamage();
}
/**
* @return The chest this shop is based on.
*/
public Inventory getInventory() {
try {
if (loc.getBlock().getState().getType() == Material.ENDER_CHEST && plugin.getOpenInvPlugin() != null) {
OpenInv openInv = ((OpenInv) plugin.getOpenInvPlugin());
return openInv.getSpecialEnderChest(openInv.loadPlayer(Bukkit.getOfflinePlayer(this.moderator.getOwner()
)), Bukkit.getOfflinePlayer((this.moderator.getOwner())).isOnline()).getBukkitInventory();
}
} catch (Exception e) {
Util.debugLog(e.getMessage());
return null;
}
InventoryHolder container;
try {
container = (InventoryHolder) this.loc.getBlock().getState();
return container.getInventory();
} catch (Exception e) {
this.onUnload();
this.delete();
Util.debugLog("Inventory doesn't exist anymore: " + this + " shop was removed.");
return null;
}
}
/**
* @return The name of the player who owns the shop.
*/
@@ -282,48 +207,6 @@ public class ContainerShop implements Shop {
return this.moderator.getOwner();
}
/**
* @return The list of players who can manage the shop.
*/
@Override
public ArrayList<UUID> getStaffs() {
return this.moderator.getStaffs();
}
@Override
public boolean addStaff(@NotNull UUID player) {
boolean result = this.moderator.addStaff(player);
update();
if (result == false)
return result;
Bukkit.getPluginManager().callEvent(new ShopModeratorChangedEvent(this, this.moderator));
return result;
}
@Override
public boolean delStaff(@NotNull UUID player) {
boolean result = this.moderator.delStaff(player);
update();
if (result == false)
return result;
Bukkit.getPluginManager().callEvent(new ShopModeratorChangedEvent(this, this.moderator));
return result;
}
@Override
public void clearStaffs() {
this.moderator.clearStaffs();
Bukkit.getPluginManager().callEvent(new ShopModeratorChangedEvent(this, this.moderator));
update();
}
/**
* @return The enchantments the shop has on its items.
*/
public Map<Enchantment, Integer> getEnchants() {
return this.item.getItemMeta().getEnchants();
}
/**
* @return Returns a dummy itemstack of the item this shop is selling.
*/
@@ -483,6 +366,56 @@ public class ContainerShop implements Shop {
}
}
@Override
public void checkDisplay() {
Util.debugLog("Checking the display...");
if (!plugin.isDisplay())
return;
if (!this.isLoaded) {
Util.debugLog("Shop not loaded, skipping...");
return;
}
if (this.displayItem == null) {
Util.debugLog("Warning: DisplayItem is null, this shouldn't happend...");
Util.debugLog("Call from: " + Thread.currentThread().getStackTrace()[2].getClassName() + "#" + Thread.currentThread()
.getStackTrace()[2].getMethodName() + "%" + Thread.currentThread().getStackTrace()[2].getLineNumber());
return;
}
if (!this.displayItem.isSpawned()) {
/* Not spawned yet. */
Util.debugLog("Target item not spawned, spawning...");
this.displayItem.spawn();
} else {
/* If not spawned, we didn't need check these, only check them when we need. */
if (this.displayItem.checkDisplayNeedRegen()) {
this.displayItem.fixDisplayNeedRegen();
} else {/* If display was regened, we didn't need check it moved, performance! */
if (this.displayItem.checkDisplayIsMoved())
this.displayItem.fixDisplayMoved();
}
}
/* Dupe is always need check, if enabled display */
if (plugin.isDisplay())
this.displayItem.removeDupe();
}
@Override
public void clearStaffs() {
this.moderator.clearStaffs();
Bukkit.getPluginManager().callEvent(new ShopModeratorChangedEvent(this, this.moderator));
update();
}
@Override
public boolean delStaff(@NotNull UUID player) {
boolean result = this.moderator.delStaff(player);
update();
if (result == false)
return result;
Bukkit.getPluginManager().callEvent(new ShopModeratorChangedEvent(this, this.moderator));
return result;
}
/**
* Changes the owner of this shop to the given player.
*
@@ -495,6 +428,52 @@ public class ContainerShop implements Shop {
update();
}
/**
* @return The list of players who can manage the shop.
*/
@Override
public ArrayList<UUID> getStaffs() {
return this.moderator.getStaffs();
}
/**
* Returns a clone of this shop. References to the same display item,
* itemstack, location and owner as this shop does. Do not modify them or
* you will modify this shop.
* <p>
* **NOT A DEEP CLONE**
*/
public ContainerShop clone() {
return new ContainerShop(this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("Shop " + (loc.getWorld() == null ?
"unloaded world" :
loc.getWorld().getName()) + "(" + loc.getBlockX() + ", " + loc.getBlockY() + ", " + loc.getBlockZ() + ")");
sb.append(" Owner: " + this.ownerName() + " - " + getOwner().toString());
if (isUnlimited())
sb.append(" Unlimited: true");
sb.append(" Price: " + getPrice());
sb.append(" Item: " + getItem().toString());
return sb.toString();
}
/**
* Returns the shop that shares it's inventory with this one.
*
* @return the shop that shares it's inventory with this one. Will return
* null if this shop is not attached to another.
*/
public ContainerShop getAttachedShop() {
Block c = Util.getSecondHalf(this.getLocation().getBlock());
if (c == null)
return null;
Shop shop = plugin.getShopManager().getShop(c.getLocation());
return shop == null ? null : (ContainerShop) shop;
}
/**
* Returns the display item associated with this shop.
*
@@ -504,6 +483,77 @@ public class ContainerShop implements Shop {
return this.displayItem;
}
/**
* @return The enchantments the shop has on its items.
*/
public Map<Enchantment, Integer> getEnchants() {
return this.item.getItemMeta().getEnchants();
}
/**
* @return The chest this shop is based on.
*/
public Inventory getInventory() {
try {
if (loc.getBlock().getState().getType() == Material.ENDER_CHEST && plugin.getOpenInvPlugin() != null) {
OpenInv openInv = ((OpenInv) plugin.getOpenInvPlugin());
return openInv.getSpecialEnderChest(openInv.loadPlayer(Bukkit.getOfflinePlayer(this.moderator.getOwner()
)), Bukkit.getOfflinePlayer((this.moderator.getOwner())).isOnline()).getBukkitInventory();
}
} catch (Exception e) {
Util.debugLog(e.getMessage());
return null;
}
InventoryHolder container;
try {
container = (InventoryHolder) this.loc.getBlock().getState();
return container.getInventory();
} catch (Exception e) {
this.onUnload();
this.delete();
Util.debugLog("Inventory doesn't exist anymore: " + this + " shop was removed.");
return null;
}
}
/**
* @return The ItemStack type of this shop
*/
public Material getMaterial() {
return this.item.getType();
}
/**
* Returns true if this shop is a double chest, and the other half is
* selling/buying the same as this is buying/selling.
*
* @return true if this shop is a double chest, and the other half is
* selling/buying the same as this is buying/selling.
*/
public boolean isDoubleShop() {
ContainerShop nextTo = this.getAttachedShop();
if (nextTo == null) {
return false;
}
if (nextTo.matches(this.getItem())) {
// They're both trading the same item
if (this.getShopType() == nextTo.getShopType()) {
// They're both buying or both selling => Not a double shop,
// just two shops.
return false;
} else {
// One is buying, one is selling.
return true;
}
} else {
return false;
}
}
public void setUnlimited(boolean unlimited) {
this.unlimited = unlimited;
this.setSignText();
@@ -770,19 +820,6 @@ public class ContainerShop implements Shop {
return name;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("Shop " + (loc.getWorld() == null ?
"unloaded world" :
loc.getWorld().getName()) + "(" + loc.getBlockX() + ", " + loc.getBlockY() + ", " + loc.getBlockZ() + ")");
sb.append(" Owner: " + this.ownerName() + " - " + getOwner().toString());
if (isUnlimited())
sb.append(" Unlimited: true");
sb.append(" Price: " + getPrice());
sb.append(" Item: " + getItem().toString());
return sb.toString();
}
@Override
public ShopModerator getModerator() {
return this.moderator.clone();
@@ -800,36 +837,4 @@ public class ContainerShop implements Shop {
return this.isLoaded;
}
@Override
public void checkDisplay() {
Util.debugLog("Checking the display...");
if (!plugin.isDisplay())
return;
if (!this.isLoaded) {
Util.debugLog("Shop not loaded, skipping...");
return;
}
if (this.displayItem == null) {
Util.debugLog("Warning: DisplayItem is null, this shouldn't happend...");
Util.debugLog("Call from: " + Thread.currentThread().getStackTrace()[2].getClassName() + "#" + Thread.currentThread()
.getStackTrace()[2].getMethodName() + "%" + Thread.currentThread().getStackTrace()[2].getLineNumber());
return;
}
if (!this.displayItem.isSpawned()) {
/* Not spawned yet. */
Util.debugLog("Target item not spawned, spawning...");
this.displayItem.spawn();
} else {
/* If not spawned, we didn't need check these, only check them when we need. */
if (this.displayItem.checkDisplayNeedRegen()) {
this.displayItem.fixDisplayNeedRegen();
} else {/* If display was regened, we didn't need check it moved, performance! */
if (this.displayItem.checkDisplayIsMoved())
this.displayItem.fixDisplayMoved();
}
}
/* Dupe is always need check, if enabled display */
if (plugin.isDisplay())
this.displayItem.removeDupe();
}
}
@@ -18,111 +18,6 @@ import org.maxgamer.quickshop.Util.Util;
* cannot be interacted with.
*/
public interface DisplayItem {
/**
* Spawn new Displays
*/
void spawn();
/**
* Respawn the displays, if it not exist, it will spawn new one.
*/
void respawn();
/**
* Add the protect flags for entity or entity's hand item.
* Target entity will got protect by QuickShop
*
* @param entity Target entity
*/
void safeGuard(Entity entity);
/**
* Check target Entity is or not a QuickShop display Entity.
* @param entity Target entity
* @return Is or not
*/
boolean checkIsShopEntity(Entity entity);
/**
* Remove this shop's display in the whole world.(Not whole server)
* @return Success
*/
boolean removeDupe();
/**
* Remove the display entity.
*/
void remove();
/**
* Get display should at location.
* Not display current location.
* @return Should at
*/
Location getDisplayLocation();
/**
* Get the display entity
* @return Target entity
*/
Entity getDisplay();
/**
* Check the display is or not moved.
* @return Moved
*/
boolean checkDisplayIsMoved();
/**
* Check the display is or not need respawn
* @return Need
*/
boolean checkDisplayNeedRegen();
/**
* Fix the display moved issue.
*/
void fixDisplayMoved();
/**
* Fix display need respawn issue.
*/
void fixDisplayNeedRegen();
/**
* Check the display is or not already spawned
*
* @return Spawned
*/
boolean isSpawned();
/**
* Create a new itemStack with protect flag.
* @param itemStack Old itemStack
* @param shop The shop
* @return New itemStack with protect flag.
*/
static ItemStack createGuardItemStack(@NotNull ItemStack itemStack, @NotNull Shop shop) {
itemStack = itemStack.clone();
itemStack.setAmount(1);
ItemMeta iMeta = itemStack.getItemMeta();
if (QuickShop.instance.getConfig().getBoolean("shop.display-item-use-name")) {
iMeta.setDisplayName("QuickShop DisplayItem");
}
java.util.List<String> lore = new ArrayList<String>();
Gson gson = new Gson();
ShopProtectionFlag shopProtectionFlag = new ShopProtectionFlag(shop.getLocation().toString(), Util
.serialize(shop.getItem()));
String protectFlag = gson.toJson(shopProtectionFlag);
for (int i = 0; i < 21; i++) {
lore.add(protectFlag); //Create 20 lines lore to make sure no stupid plugin accident remove mark.
}
iMeta.setLore(lore);
itemStack.setItemMeta(iMeta);
return itemStack;
}
/**
* Check the itemStack is contains protect flag.
* @param itemStack Target ItemStack
@@ -193,6 +88,109 @@ public interface DisplayItem {
return false;
}
/**
* Create a new itemStack with protect flag.
*
* @param itemStack Old itemStack
* @param shop The shop
* @return New itemStack with protect flag.
*/
static ItemStack createGuardItemStack(@NotNull ItemStack itemStack, @NotNull Shop shop) {
itemStack = itemStack.clone();
itemStack.setAmount(1);
ItemMeta iMeta = itemStack.getItemMeta();
if (QuickShop.instance.getConfig().getBoolean("shop.display-item-use-name")) {
iMeta.setDisplayName("QuickShop DisplayItem");
}
java.util.List<String> lore = new ArrayList<String>();
Gson gson = new Gson();
ShopProtectionFlag shopProtectionFlag = new ShopProtectionFlag(shop.getLocation().toString(), Util.serialize(itemStack));
String protectFlag = gson.toJson(shopProtectionFlag);
for (int i = 0; i < 21; i++) {
lore.add(protectFlag); //Create 20 lines lore to make sure no stupid plugin accident remove mark.
}
iMeta.setLore(lore);
itemStack.setItemMeta(iMeta);
return itemStack;
}
/**
* Check the display is or not moved.
*
* @return Moved
*/
boolean checkDisplayIsMoved();
/**
* Check the display is or not need respawn
*
* @return Need
*/
boolean checkDisplayNeedRegen();
/**
* Check target Entity is or not a QuickShop display Entity.
*
* @param entity Target entity
* @return Is or not
*/
boolean checkIsShopEntity(Entity entity);
/**
* Fix the display moved issue.
*/
void fixDisplayMoved();
/**
* Fix display need respawn issue.
*/
void fixDisplayNeedRegen();
/**
* Remove the display entity.
*/
void remove();
/**
* Remove this shop's display in the whole world.(Not whole server)
*
* @return Success
*/
boolean removeDupe();
/**
* Respawn the displays, if it not exist, it will spawn new one.
*/
void respawn();
/**
* Add the protect flags for entity or entity's hand item.
* Target entity will got protect by QuickShop
*
* @param entity Target entity
*/
void safeGuard(Entity entity);
/**
* Spawn new Displays
*/
void spawn();
/**
* Get the display entity
*
* @return Target entity
*/
Entity getDisplay();
/**
* Get display should at location.
* Not display current location.
*
* @return Should at
*/
Location getDisplayLocation();
/**
* Get plugin now is using which one DisplayType
* @return Using displayType.
@@ -201,4 +199,11 @@ public interface DisplayItem {
return DisplayType.fromID(QuickShop.instance.getConfig().getInt("shop.display-type"));
}
/**
* Check the display is or not already spawned
*
* @return Spawned
*/
boolean isSpawned();
}
@@ -4,12 +4,6 @@ import org.jetbrains.annotations.*;
public enum DisplayType {
UNKNOWN(-1), REALITEM(0), ARMORSTAND(1), VIRTUALITEM(2);
private int id;
DisplayType(int id) {
this.id = id;
}
public static DisplayType fromID(int id) {
for (DisplayType type : DisplayType.values()) {
if (type.id == id) {
@@ -23,10 +17,6 @@ public enum DisplayType {
return displayType.id;
}
public int toID() {
return id;
}
public static DisplayType typeIs(@Nullable DisplayItem displayItem) {
if (displayItem instanceof RealDisplayItem)
return REALITEM;
@@ -34,4 +24,14 @@ public enum DisplayType {
return ARMORSTAND;
return UNKNOWN;
}
private int id;
DisplayType(int id) {
this.id = id;
}
public int toID() {
return id;
}
}
@@ -12,10 +12,10 @@ import org.jetbrains.annotations.*;
@EqualsAndHashCode
@ToString
public class Info {
private Location loc;
private ShopAction action;
private ItemStack item;
private Block last;
private Location loc;
private Shop shop;
public Info(@NotNull Location loc, @NotNull ShopAction action, @Nullable ItemStack item, @Nullable Block last) {
@@ -63,11 +63,8 @@ public class Info {
return this.action;
}
/**
* @return Location loc, Get shop's location,
*/
public Location getLocation() {
return this.loc;
public void setAction(ShopAction action) {
this.action = action;
}
/*
@@ -82,8 +79,11 @@ public class Info {
return this.item;
}
public void setAction(ShopAction action) {
this.action = action;
/**
* @return Location loc, Get shop's location,
*/
public Location getLocation() {
return this.loc;
}
/**
@@ -23,8 +23,21 @@ import org.maxgamer.quickshop.Util.Util;
@ToString
public class InventoryPreview implements Listener {
private ItemStack itemStack;
public static boolean isPreviewItem(@Nullable ItemStack stack) {
if (stack == null)
return false;
if (!stack.hasItemMeta() || !stack.getItemMeta().hasLore())
return false;
List<String> lores = stack.getItemMeta().getLore();
for (String string : lores) {
if (string.equals("QuickShop GUI preview item")) {
return true;
}
}
return false;
}
private Inventory inventory;
private ItemStack itemStack;
private Player player;
/**
@@ -51,6 +64,15 @@ public class InventoryPreview implements Listener {
}
}
public void close() {
if (inventory == null)
return;
for (HumanEntity player : inventory.getViewers()) {
player.closeInventory();
}
inventory = null; // Destory
}
/**
* Open the preview GUI for player.
*/
@@ -76,27 +98,4 @@ public class InventoryPreview implements Listener {
}
player.openInventory(inventory);
}
public void close() {
if (inventory == null)
return;
for (HumanEntity player : inventory.getViewers()) {
player.closeInventory();
}
inventory = null; // Destory
}
public static boolean isPreviewItem(@Nullable ItemStack stack) {
if (stack == null)
return false;
if (!stack.hasItemMeta() || !stack.getItemMeta().hasLore())
return false;
List<String> lores = stack.getItemMeta().getLore();
for (String string : lores) {
if (string.equals("QuickShop GUI preview item")) {
return true;
}
}
return false;
}
}
@@ -17,11 +17,11 @@ import org.maxgamer.quickshop.Util.Util;
@ToString
public class RealDisplayItem implements DisplayItem {
private Shop shop;
private ItemStack originalItemStack;
private static QuickShop plugin = QuickShop.instance;
private ItemStack guardedIstack;
private Item item;
private static QuickShop plugin = QuickShop.instance;
private ItemStack originalItemStack;
private Shop shop;
/**
* ZZ Creates a new display item.
@@ -37,55 +37,48 @@ public class RealDisplayItem implements DisplayItem {
}
@Override
public void spawn() {
if (shop.getLocation().getWorld() == null) {
Util.debugLog("Canceled the displayItem spawning because the location in the world is null.");
return;
}
if (originalItemStack == null) {
Util.debugLog("Canceled the displayItem spawning because the ItemStack is null.");
return;
}
if (item != null && item.isValid() && !item.isDead()) {
Util.debugLog("Warning: Spawning the Dropped Item for DisplayItem when there is already an existing Dropped Item, May cause a duplicated Dropped Item!");
StackTraceElement[] traces = Thread.currentThread().getStackTrace();
for (StackTraceElement trace : traces) {
Util.debugLog(trace.getClassName() + "#" + trace.getMethodName() + "#" + trace.getLineNumber());
}
}
if (!Util.isDisplayAllowBlock(getDisplayLocation().getBlock().getType())) {
Util.debugLog("Can't spawn the displayItem because there is not an AIR block above the shopblock.");
return;
}
ShopDisplayItemSpawnEvent shopDisplayItemSpawnEvent = new ShopDisplayItemSpawnEvent(shop, originalItemStack, DisplayType.REALITEM);
Bukkit.getPluginManager().callEvent(shopDisplayItemSpawnEvent);
if (shopDisplayItemSpawnEvent.isCancelled()) {
Util.debugLog("Canceled the displayItem spawning because a plugin setCancelled the spawning event, usually this is a QuickShop Add on");
return;
}
this.item = this.shop.getLocation().getWorld().dropItem(getDisplayLocation(), originalItemStack);
this.item.setPickupDelay(Integer.MAX_VALUE);
this.item.setSilent(true);
this.item.setPortalCooldown(Integer.MAX_VALUE);
this.item.setVelocity(new Vector(0, 0.1, 0));
safeGuard(this.item);
Util.debugLog("Spawned new DisplayItem for shop " + shop.getLocation().toString());
public boolean checkDisplayIsMoved() {
if (this.item == null)
return false;
//return !this.item.getLocation().equals(getDisplayLocation());
/* We give 0.6 block to allow item drop on the chest, not floating on the air. */
if (!this.item.getLocation().getWorld().equals(getDisplayLocation().getWorld()))
return true;
return this.item.getLocation().distance(getDisplayLocation()) > 0.6;
}
@Override
public void safeGuard(@NotNull Entity entity) {
if (!(entity instanceof Item)) {
Util.debugLog("Failed to safeGuard " + entity.getLocation().toString() + ", cause target not a Item");
return;
public boolean checkDisplayNeedRegen() {
if (this.item == null)
return false;
return !this.item.isValid() || this.item.isDead();
}
@Override
public boolean checkIsShopEntity(@NotNull Entity entity) {
if (!(entity instanceof Item))
return false;
return DisplayItem.checkIsGuardItemStack(((Item) entity).getItemStack());
}
@Override
public void fixDisplayMoved() {
for (Entity entity : this.shop.getLocation().getWorld().getEntities()) {
if (!(entity instanceof Item))
continue;
Item eItem = (Item) entity;
if (eItem.getUniqueId().equals(this.item.getUniqueId())) {
Util.debugLog("Fixing moved Item displayItem " + eItem.getUniqueId().toString() + " at " + eItem
.getLocation().toString());
eItem.teleport(getDisplayLocation());
return;
}
}
Item item = (Item) entity;
//Set item protect in the armorstand's hand
this.guardedIstack = DisplayItem.createGuardItemStack(this.originalItemStack, this.shop);
item.setItemStack(this.guardedIstack);
Util.debugLog("Successfully safeGuard Item: " + item.getLocation().toString());
}
@Override
public void fixDisplayNeedRegen() {
respawn();
}
@Override
@@ -139,54 +132,66 @@ public class RealDisplayItem implements DisplayItem {
spawn();
}
@Override
public void safeGuard(@NotNull Entity entity) {
if (!(entity instanceof Item)) {
Util.debugLog("Failed to safeGuard " + entity.getLocation().toString() + ", cause target not a Item");
return;
}
Item item = (Item) entity;
//Set item protect in the armorstand's hand
this.guardedIstack = DisplayItem.createGuardItemStack(this.originalItemStack, this.shop);
item.setItemStack(this.guardedIstack);
Util.debugLog("Successfully safeGuard Item: " + item.getLocation().toString());
}
@Override
public void spawn() {
if (shop.getLocation().getWorld() == null) {
Util.debugLog("Canceled the displayItem spawning because the location in the world is null.");
return;
}
if (originalItemStack == null) {
Util.debugLog("Canceled the displayItem spawning because the ItemStack is null.");
return;
}
if (item != null && item.isValid() && !item.isDead()) {
Util.debugLog("Warning: Spawning the Dropped Item for DisplayItem when there is already an existing Dropped Item, May cause a duplicated Dropped Item!");
StackTraceElement[] traces = Thread.currentThread().getStackTrace();
for (StackTraceElement trace : traces) {
Util.debugLog(trace.getClassName() + "#" + trace.getMethodName() + "#" + trace.getLineNumber());
}
}
if (!Util.isDisplayAllowBlock(getDisplayLocation().getBlock().getType())) {
Util.debugLog("Can't spawn the displayItem because there is not an AIR block above the shopblock.");
return;
}
ShopDisplayItemSpawnEvent shopDisplayItemSpawnEvent = new ShopDisplayItemSpawnEvent(shop, originalItemStack, DisplayType.REALITEM);
Bukkit.getPluginManager().callEvent(shopDisplayItemSpawnEvent);
if (shopDisplayItemSpawnEvent.isCancelled()) {
Util.debugLog("Canceled the displayItem spawning because a plugin setCancelled the spawning event, usually this is a QuickShop Add on");
return;
}
this.item = this.shop.getLocation().getWorld().dropItem(getDisplayLocation(), originalItemStack);
this.item.setPickupDelay(Integer.MAX_VALUE);
this.item.setSilent(true);
this.item.setPortalCooldown(Integer.MAX_VALUE);
this.item.setVelocity(new Vector(0, 0.1, 0));
safeGuard(this.item);
Util.debugLog("Spawned new DisplayItem for shop " + shop.getLocation().toString());
}
@Override
public Entity getDisplay() {
return this.item;
}
@Override
public boolean checkIsShopEntity(@NotNull Entity entity) {
if (!(entity instanceof Item))
return false;
return DisplayItem.checkIsGuardItemStack(((Item) entity).getItemStack());
}
@Override
public boolean checkDisplayNeedRegen() {
if (this.item == null)
return false;
return !this.item.isValid() || this.item.isDead();
}
@Override
public boolean checkDisplayIsMoved() {
if (this.item == null)
return false;
//return !this.item.getLocation().equals(getDisplayLocation());
/* We give 0.6 block to allow item drop on the chest, not floating on the air. */
if (!this.item.getLocation().getWorld().equals(getDisplayLocation().getWorld()))
return true;
return this.item.getLocation().distance(getDisplayLocation()) > 0.6;
}
@Override
public void fixDisplayNeedRegen() {
respawn();
}
@Override
public void fixDisplayMoved() {
for (Entity entity : this.shop.getLocation().getWorld().getEntities()) {
if (!(entity instanceof Item))
continue;
Item eItem = (Item) entity;
if (eItem.getUniqueId().equals(this.item.getUniqueId())) {
Util.debugLog("Fixing moved Item displayItem " + eItem.getUniqueId().toString() + " at " + eItem
.getLocation().toString());
eItem.teleport(getDisplayLocation());
return;
}
}
public Location getDisplayLocation() {
return this.shop.getLocation().clone().add(0.5, 1.2, 0.5);
}
@Override
@@ -195,9 +200,4 @@ public class RealDisplayItem implements DisplayItem {
return false;
return this.item.isValid();
}
@Override
public Location getDisplayLocation() {
return this.shop.getLocation().clone().add(0.5, 1.2, 0.5);
}
}
@@ -11,6 +11,40 @@ import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public interface Shop {
/**
* Add x ItemStack to the shop inventory
*
* @param paramItemStack The ItemStack you want add
* @param paramInt How many you want add
*/
void add(ItemStack paramItemStack, int paramInt);
/**
* Add new staff to the moderators
*
* @param player New staff
* @return Success
*/
boolean addStaff(UUID player);
/**
* Execute buy action for player with x items.
*
* @param paramPlayer Target player
* @param paramInt How many buyed?
*/
void buy(Player paramPlayer, int paramInt);
/**
* Check the display location, and teleport, respawn if needs.
*/
void checkDisplay();
/**
* Empty moderators team.
*/
void clearStaffs();
/**
* Clone new shop object.
* Not a deep clone.
@@ -20,163 +54,11 @@ public interface Shop {
Shop clone();
/**
* Check the display location, and teleport, respawn if needs.
* Remove a staff from moderators
* @param player Staff
* @return Success
*/
void checkDisplay();
/**
* Get shop remaining stock.
* @return Remaining stock.
*/
int getRemainingStock();
/**
* Get shop remaining space.
* @return Remaining space.
*/
int getRemainingSpace();
/**
* Check the target ItemStack is matches with this shop's item.
* @param paramItemStack Target ItemStack.
* @return Matches
*/
boolean matches(ItemStack paramItemStack);
/**
* Get shop's location
* @return Shop's location
*/
Location getLocation();
/**
* Get shop's price
* @return Price
*/
double getPrice();
/**
* Set shop's new price
* @param paramDouble New price
*/
void setPrice(double paramDouble);
/**
* Update shop data to database
*/
void update();
/**
* Get shop's item durability, if have.
* @return Shop's item durability
*/
short getDurability();
/**
* Get shop's owner UUID
* @return Shop's owner UUID, can use Bukkit.getOfflinePlayer to convert to the OfflinePlayer.
*/
UUID getOwner();
/**
* Get shop item's ItemStack
* @return The shop's ItemStack
*/
ItemStack getItem();
/**
* Remove x ItemStack from the shop inventory
* @param paramItemStack Want removed ItemStack
* @param paramInt Want remove how many
*/
void remove(ItemStack paramItemStack, int paramInt);
/**
* Add x ItemStack to the shop inventory
* @param paramItemStack The ItemStack you want add
* @param paramInt How many you want add
*/
void add(ItemStack paramItemStack, int paramInt);
/**
* Execute sell action for player with x items.
* @param paramPlayer Target player
* @param paramInt How many sold?
*/
void sell(Player paramPlayer, int paramInt);
/**
* Execute buy action for player with x items.
* @param paramPlayer Target player
* @param paramInt How many buyed?
*/
void buy(Player paramPlayer, int paramInt);
/**
* Set new owner to the shop's owner
* @param paramString New owner UUID
*/
void setOwner(UUID paramString);
/**
* Set shop is or not Unlimited Mode (Admin Shop)
* @param paramBoolean status
*/
void setUnlimited(boolean paramBoolean);
/**
* Get shop is or not in Unlimited Mode (Admin Shop)
* @return yes or not
*/
boolean isUnlimited();
/**
* Get shop type
* @return shop type
*/
ShopType getShopType();
/**
* Get shop is or not in buying mode
* @return yes or no
*/
boolean isBuying();
/**
* Get shop is or not in selling mode
* @return yes or no
*/
boolean isSelling();
/**
* Set new shop type for this shop
* @param paramShopType New shop type
*/
void setShopType(ShopType paramShopType);
/**
* Generate new sign texts on shop's sign.
*/
void setSignText();
/**
* Set texts on shop's sign
* @param paramArrayOfString The texts you want set
*/
void setSignText(String[] paramArrayOfString);
/**
* Get shop signs, may have multi signs
* @return Signs for the shop
*/
List<Sign> getSigns();
/**
* Check shop is or not attacked the target block
* @param paramBlock Target block
* @return isAttached
*/
boolean isAttached(Block paramBlock);
boolean delStaff(UUID player);
/**
* Delete shop from ram, and database.
@@ -190,32 +72,96 @@ public interface Shop {
void delete(boolean paramBoolean);
/**
* Shop is valid
* @return status
* Check shop is or not attacked the target block
*
* @param paramBlock Target block
* @return isAttached
*/
boolean isValid();
boolean isAttached(Block paramBlock);
/**
* Unload shop from world
* Check the target ItemStack is matches with this shop's item.
* @param paramItemStack Target ItemStack.
* @return Matches
*/
void onUnload();
/**
* Load shop to the world
*/
void onLoad();
boolean matches(ItemStack paramItemStack);
/**
* Execute codes when player click the shop will did things
*/
void onClick();
/**
* Load shop to the world
*/
void onLoad();
/**
* Unload shop from world
*/
void onUnload();
/**
* Get shop's owner name, it will return owner name or Admin Shop(i18n) when it is unlimited
* @return owner name
*/
String ownerName();
/**
* Remove x ItemStack from the shop inventory
* @param paramItemStack Want removed ItemStack
* @param paramInt Want remove how many
*/
void remove(ItemStack paramItemStack, int paramInt);
/**
* Execute sell action for player with x items.
* @param paramPlayer Target player
* @param paramInt How many sold?
*/
void sell(Player paramPlayer, int paramInt);
/**
* Generate new sign texts on shop's sign.
*/
void setSignText();
/**
* Update shop data to database
*/
void update();
/**
* Set new shop type for this shop
* @param paramShopType New shop type
*/
void setShopType(ShopType paramShopType);
/**
* Get shop's item durability, if have.
* @return Shop's item durability
*/
short getDurability();
/**
* Get shop item's ItemStack
*
* @return The shop's ItemStack
*/
ItemStack getItem();
/**
* Set texts on shop's sign
* @param paramArrayOfString The texts you want set
*/
void setSignText(String[] paramArrayOfString);
/**
* Get shop's location
* @return Shop's location
*/
Location getLocation();
/**
* Return this shop's moderators
* @return Shop moderators
@@ -229,35 +175,104 @@ public interface Shop {
void setModerator(ShopModerator shopModerator);
/**
* Add new staff to the moderators
* @param player New staff
* @return Success
* Get shop's owner UUID
*
* @return Shop's owner UUID, can use Bukkit.getOfflinePlayer to convert to the OfflinePlayer.
*/
boolean addStaff(UUID player);
UUID getOwner();
/**
* Remove a staff from moderators
* @param player Staff
* @return Success
* Set new owner to the shop's owner
*
* @param paramString New owner UUID
*/
boolean delStaff(UUID player);
void setOwner(UUID paramString);
/**
* Empty moderators team.
* Get shop's price
*
* @return Price
*/
void clearStaffs();
double getPrice();
/**
* Get this container shop is loaded or unloaded.
* @return Loaded
* Set shop's new price
* @param paramDouble New price
*/
boolean isLoaded();
void setPrice(double paramDouble);
/**
* Get shop remaining space.
* @return Remaining space.
*/
int getRemainingSpace();
/**
* Get shop remaining stock.
* @return Remaining stock.
*/
int getRemainingStock();
/**
* Get shop type
* @return shop type
*/
ShopType getShopType();
/**
* Get shop signs, may have multi signs
*
* @return Signs for the shop
*/
List<Sign> getSigns();
/**
* Directly get all staffs.
* @return staffs
*/
*/
ArrayList<UUID> getStaffs();
/**
* Get shop is or not in buying mode
*
* @return yes or no
*/
boolean isBuying();
/**
* Get this container shop is loaded or unloaded.
*
* @return Loaded
*/
boolean isLoaded();
/**
* Get shop is or not in selling mode
*
* @return yes or no
*/
boolean isSelling();
/**
* Get shop is or not in Unlimited Mode (Admin Shop)
*
* @return yes or not
*/
boolean isUnlimited();
/**
* Set shop is or not Unlimited Mode (Admin Shop)
*
* @param paramBoolean status
*/
void setUnlimited(boolean paramBoolean);
/**
* Shop is valid
*
* @return status
*/
boolean isValid();
}
@@ -21,12 +21,12 @@ import org.maxgamer.quickshop.Util.Util;
* A class allow plugin load shops fast and simply.
*/
public class ShopLoader {
private QuickShop plugin;
private int errors;
final private ArrayList<Long> loadTimes = new ArrayList<>();
private int totalLoaded = 0;
private int errors;
private int loadAfterChunkLoaded = 0;
private int loadAfterWorldLoaded = 0;
private QuickShop plugin;
private int totalLoaded = 0;
/**
* The shop load allow plugin load shops fast and simply.
@@ -37,9 +37,41 @@ public class ShopLoader {
this.plugin = plugin;
}
public void loadShops() {
loadShops(null);
private void exceptionHandler(@NotNull Exception ex, @Nullable Location shopLocation) {
errors++;
Logger logger = plugin.getLogger();
logger.warning("##########FAILED TO LOAD SHOP##########");
logger.warning(" >> Error Info:");
logger.warning(ex.getMessage());
logger.warning(" >> Error Trace");
ex.printStackTrace();
logger.warning(" >> Target Location Info");
logger.warning("Location: " + ((shopLocation == null) ? "NULL" : shopLocation.toString()));
logger.warning("Block: " + ((shopLocation == null) ? "NULL" : shopLocation.getBlock().getType().name()));
logger.warning(" >> Database Info");
try {
logger.warning("Connected: " + String.valueOf(plugin.getDatabase().getConnection().isClosed()));
} catch (SQLException | NullPointerException e) {
logger.warning("Connected: " + "FALSE - Failed to load status.");
}
try {
logger.warning("Readonly: " + String.valueOf(plugin.getDatabase().getConnection().isReadOnly()));
} catch (SQLException | NullPointerException e) {
logger.warning("Readonly: " + "FALSE - Failed to load status.");
}
try {
logger.warning("ClientInfo: " + String.valueOf(plugin.getDatabase().getConnection().getClientInfo().toString()));
} catch (SQLException | NullPointerException e) {
logger.warning("ClientInfo: " + "FALSE - Failed to load status.");
}
logger.warning("#######################################");
if (errors > 10)
logger.severe("QuickShop detected too many errors when loading shops, you should backup your shop database and ask the developer for help");
}
/**
* Load all shops
* @param worldName The world name
@@ -105,6 +137,10 @@ public class ShopLoader {
}
}
public void loadShops() {
loadShops(null);
}
private Long mean(Long[] m) {
long sum = 0;
for (Long aM : m) {
@@ -115,13 +151,6 @@ public class ShopLoader {
return sum / m.length;
}
private void singleShopLoaded(@NotNull Timer singleShopLoadTimer) {
totalLoaded++;
long singleShopLoadTime = singleShopLoadTimer.endTimer();
loadTimes.add(singleShopLoadTime);
Util.debugLog("Loaded shop used time " + singleShopLoadTime + "ms");
}
private boolean shopNullCheck(@Nullable Shop shop) {
if (shop == null) {
Util.debugLog("Shop Object is null");
@@ -150,85 +179,26 @@ public class ShopLoader {
return false;
}
private void exceptionHandler(@NotNull Exception ex, @Nullable Location shopLocation) {
errors++;
Logger logger = plugin.getLogger();
logger.warning("##########FAILED TO LOAD SHOP##########");
logger.warning(" >> Error Info:");
logger.warning(ex.getMessage());
logger.warning(" >> Error Trace");
ex.printStackTrace();
logger.warning(" >> Target Location Info");
logger.warning("Location: " + ((shopLocation == null) ? "NULL" : shopLocation.toString()));
logger.warning("Block: " + ((shopLocation == null) ? "NULL" : shopLocation.getBlock().getType().name()));
logger.warning(" >> Database Info");
try {
logger.warning("Connected: " + String.valueOf(plugin.getDatabase().getConnection().isClosed()));
} catch (SQLException | NullPointerException e) {
logger.warning("Connected: " + "FALSE - Failed to load status.");
}
try {
logger.warning("Readonly: " + String.valueOf(plugin.getDatabase().getConnection().isReadOnly()));
} catch (SQLException | NullPointerException e) {
logger.warning("Readonly: " + "FALSE - Failed to load status.");
}
try {
logger.warning("ClientInfo: " + String.valueOf(plugin.getDatabase().getConnection().getClientInfo().toString()));
} catch (SQLException | NullPointerException e) {
logger.warning("ClientInfo: " + "FALSE - Failed to load status.");
}
logger.warning("#######################################");
if (errors > 10)
logger.severe("QuickShop detected too many errors when loading shops, you should backup your shop database and ask the developer for help");
}
@Getter
@Setter
class ShopDatabaseInfoOrigin {
private int x;
private int y;
private int z;
private String world;
private String item;
private String moderators;
private double price;
private int type;
private boolean unlimited;
ShopDatabaseInfoOrigin(ResultSet rs) {
try {
this.x = rs.getInt("x");
this.y = rs.getInt("y");
this.z = rs.getInt("z");
this.world = rs.getString("world");
this.item = rs.getString("itemConfig");
this.moderators = rs.getString("owner");
this.price = rs.getDouble("price");
this.type = rs.getInt("type");
this.unlimited = rs.getBoolean("unlimited");
} catch (SQLException sqlex) {
exceptionHandler(sqlex, null);
}
}
private void singleShopLoaded(@NotNull Timer singleShopLoadTimer) {
totalLoaded++;
long singleShopLoadTime = singleShopLoadTimer.endTimer();
loadTimes.add(singleShopLoadTime);
Util.debugLog("Loaded shop used time " + singleShopLoadTime + "ms");
}
@Getter
@Setter
class ShopDatabaseInfo {
private ItemStack item;
private Location location;
private ShopModerator moderators;
private double price;
private ShopType type;
private boolean unlimited;
private World world;
private int x;
private int y;
private int z;
private double price;
private boolean unlimited;
private ShopType type;
private World world;
private ItemStack item;
private ShopModerator moderators;
private Location location;
ShopDatabaseInfo(ShopDatabaseInfoOrigin origin) {
try {
@@ -282,4 +252,35 @@ public class ShopLoader {
return shopModerator;
}
}
@Getter
@Setter
class ShopDatabaseInfoOrigin {
private String item;
private String moderators;
private double price;
private int type;
private boolean unlimited;
private String world;
private int x;
private int y;
private int z;
ShopDatabaseInfoOrigin(ResultSet rs) {
try {
this.x = rs.getInt("x");
this.y = rs.getInt("y");
this.z = rs.getInt("z");
this.world = rs.getString("world");
this.item = rs.getString("itemConfig");
this.moderators = rs.getString("owner");
this.price = rs.getDouble("price");
this.type = rs.getInt("type");
this.unlimited = rs.getBoolean("unlimited");
} catch (SQLException sqlex) {
exceptionHandler(sqlex, null);
}
}
}
}
@@ -33,378 +33,15 @@ import org.maxgamer.quickshop.Util.Util;
*/
@SuppressWarnings("WeakerAccess")
public class ShopManager {
private QuickShop plugin;
private HashMap<UUID, Info> actions = new HashMap<UUID, Info>();
private HashMap<String, HashMap<ShopChunk, HashMap<Location, Shop>>> shops = new HashMap<>();
final private static ItemStack AIR = new ItemStack(Material.AIR);
private HashMap<UUID, Info> actions = new HashMap<UUID, Info>();
private QuickShop plugin;
private HashMap<String, HashMap<ShopChunk, HashMap<Location, Shop>>> shops = new HashMap<>();
public ShopManager(@NotNull QuickShop plugin) {
this.plugin = plugin;
}
/**
* @return Returns the HashMap. Info contains what
* their last question etc was.
*/
public HashMap<UUID, Info> getActions() {
return this.actions;
}
/**
* Create a shop use Shop and Info object.
*
* @param shop The shop object
* @param info The info object
*/
public void createShop(@NotNull Shop shop, @NotNull Info info) {
ShopCreateEvent ssShopCreateEvent = new ShopCreateEvent(shop, Bukkit.getPlayer(shop.getOwner()));
Bukkit.getPluginManager().callEvent(ssShopCreateEvent);
if (ssShopCreateEvent.isCancelled()) {
return;
}
Location loc = shop.getLocation();
ItemStack item = shop.getItem();
try {
// Write it to the database
plugin.getDatabaseHelper().createShop(plugin.getDatabase(), ShopModerator.serialize(shop.getModerator()), shop
.getPrice(), item, (shop.isUnlimited() ?
1 :
0), shop.getShopType().toID(), loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
// Add it to the world
addShop(loc.getWorld().getName(), shop);
} catch (SQLException error) {
plugin.getLogger().warning("SQLException detected, trying to auto fix the database...");
boolean backupSuccess = Util.backupDatabase();
try {
if (backupSuccess) {
plugin.getDatabaseHelper().removeShop(plugin.getDatabase(), loc.getBlockX(), loc.getBlockY(), loc
.getBlockZ(), loc.getWorld().getName());
} else {
plugin.getLogger().warning("Failed to backup the database, all changes will revert after a reboot.");
}
} catch (SQLException error2) {
//Failed removing
plugin.getLogger().warning("Failed to autofix the database, all changes will revert after a reboot.");
error.printStackTrace();
error2.printStackTrace();
}
}
//Create sign
if (info.getSignBlock() != null && plugin.getConfig().getBoolean("shop.auto-sign")) {
if (!Util.isAir(info.getSignBlock().getType())) {
Util.debugLog("Sign cannot placed cause no enough space(Not air block)");
return;
}
boolean isWaterLogged = false;
if (info.getSignBlock().getType() == Material.WATER)
isWaterLogged = true;
info.getSignBlock().setType(Util.getSignMaterial());
BlockState bs = info.getSignBlock().getState();
if (isWaterLogged) {
if (bs.getBlockData() instanceof Waterlogged) {
Waterlogged waterable = (Waterlogged) bs.getBlockData();
waterable.setWaterlogged(true); // Looks like sign directly put in water
}
}
if (bs.getBlockData() instanceof WallSign) {
org.bukkit.block.data.type.WallSign signBlockDataType = (org.bukkit.block.data.type.WallSign) bs.getBlockData();
BlockFace bf = info.getLocation().getBlock().getFace(info.getSignBlock());
if (bf != null) {
signBlockDataType.setFacing(bf);
bs.setBlockData(signBlockDataType);
}
} else {
plugin.getLogger().warning("Sign material " + bs.getType()
.name() + " not a WallSign, make sure you using correct sign material.");
}
bs.update(true);
shop.setSignText();
}
}
/**
* Loads the given shop into storage. This method is used for loading data
* from the database. Do not use this method to create a shop.
*
* @param world The world the shop is in
* @param shop The shop to load
*/
public void loadShop(@NotNull String world, @NotNull Shop shop) {
this.addShop(world, shop);
}
/**
* Returns a hashmap of World - Chunk - Shop
*
* @return a hashmap of World - Chunk - Shop
*/
public HashMap<String, HashMap<ShopChunk, HashMap<Location, Shop>>> getShops() {
return this.shops;
}
/**
* Returns a hashmap of Chunk - Shop
*
* @param world The name of the world (case sensitive) to get the list of
* shops from
* @return a hashmap of Chunk - Shop
*/
public HashMap<ShopChunk, HashMap<Location, Shop>> getShops(@NotNull String world) {
return this.shops.get(world);
}
/**
* Returns a hashmap of Shops
*
* @param c The chunk to search. Referencing doesn't matter, only
* coordinates and world are used.
* @return Shops
*/
public HashMap<Location, Shop> getShops(@NotNull Chunk c) {
// long start = System.nanoTime();
return getShops(c.getWorld().getName(), c.getX(), c.getZ());
// long end = System.nanoTime();
// plugin.getLogger().log(Level.WARNING, "Chunk lookup in " + ((end - start)/1000000.0) +
// "ms.");
}
public HashMap<Location, Shop> getShops(String world, int chunkX, int chunkZ) {
HashMap<ShopChunk, HashMap<Location, Shop>> inWorld = this.getShops(world);
if (inWorld == null) {
return null;
}
ShopChunk shopChunk = new ShopChunk(world, chunkX, chunkZ);
return inWorld.get(shopChunk);
}
/**
* Gets a shop in a specific location
*
* @param loc The location to get the shop from
* @return The shop at that location
*/
public Shop getShop(@NotNull Location loc) {
HashMap<Location, Shop> inChunk = getShops(loc.getChunk());
if (inChunk == null) {
return null;
}
// We can do this because WorldListener updates the world reference so
// the world in loc is the same as world in inChunk.get(loc)
return inChunk.get(loc);
}
/**
* Adds a shop to the world. Does NOT require the chunk or world to be loaded
* Call shop.onLoad by yourself
*
* @param world The name of the world
* @param shop The shop to add
*/
public void addShop(@NotNull String world, @NotNull Shop shop) {
HashMap<ShopChunk, HashMap<Location, Shop>> inWorld = this.getShops()
.computeIfAbsent(world, k -> new HashMap<>(3));
// There's no world storage yet. We need to create that hashmap.
// Put it in the data universe
// Calculate the chunks coordinates. These are 1,2,3 for each chunk, NOT
// location rounded to the nearest 16.
int x = (int) Math.floor((shop.getLocation().getBlockX()) / 16.0);
int z = (int) Math.floor((shop.getLocation().getBlockZ()) / 16.0);
// Get the chunk set from the world info
ShopChunk shopChunk = new ShopChunk(world, x, z);
HashMap<Location, Shop> inChunk = inWorld.computeIfAbsent(shopChunk, k -> new HashMap<>(1));
// That chunk data hasn't been created yet - Create it!
// Put it in the world
// Put the shop in its location in the chunk list.
inChunk.put(shop.getLocation(), shop);
// shop.onLoad();
}
/**
* Removes a shop from the world. Does NOT remove it from the database. *
* REQUIRES * the world to be loaded
* Call shop.onUnload by your self.
*
* @param shop The shop to remove
*/
public void removeShop(@NotNull Shop shop) {
// shop.onUnload();
Location loc = shop.getLocation();
String world = loc.getWorld().getName();
HashMap<ShopChunk, HashMap<Location, Shop>> inWorld = this.getShops().get(world);
int x = (int) Math.floor((shop.getLocation().getBlockX()) / 16.0);
int z = (int) Math.floor((shop.getLocation().getBlockZ()) / 16.0);
ShopChunk shopChunk = new ShopChunk(world, x, z);
HashMap<Location, Shop> inChunk = inWorld.get(shopChunk);
if (inChunk == null)
return;
inChunk.remove(loc);
// shop.onUnload();
}
/**
* Removes all shops from memory and the world. Does not delete them from
* the database. Call this on plugin disable ONLY.
*/
public void clear() {
if (plugin.isDisplay()) {
for (World world : Bukkit.getWorlds()) {
for (Chunk chunk : world.getLoadedChunks()) {
HashMap<Location, Shop> inChunk = this.getShops(chunk);
if (inChunk == null || inChunk.isEmpty())
continue;
for (Shop shop : inChunk.values()) {
shop.onUnload();
}
}
}
}
this.actions.clear();
this.shops.clear();
}
/**
* Checks other plugins to make sure they can use the chest they're making a
* shop.
*
* @param p The player to check
* @param b The block to check
* @param bf The blockface to check
* @return True if they're allowed to place a shop there.
*/
public boolean canBuildShop(@NotNull Player p, @NotNull Block b, @NotNull BlockFace bf) {
RegisteredListener openInvRegisteredListener = null; // added for compatibility reasons with OpenInv - see https://github.com/KaiKikuchi/QuickShop/issues/139
// try {
// if (plugin.openInvPlugin != null) {
// for (RegisteredListener listener : PlayerInteractEvent.getHandlerList().getRegisteredListeners()) {
// if (listener.getPlugin().getName().equals(plugin.openInvPlugin.getName())) {
// openInvRegisteredListener = listener;
// PlayerInteractEvent.getHandlerList().unregister(listener);
// break;
// }
// }
// }
try {
plugin.getCompatibilityTool().toggleInteractListeners(false);
if (plugin.isLimit()) {
int owned = 0;
if (!plugin.getConfig().getBoolean("limits.old-algorithm")) {
for (HashMap<ShopChunk, HashMap<Location, Shop>> shopmap : getShops().values()) {
for (HashMap<Location, Shop> shopLocs : shopmap.values()) {
for (Shop shop : shopLocs.values()) {
if (shop.getOwner().equals(p.getUniqueId()) && !shop.isUnlimited()) {
owned++;
}
}
}
}
} else {
Iterator<Shop> it = getShopIterator();
while (it.hasNext()) {
if (it.next().getOwner().equals(p.getUniqueId())) {
owned++;
}
}
}
int max = plugin.getShopLimit(p);
if (owned + 1 > max) {
//p.sendMessage(ChatColor.RED + "You have already created a maximum of " + owned + "/" + max + " shops!");
p.sendMessage(MsgUtil.getMessage("reached-maximum-can-create", String.valueOf(owned), String.valueOf(max)));
return false;
}
}
if (!plugin.getPermissionChecker().canBuild(p, b, false)) {
Util.debugLog("PermissionChecker canceled shop creation");
return false;
}
ShopPreCreateEvent spce = new ShopPreCreateEvent(p, b.getLocation());
Bukkit.getPluginManager().callEvent(spce);
if (spce.isCancelled()) {
return false;
}
} finally {
// if (plugin.openInvPlugin != null && openInvRegisteredListener != null) {
// PlayerInteractEvent.getHandlerList().register(openInvRegisteredListener);
// }
plugin.getCompatibilityTool().toggleInteractListeners(true);
}
return true;
}
public void handleChat(@NotNull Player p, @NotNull String msg) {
handleChat(p, msg, false);
}
public void handleChat(@NotNull Player p, @NotNull String msg, boolean bypassProtectionChecks) {
final String message = ChatColor.stripColor(msg);
// Use from the main thread, because Bukkit hates life
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> {
HashMap<UUID, Info> actions = getActions();
// They wanted to do something.
Info info = actions.remove(p.getUniqueId());
if (info == null)
return; // multithreaded means this can happen
if (info.getLocation().getWorld() != p.getLocation().getWorld()) {
p.sendMessage(MsgUtil.getMessage("shop-creation-cancelled"));
return;
}
if (info.getLocation().distanceSquared(p.getLocation()) > 25) {
p.sendMessage(MsgUtil.getMessage("shop-creation-cancelled"));
return;
}
/* Creation handling */
// if (info.getAction() == ShopAction.CREATE) {
// actionCreate(p, actions, info, message);
// /* Purchase Handling */
// } else if (info.getAction() == ShopAction.BUY) {
// actionTrade(p, actions, info, message);
// }
switch (info.getAction()) {
case CREATE:
actionCreate(p, actions, info, message, bypassProtectionChecks);
break;
case BUY:
actionTrade(p, actions, info, message);
break;
case CANCELLED:
break; //Go away
}
});
}
private void actionTrade(@NotNull Player p, @NotNull HashMap<UUID, Info> actions, @NotNull Info info, @NotNull String message) {
int amount;
try {
amount = Integer.parseInt(message);
} catch (NumberFormatException e) {
p.sendMessage(MsgUtil.getMessage("shop-purchase-cancelled"));
return;
}
// Get the shop they interacted with
Shop shop = plugin.getShopManager().getShop(info.getLocation());
// It's not valid anymore
if (shop == null || !Util.canBeShop(info.getLocation().getBlock())) {
p.sendMessage(MsgUtil.getMessage("chest-was-removed"));
return;
}
if (info.hasChanged(shop)) {
p.sendMessage(MsgUtil.getMessage("shop-has-changed"));
return;
}
if (shop.isBuying()) {
actionBuy(p, actions, info, message, shop, amount);
} else if (shop.isSelling()) {
actionSell(p, actions, info, message, shop, amount);
} else {
p.sendMessage(MsgUtil.getMessage("shop-purchase-cancelled"));
plugin.getLogger().warning("Shop data broken? Loc:" + shop.getLocation().toString());
}
}
@SuppressWarnings("deprecation")
private void actionBuy(@NotNull Player p, @NotNull HashMap<UUID, Info> actions2, @NotNull Info info, @NotNull String message, @NotNull Shop shop, int amount) {
if (!Util.canBeShop(info.getLocation().getBlock())) {
@@ -494,93 +131,6 @@ public class ShopManager {
shop.setSignText(); // Update the signs count
}
@SuppressWarnings("deprecation")
private void actionSell(@NotNull Player p, @NotNull HashMap<UUID, Info> actions2, @NotNull Info info, @NotNull String message, @NotNull Shop shop, int amount) {
if (!Util.canBeShop(info.getLocation().getBlock())) {
p.sendMessage(MsgUtil.getMessage("chest-was-removed"));
return;
}
if (info.hasChanged(shop)) {
p.sendMessage(MsgUtil.getMessage("shop-has-changed"));
return;
}
int stock = shop.getRemainingStock();
if (stock == -1)
stock = 10000;
if (stock < amount) {
p.sendMessage(MsgUtil
.getMessage("shop-stock-too-low", "" + shop.getRemainingStock(), Util.getItemStackName(shop.getItem())));
return;
}
if (amount < 1) {
// & Dumber
p.sendMessage(MsgUtil.getMessage("negative-amount"));
return;
}
int pSpace = Util.countSpace(p.getInventory(), shop.getItem());
if (amount > pSpace) {
p.sendMessage(MsgUtil.getMessage("not-enough-space", String.valueOf(pSpace)));
return;
}
ShopPurchaseEvent e = new ShopPurchaseEvent(shop, p, amount);
Bukkit.getPluginManager().callEvent(e);
if (e.isCancelled())
return; // Cancelled
// Money handling
double tax = plugin.getConfig().getDouble("tax");
double total = amount * shop.getPrice();
if (tax < 0)
tax = 0; //Tax was disabled.
if (shop.getModerator().isModerator(p.getUniqueId()))
tax = 0; //Is staff or owner, so we won't will take them tax
Economy eco = plugin.getEconomy();
boolean successA = eco.withdraw(p.getUniqueId(), total); //Withdraw owner's money
if (!successA) {
p.sendMessage(MsgUtil
.getMessage("you-cant-afford-to-buy", format(total), format(eco.getBalance(p.getUniqueId()))));
return;
}
boolean shouldPayOwner = !shop.isUnlimited() || (plugin.getConfig().getBoolean("shop.pay-unlimited-shop-owners") && shop
.isUnlimited());
if (shouldPayOwner) {
boolean successB = eco.deposit(shop.getOwner(), total * (1 - tax));
if (!successB) {
plugin.getLogger().warning("Failed to deposit the money for player " + Bukkit.getPlayer(shop.getOwner()));
/* Rollback the trade */
if (!eco.deposit(p.getUniqueId(), total * (1 - tax))) {
plugin.getLogger().warning("Failed to rollback the purchase actions for player " + Bukkit
.getOfflinePlayer(shop.getOwner()).getName());
}
p.sendMessage(MsgUtil.getMessage("purchase-failed"));
return;
}
}
String msg;
// Notify the shop owner
if (plugin.getConfig().getBoolean("show-tax")) {
msg = MsgUtil.getMessage("player-bought-from-your-store-tax", p.getName(), "" + amount, Util
.getItemStackName(shop.getItem()), Util.format((tax * total)));
} else {
msg = MsgUtil.getMessage("player-bought-from-your-store", p.getName(), "" + amount, Util
.getItemStackName(shop.getItem()));
}
// Transfers the item from A to B
if (stock == amount)
msg += "\n" + MsgUtil.getMessage("shop-out-of-stock", "" + shop.getLocation().getBlockX(), "" + shop
.getLocation().getBlockY(), "" + shop.getLocation().getBlockZ(), Util
.getItemStackName(shop.getItem()));
MsgUtil.send(shop.getOwner(), msg, shop.isUnlimited());
shop.sell(p, amount);
MsgUtil.sendPurchaseSuccess(p, shop, amount);
ShopSuccessPurchaseEvent se = new ShopSuccessPurchaseEvent(shop, p, amount, total, tax);
Bukkit.getPluginManager().callEvent(se);
}
@SuppressWarnings("deprecation")
private void actionCreate(@NotNull Player p, @NotNull HashMap<UUID, Info> actions2, @NotNull Info info, @NotNull String message, boolean bypassProtectionChecks) {
Util.debugLog("actionCreate");
@@ -720,14 +270,312 @@ public class ShopManager {
}
}
@SuppressWarnings("deprecation")
private void actionSell(@NotNull Player p, @NotNull HashMap<UUID, Info> actions2, @NotNull Info info, @NotNull String message, @NotNull Shop shop, int amount) {
if (!Util.canBeShop(info.getLocation().getBlock())) {
p.sendMessage(MsgUtil.getMessage("chest-was-removed"));
return;
}
if (info.hasChanged(shop)) {
p.sendMessage(MsgUtil.getMessage("shop-has-changed"));
return;
}
int stock = shop.getRemainingStock();
if (stock == -1)
stock = 10000;
if (stock < amount) {
p.sendMessage(MsgUtil
.getMessage("shop-stock-too-low", "" + shop.getRemainingStock(), Util.getItemStackName(shop.getItem())));
return;
}
if (amount < 1) {
// & Dumber
p.sendMessage(MsgUtil.getMessage("negative-amount"));
return;
}
int pSpace = Util.countSpace(p.getInventory(), shop.getItem());
if (amount > pSpace) {
p.sendMessage(MsgUtil.getMessage("not-enough-space", String.valueOf(pSpace)));
return;
}
ShopPurchaseEvent e = new ShopPurchaseEvent(shop, p, amount);
Bukkit.getPluginManager().callEvent(e);
if (e.isCancelled())
return; // Cancelled
// Money handling
double tax = plugin.getConfig().getDouble("tax");
double total = amount * shop.getPrice();
if (tax < 0)
tax = 0; //Tax was disabled.
if (shop.getModerator().isModerator(p.getUniqueId()))
tax = 0; //Is staff or owner, so we won't will take them tax
Economy eco = plugin.getEconomy();
boolean successA = eco.withdraw(p.getUniqueId(), total); //Withdraw owner's money
if (!successA) {
p.sendMessage(MsgUtil
.getMessage("you-cant-afford-to-buy", format(total), format(eco.getBalance(p.getUniqueId()))));
return;
}
boolean shouldPayOwner = !shop.isUnlimited() || (plugin.getConfig().getBoolean("shop.pay-unlimited-shop-owners") && shop
.isUnlimited());
if (shouldPayOwner) {
boolean successB = eco.deposit(shop.getOwner(), total * (1 - tax));
if (!successB) {
plugin.getLogger().warning("Failed to deposit the money for player " + Bukkit.getPlayer(shop.getOwner()));
/* Rollback the trade */
if (!eco.deposit(p.getUniqueId(), total * (1 - tax))) {
plugin.getLogger().warning("Failed to rollback the purchase actions for player " + Bukkit
.getOfflinePlayer(shop.getOwner()).getName());
}
p.sendMessage(MsgUtil.getMessage("purchase-failed"));
return;
}
}
String msg;
// Notify the shop owner
if (plugin.getConfig().getBoolean("show-tax")) {
msg = MsgUtil.getMessage("player-bought-from-your-store-tax", p.getName(), "" + amount, Util
.getItemStackName(shop.getItem()), Util.format((tax * total)));
} else {
msg = MsgUtil.getMessage("player-bought-from-your-store", p.getName(), "" + amount, Util
.getItemStackName(shop.getItem()));
}
// Transfers the item from A to B
if (stock == amount)
msg += "\n" + MsgUtil.getMessage("shop-out-of-stock", "" + shop.getLocation().getBlockX(), "" + shop
.getLocation().getBlockY(), "" + shop.getLocation().getBlockZ(), Util
.getItemStackName(shop.getItem()));
MsgUtil.send(shop.getOwner(), msg, shop.isUnlimited());
shop.sell(p, amount);
MsgUtil.sendPurchaseSuccess(p, shop, amount);
ShopSuccessPurchaseEvent se = new ShopSuccessPurchaseEvent(shop, p, amount, total, tax);
Bukkit.getPluginManager().callEvent(se);
}
private void actionTrade(@NotNull Player p, @NotNull HashMap<UUID, Info> actions, @NotNull Info info, @NotNull String message) {
int amount;
try {
amount = Integer.parseInt(message);
} catch (NumberFormatException e) {
p.sendMessage(MsgUtil.getMessage("shop-purchase-cancelled"));
return;
}
// Get the shop they interacted with
Shop shop = plugin.getShopManager().getShop(info.getLocation());
// It's not valid anymore
if (shop == null || !Util.canBeShop(info.getLocation().getBlock())) {
p.sendMessage(MsgUtil.getMessage("chest-was-removed"));
return;
}
if (info.hasChanged(shop)) {
p.sendMessage(MsgUtil.getMessage("shop-has-changed"));
return;
}
if (shop.isBuying()) {
actionBuy(p, actions, info, message, shop, amount);
} else if (shop.isSelling()) {
actionSell(p, actions, info, message, shop, amount);
} else {
p.sendMessage(MsgUtil.getMessage("shop-purchase-cancelled"));
plugin.getLogger().warning("Shop data broken? Loc:" + shop.getLocation().toString());
}
}
/**
* Returns a new shop iterator object, allowing iteration over shops easily,
* instead of sorting through a 3D hashmap.
* Adds a shop to the world. Does NOT require the chunk or world to be loaded
* Call shop.onLoad by yourself
*
* @return a new shop iterator object.
* @param world The name of the world
* @param shop The shop to add
*/
public Iterator<Shop> getShopIterator() {
return new ShopIterator();
public void addShop(@NotNull String world, @NotNull Shop shop) {
HashMap<ShopChunk, HashMap<Location, Shop>> inWorld = this.getShops()
.computeIfAbsent(world, k -> new HashMap<>(3));
// There's no world storage yet. We need to create that hashmap.
// Put it in the data universe
// Calculate the chunks coordinates. These are 1,2,3 for each chunk, NOT
// location rounded to the nearest 16.
int x = (int) Math.floor((shop.getLocation().getBlockX()) / 16.0);
int z = (int) Math.floor((shop.getLocation().getBlockZ()) / 16.0);
// Get the chunk set from the world info
ShopChunk shopChunk = new ShopChunk(world, x, z);
HashMap<Location, Shop> inChunk = inWorld.computeIfAbsent(shopChunk, k -> new HashMap<>(1));
// That chunk data hasn't been created yet - Create it!
// Put it in the world
// Put the shop in its location in the chunk list.
inChunk.put(shop.getLocation(), shop);
// shop.onLoad();
}
/**
* Checks other plugins to make sure they can use the chest they're making a
* shop.
*
* @param p The player to check
* @param b The block to check
* @param bf The blockface to check
* @return True if they're allowed to place a shop there.
*/
public boolean canBuildShop(@NotNull Player p, @NotNull Block b, @NotNull BlockFace bf) {
RegisteredListener openInvRegisteredListener = null; // added for compatibility reasons with OpenInv - see https://github.com/KaiKikuchi/QuickShop/issues/139
// try {
// if (plugin.openInvPlugin != null) {
// for (RegisteredListener listener : PlayerInteractEvent.getHandlerList().getRegisteredListeners()) {
// if (listener.getPlugin().getName().equals(plugin.openInvPlugin.getName())) {
// openInvRegisteredListener = listener;
// PlayerInteractEvent.getHandlerList().unregister(listener);
// break;
// }
// }
// }
try {
plugin.getCompatibilityTool().toggleInteractListeners(false);
if (plugin.isLimit()) {
int owned = 0;
if (!plugin.getConfig().getBoolean("limits.old-algorithm")) {
for (HashMap<ShopChunk, HashMap<Location, Shop>> shopmap : getShops().values()) {
for (HashMap<Location, Shop> shopLocs : shopmap.values()) {
for (Shop shop : shopLocs.values()) {
if (shop.getOwner().equals(p.getUniqueId()) && !shop.isUnlimited()) {
owned++;
}
}
}
}
} else {
Iterator<Shop> it = getShopIterator();
while (it.hasNext()) {
if (it.next().getOwner().equals(p.getUniqueId())) {
owned++;
}
}
}
int max = plugin.getShopLimit(p);
if (owned + 1 > max) {
//p.sendMessage(ChatColor.RED + "You have already created a maximum of " + owned + "/" + max + " shops!");
p.sendMessage(MsgUtil.getMessage("reached-maximum-can-create", String.valueOf(owned), String.valueOf(max)));
return false;
}
}
if (!plugin.getPermissionChecker().canBuild(p, b, false)) {
Util.debugLog("PermissionChecker canceled shop creation");
return false;
}
ShopPreCreateEvent spce = new ShopPreCreateEvent(p, b.getLocation());
Bukkit.getPluginManager().callEvent(spce);
if (spce.isCancelled()) {
return false;
}
} finally {
// if (plugin.openInvPlugin != null && openInvRegisteredListener != null) {
// PlayerInteractEvent.getHandlerList().register(openInvRegisteredListener);
// }
plugin.getCompatibilityTool().toggleInteractListeners(true);
}
return true;
}
/**
* Removes all shops from memory and the world. Does not delete them from
* the database. Call this on plugin disable ONLY.
*/
public void clear() {
if (plugin.isDisplay()) {
for (World world : Bukkit.getWorlds()) {
for (Chunk chunk : world.getLoadedChunks()) {
HashMap<Location, Shop> inChunk = this.getShops(chunk);
if (inChunk == null || inChunk.isEmpty())
continue;
for (Shop shop : inChunk.values()) {
shop.onUnload();
}
}
}
}
this.actions.clear();
this.shops.clear();
}
/**
* Create a shop use Shop and Info object.
*
* @param shop The shop object
* @param info The info object
*/
public void createShop(@NotNull Shop shop, @NotNull Info info) {
ShopCreateEvent ssShopCreateEvent = new ShopCreateEvent(shop, Bukkit.getPlayer(shop.getOwner()));
Bukkit.getPluginManager().callEvent(ssShopCreateEvent);
if (ssShopCreateEvent.isCancelled()) {
return;
}
Location loc = shop.getLocation();
ItemStack item = shop.getItem();
try {
// Write it to the database
plugin.getDatabaseHelper().createShop(plugin.getDatabase(), ShopModerator.serialize(shop.getModerator()), shop
.getPrice(), item, (shop.isUnlimited() ?
1 :
0), shop.getShopType().toID(), loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
// Add it to the world
addShop(loc.getWorld().getName(), shop);
} catch (SQLException error) {
plugin.getLogger().warning("SQLException detected, trying to auto fix the database...");
boolean backupSuccess = Util.backupDatabase();
try {
if (backupSuccess) {
plugin.getDatabaseHelper().removeShop(plugin.getDatabase(), loc.getBlockX(), loc.getBlockY(), loc
.getBlockZ(), loc.getWorld().getName());
} else {
plugin.getLogger().warning("Failed to backup the database, all changes will revert after a reboot.");
}
} catch (SQLException error2) {
//Failed removing
plugin.getLogger().warning("Failed to autofix the database, all changes will revert after a reboot.");
error.printStackTrace();
error2.printStackTrace();
}
}
//Create sign
if (info.getSignBlock() != null && plugin.getConfig().getBoolean("shop.auto-sign")) {
if (!Util.isAir(info.getSignBlock().getType())) {
Util.debugLog("Sign cannot placed cause no enough space(Not air block)");
return;
}
boolean isWaterLogged = false;
if (info.getSignBlock().getType() == Material.WATER)
isWaterLogged = true;
info.getSignBlock().setType(Util.getSignMaterial());
BlockState bs = info.getSignBlock().getState();
if (isWaterLogged) {
if (bs.getBlockData() instanceof Waterlogged) {
Waterlogged waterable = (Waterlogged) bs.getBlockData();
waterable.setWaterlogged(true); // Looks like sign directly put in water
}
}
if (bs.getBlockData() instanceof WallSign) {
org.bukkit.block.data.type.WallSign signBlockDataType = (org.bukkit.block.data.type.WallSign) bs.getBlockData();
BlockFace bf = info.getLocation().getBlock().getFace(info.getSignBlock());
if (bf != null) {
signBlockDataType.setFacing(bf);
bs.setBlockData(signBlockDataType);
}
} else {
plugin.getLogger().warning("Sign material " + bs.getType()
.name() + " not a WallSign, make sure you using correct sign material.");
}
bs.update(true);
shop.setSignText();
}
}
/**
@@ -740,11 +588,163 @@ public class ShopManager {
return plugin.getEconomy().format(d);
}
/**
* Gets a shop in a specific location
*
* @param loc The location to get the shop from
* @return The shop at that location
*/
public Shop getShop(@NotNull Location loc) {
HashMap<Location, Shop> inChunk = getShops(loc.getChunk());
if (inChunk == null) {
return null;
}
// We can do this because WorldListener updates the world reference so
// the world in loc is the same as world in inChunk.get(loc)
return inChunk.get(loc);
}
/**
* Returns a hashmap of Chunk - Shop
*
* @param world The name of the world (case sensitive) to get the list of
* shops from
* @return a hashmap of Chunk - Shop
*/
public HashMap<ShopChunk, HashMap<Location, Shop>> getShops(@NotNull String world) {
return this.shops.get(world);
}
/**
* Returns a hashmap of Shops
*
* @param c The chunk to search. Referencing doesn't matter, only
* coordinates and world are used.
* @return Shops
*/
public HashMap<Location, Shop> getShops(@NotNull Chunk c) {
// long start = System.nanoTime();
return getShops(c.getWorld().getName(), c.getX(), c.getZ());
// long end = System.nanoTime();
// plugin.getLogger().log(Level.WARNING, "Chunk lookup in " + ((end - start)/1000000.0) +
// "ms.");
}
public HashMap<Location, Shop> getShops(String world, int chunkX, int chunkZ) {
HashMap<ShopChunk, HashMap<Location, Shop>> inWorld = this.getShops(world);
if (inWorld == null) {
return null;
}
ShopChunk shopChunk = new ShopChunk(world, chunkX, chunkZ);
return inWorld.get(shopChunk);
}
public void handleChat(@NotNull Player p, @NotNull String msg) {
handleChat(p, msg, false);
}
public void handleChat(@NotNull Player p, @NotNull String msg, boolean bypassProtectionChecks) {
final String message = ChatColor.stripColor(msg);
// Use from the main thread, because Bukkit hates life
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> {
HashMap<UUID, Info> actions = getActions();
// They wanted to do something.
Info info = actions.remove(p.getUniqueId());
if (info == null)
return; // multithreaded means this can happen
if (info.getLocation().getWorld() != p.getLocation().getWorld()) {
p.sendMessage(MsgUtil.getMessage("shop-creation-cancelled"));
return;
}
if (info.getLocation().distanceSquared(p.getLocation()) > 25) {
p.sendMessage(MsgUtil.getMessage("shop-creation-cancelled"));
return;
}
/* Creation handling */
// if (info.getAction() == ShopAction.CREATE) {
// actionCreate(p, actions, info, message);
// /* Purchase Handling */
// } else if (info.getAction() == ShopAction.BUY) {
// actionTrade(p, actions, info, message);
// }
switch (info.getAction()) {
case CREATE:
actionCreate(p, actions, info, message, bypassProtectionChecks);
break;
case BUY:
actionTrade(p, actions, info, message);
break;
case CANCELLED:
break; //Go away
}
});
}
/**
* Loads the given shop into storage. This method is used for loading data
* from the database. Do not use this method to create a shop.
*
* @param world The world the shop is in
* @param shop The shop to load
*/
public void loadShop(@NotNull String world, @NotNull Shop shop) {
this.addShop(world, shop);
}
/**
* Removes a shop from the world. Does NOT remove it from the database. *
* REQUIRES * the world to be loaded
* Call shop.onUnload by your self.
*
* @param shop The shop to remove
*/
public void removeShop(@NotNull Shop shop) {
// shop.onUnload();
Location loc = shop.getLocation();
String world = loc.getWorld().getName();
HashMap<ShopChunk, HashMap<Location, Shop>> inWorld = this.getShops().get(world);
int x = (int) Math.floor((shop.getLocation().getBlockX()) / 16.0);
int z = (int) Math.floor((shop.getLocation().getBlockZ()) / 16.0);
ShopChunk shopChunk = new ShopChunk(world, x, z);
HashMap<Location, Shop> inChunk = inWorld.get(shopChunk);
if (inChunk == null)
return;
inChunk.remove(loc);
// shop.onUnload();
}
/**
* @return Returns the HashMap. Info contains what
* their last question etc was.
*/
public HashMap<UUID, Info> getActions() {
return this.actions;
}
/**
* Returns a new shop iterator object, allowing iteration over shops easily,
* instead of sorting through a 3D hashmap.
*
* @return a new shop iterator object.
*/
public Iterator<Shop> getShopIterator() {
return new ShopIterator();
}
/**
* Returns a hashmap of World - Chunk - Shop
*
* @return a hashmap of World - Chunk - Shop
*/
public HashMap<String, HashMap<ShopChunk, HashMap<Location, Shop>>> getShops() {
return this.shops;
}
public class ShopIterator implements Iterator<Shop> {
private Iterator<Shop> shops;
private Iterator<HashMap<Location, Shop>> chunks;
private Iterator<HashMap<ShopChunk, HashMap<Location, Shop>>> worlds;
private Shop current;
private Iterator<Shop> shops;
private Iterator<HashMap<ShopChunk, HashMap<Location, Shop>>> worlds;
public ShopIterator() {
worlds = getShops().values().iterator();
@@ -12,6 +12,16 @@ import org.jetbrains.annotations.*;
*/
@EqualsAndHashCode
public class ShopModerator {
public static ShopModerator deserialize(@NotNull String serilized) {
//Use Gson deserialize data
Gson gson = new Gson();
return gson.fromJson(serilized, ShopModerator.class);
}
public static String serialize(@NotNull ShopModerator shopModerator) {
Gson gson = new Gson();
return gson.toJson(shopModerator); //Use Gson serialize this class
}
private UUID owner;
private ArrayList<UUID> staffs;
@@ -40,34 +50,6 @@ public class ShopModerator {
this.staffs = new ArrayList<UUID>();
}
public ShopModerator clone() {
return new ShopModerator(this);
}
/**
* Get moderators owner (Shop Owner).
* @return Owner's UUID
*/
public UUID getOwner() {
return owner;
}
/**
* Set moderators owner (Shop Owner)
* @param player Owner's UUID
*/
public void setOwner(@NotNull UUID player) {
this.owner = player;
}
/**
* Set moderators staffs
* @param players staffs list
*/
public void setStaffs(@NotNull ArrayList<UUID> players) {
this.staffs = players;
}
/**
* Add moderators staff to staff list
* @param player New staff
@@ -80,6 +62,22 @@ public class ShopModerator {
return true;
}
/**
* Remove all staffs
*/
public void clearStaffs() {
staffs.clear();
}
public ShopModerator clone() {
return new ShopModerator(this);
}
@Override
public String toString() {
return serialize(this);
}
/**
* Remove moderators staff from staff list
* @param player Staff
@@ -90,18 +88,14 @@ public class ShopModerator {
}
/**
* Remove all staffs
* Get a player is or not moderators
* @param player Player
* @return yes or no, return true when it is staff or owner
*/
public void clearStaffs() {
staffs.clear();
}
/**
* Get staffs list
* @return Staffs
*/
public ArrayList<UUID> getStaffs() {
return staffs;
public boolean isModerator(@NotNull UUID player) {
if (isOwner(player))
return true;
return isStaff(player);
}
/**
@@ -123,29 +117,37 @@ public class ShopModerator {
}
/**
* Get a player is or not moderators
* @param player Player
* @return yes or no, return true when it is staff or owner
* Get moderators owner (Shop Owner).
* @return Owner's UUID
*/
public boolean isModerator(@NotNull UUID player) {
if (isOwner(player))
return true;
return isStaff(player);
public UUID getOwner() {
return owner;
}
public static String serialize(@NotNull ShopModerator shopModerator) {
Gson gson = new Gson();
return gson.toJson(shopModerator); //Use Gson serialize this class
/**
* Set moderators owner (Shop Owner)
*
* @param player Owner's UUID
*/
public void setOwner(@NotNull UUID player) {
this.owner = player;
}
public static ShopModerator deserialize(@NotNull String serilized) {
//Use Gson deserialize data
Gson gson = new Gson();
return gson.fromJson(serilized, ShopModerator.class);
/**
* Get staffs list
*
* @return Staffs
*/
public ArrayList<UUID> getStaffs() {
return staffs;
}
@Override
public String toString() {
return serialize(this);
/**
* Set moderators staffs
*
* @param players staffs list
*/
public void setStaffs(@NotNull ArrayList<UUID> players) {
this.staffs = players;
}
}
@@ -7,9 +7,9 @@ import lombok.*;
@EqualsAndHashCode
@ToString
public class ShopProtectionFlag {
private String shopLocation;
private String itemStackString;
private String mark = "QuickShop DisplayItem";
private String shopLocation;
public ShopProtectionFlag(String shopLocation, String itemStackString) {
this.shopLocation = shopLocation;
@@ -4,12 +4,6 @@ import org.jetbrains.annotations.*;
public enum ShopType {
SELLING(0), BUYING(1);
private int id;
ShopType(int id) {
this.id = id;
}
public static ShopType fromID(int id) {
for (ShopType type : ShopType.values()) {
if (type.id == id) {
@@ -23,6 +17,12 @@ public enum ShopType {
return shopType.id;
}
private int id;
ShopType(int id) {
this.id = id;
}
public int toID() {
return id;
}
@@ -16,9 +16,26 @@ import org.jetbrains.annotations.*;
A utils for print sheet on chat.
*/
public class ChatSheetPrinter {
final ChatColor chatColor = ChatColor.DARK_PURPLE;
//StringBuffer buffer = new StringBuffer();
private CommandSender p;
final ChatColor chatColor = ChatColor.DARK_PURPLE;
public void printCenterLine(@NotNull String text) {
p.sendMessage(chatColor + MsgUtil.getMessage("tableformat.left_half_line") + text + MsgUtil
.getMessage("tableformat.right_half_line"));
}
public void printExecuteableCmdLine(@NotNull String text, @NotNull String hoverText, @NotNull String executeCmd) {
TextComponent message = new TextComponent(chatColor + MsgUtil.getMessage("tableformat.left_begin") + text);
message.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, executeCmd));
message.setHoverEvent(
new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(hoverText).create()));
p.spigot().sendMessage(message);
}
public void printFooter() {
p.sendMessage(chatColor + MsgUtil.getMessage("tableformat.full_line"));
}
public void printHeader() {
p.sendMessage("");
@@ -30,23 +47,6 @@ public class ChatSheetPrinter {
p.sendMessage(chatColor + MsgUtil.getMessage("tableformat.left_begin") + " " + text);
}
public void printCenterLine(@NotNull String text) {
p.sendMessage(chatColor + MsgUtil.getMessage("tableformat.left_half_line") + text + MsgUtil
.getMessage("tableformat.right_half_line"));
}
public void printFooter() {
p.sendMessage(chatColor + MsgUtil.getMessage("tableformat.full_line"));
}
public void printExecuteableCmdLine(@NotNull String text, @NotNull String hoverText, @NotNull String executeCmd) {
TextComponent message = new TextComponent(chatColor + MsgUtil.getMessage("tableformat.left_begin") + text);
message.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, executeCmd));
message.setHoverEvent(
new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(hoverText).create()));
p.spigot().sendMessage(message);
}
public void printSuggestableCmdLine(@NotNull String text, @NotNull String hoverText, @NotNull String suggestCmd) {
TextComponent message = new TextComponent(chatColor + MsgUtil.getMessage("tableformat.left_begin") + text);
message.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, suggestCmd));
@@ -10,8 +10,9 @@ import org.maxgamer.quickshop.QuickShop;
* WIP
*/
public class Compatibility {
private QuickShop plugin;
private final ArrayList<RegisteredListener> disabledListeners = new ArrayList<>();
final private ArrayList<String> knownIncompatiablePlugin = new ArrayList<>();
private QuickShop plugin;
public Compatibility(@NotNull QuickShop plugin) {
this.plugin = plugin;
@@ -19,8 +20,6 @@ public class Compatibility {
knownIncompatiablePlugin.add("LWC");
}
private final ArrayList<RegisteredListener> disabledListeners = new ArrayList<>();
/**
* Switch the compatibility mode on or off, set false to disable all we known incompatiable plugin listener,
* set true to enable back all disabled plugin liseners.
@@ -27,6 +27,22 @@ public class IncompatibleChecker {
return incompatibleVersionList.contains(version);
}
private void mc1_10() {
incompatibleVersionList.add("v1_10_R1");
}
private void mc1_11() {
incompatibleVersionList.add("v1_11_R1");
}
private void mc1_12() {
incompatibleVersionList.add("v1_12_R1");
}
private void mc1_13() {
incompatibleVersionList.add("v1_13_R1"); //1.13.0-1.13.1 no Tag feature.
}
private void mc1_5() {
incompatibleVersionList.add("v1_5_R1");
incompatibleVersionList.add("v1_5_R2");
@@ -56,20 +72,4 @@ public class IncompatibleChecker {
incompatibleVersionList.add("v1_9_R1");
incompatibleVersionList.add("v1_9_R2");
}
private void mc1_10() {
incompatibleVersionList.add("v1_10_R1");
}
private void mc1_11() {
incompatibleVersionList.add("v1_11_R1");
}
private void mc1_12() {
incompatibleVersionList.add("v1_12_R1");
}
private void mc1_13() {
incompatibleVersionList.add("v1_13_R1"); //1.13.0-1.13.1 no Tag feature.
}
}
@@ -17,8 +17,8 @@ import org.maxgamer.quickshop.QuickShop;
* A util allow quickshop check item matches easy and quick.
*/
public class ItemMatcher {
private QuickShop plugin;
private ItemMetaMatcher itemMetaMatcher;
private QuickShop plugin;
public ItemMatcher(QuickShop plugin) {
this.plugin = plugin;
@@ -63,14 +63,14 @@ public class ItemMatcher {
}
class ItemMetaMatcher {
private boolean attributes;
private boolean custommodeldata;
private boolean damage;
private boolean displayname;
private boolean lores;
private boolean enchs;
private boolean potions;
private boolean attributes;
private boolean itemflags;
private boolean custommodeldata;
private boolean lores;
private boolean potions;
public ItemMetaMatcher(ConfigurationSection itemMatcherConfig) {
this.damage = itemMatcherConfig.getBoolean("damage");
@@ -83,6 +83,108 @@ public class ItemMatcher {
this.custommodeldata = itemMatcherConfig.getBoolean("custommodeldata");
}
private boolean attributeModifiersMatches(ItemMeta meta1, ItemMeta meta2) {
if (!this.attributes)
return true;
if (meta1.hasAttributeModifiers() != meta2.hasAttributeModifiers())
return false;
if (!meta1.hasAttributeModifiers())
return true; //No attributeModifiers need to be checked.
return (meta1.getAttributeModifiers().hashCode() == meta2.getAttributeModifiers().hashCode());
}
private boolean customModelDataMatches(ItemMeta meta1, ItemMeta meta2) {
if (!this.custommodeldata)
return true;
if (meta1.hasCustomModelData() != meta2.hasCustomModelData())
return false;
if (!meta1.hasCustomModelData())
return true; //No customModelData needs to be checked.
return (meta1.getCustomModelData() == meta2.getCustomModelData());
}
private boolean damageMatches(ItemMeta meta1, ItemMeta meta2) {
if (!this.damage)
return true;
if ((meta1 instanceof Damageable) != (meta2 instanceof Damageable))
return false;
if (!(meta1 instanceof Damageable))
return true; //No damage need to check.
Damageable damage1 = (Damageable) meta1;
Damageable damage2 = (Damageable) meta2;
if (damage1.hasDamage() != damage2.hasDamage())
return false;
if (!damage1.hasDamage())
return true; //No damage need to check.
return damage1.getDamage() == damage2.getDamage();
}
private boolean displayMatches(ItemMeta meta1, ItemMeta meta2) {
if (!this.displayname)
return true;
if (meta1.hasDisplayName() != meta2.hasDisplayName())
return false;
if (!meta1.hasDisplayName())
return true; //Passed check. no display need to check
return (meta1.getDisplayName().equals(meta2.getDisplayName()));
}
private boolean enchMatches(ItemMeta meta1, ItemMeta meta2) {
if (!this.enchs)
return true;
if (meta1.hasEnchants() != meta2.hasEnchants())
return false;
if (meta1.hasEnchants()) {
Map<Enchantment, Integer> enchMap1 = meta1.getEnchants();
Map<Enchantment, Integer> enchMap2 = meta2.getEnchants();
if (!Util.mapDuoMatches(enchMap1, enchMap2))
return false;
}
if (meta1 instanceof EnchantmentStorageMeta != meta2 instanceof EnchantmentStorageMeta)
return false;
if (meta1 instanceof EnchantmentStorageMeta) {
Map<Enchantment, Integer> stor1 = ((EnchantmentStorageMeta) meta1).getStoredEnchants();
Map<Enchantment, Integer> stor2 = ((EnchantmentStorageMeta) meta2).getStoredEnchants();
return Util.mapDuoMatches(stor1, stor2);
}
return true;
}
private boolean itemFlagsMatches(ItemMeta meta1, ItemMeta meta2) {
if (!this.itemflags)
return true;
return (meta1.getItemFlags().hashCode() == meta2.getItemFlags().hashCode());
}
private boolean loresMatches(ItemMeta meta1, ItemMeta meta2) {
Util.debugLog("Lores checker");
if (!this.lores)
return true;
Util.debugLog("Lores checking");
if (meta1.hasLore() != meta2.hasLore())
return false;
if (!meta1.hasLore())
return true; // No lores need to be checked.
List<String> lores1 = meta1.getLore();
List<String> lores2 = meta2.getLore();
if (lores1.size() != lores2.size())
return false;
for (int i = 0; i < lores1.size(); i++) {
if (!lores1.get(i).equals(lores2.get(i)))
return false;
}
return (lores2.hashCode() == lores2.hashCode());
}
boolean matches(ItemStack stack1, ItemStack stack2) {
Util.debugLog("Begin the item matches checking...");
if (stack1.hasItemMeta() != stack2.hasItemMeta())
@@ -121,84 +223,6 @@ public class ItemMatcher {
return true;
}
private boolean rootMatches(ItemMeta meta1, ItemMeta meta2) {
return (meta1.hashCode() == meta2.hashCode());
}
private boolean damageMatches(ItemMeta meta1, ItemMeta meta2) {
if (!this.damage)
return true;
if ((meta1 instanceof Damageable) != (meta2 instanceof Damageable))
return false;
if (!(meta1 instanceof Damageable))
return true; //No damage need to check.
Damageable damage1 = (Damageable) meta1;
Damageable damage2 = (Damageable) meta2;
if (damage1.hasDamage() != damage2.hasDamage())
return false;
if (!damage1.hasDamage())
return true; //No damage need to check.
return damage1.getDamage() == damage2.getDamage();
}
private boolean displayMatches(ItemMeta meta1, ItemMeta meta2) {
if (!this.displayname)
return true;
if (meta1.hasDisplayName() != meta2.hasDisplayName())
return false;
if (!meta1.hasDisplayName())
return true; //Passed check. no display need to check
return (meta1.getDisplayName().equals(meta2.getDisplayName()));
}
private boolean loresMatches(ItemMeta meta1, ItemMeta meta2) {
Util.debugLog("Lores checker");
if (!this.lores)
return true;
Util.debugLog("Lores checking");
if (meta1.hasLore() != meta2.hasLore())
return false;
if (!meta1.hasLore())
return true; // No lores need to be checked.
List<String> lores1 = meta1.getLore();
List<String> lores2 = meta2.getLore();
if (lores1.size() != lores2.size())
return false;
for (int i = 0; i < lores1.size(); i++) {
if (!lores1.get(i).equals(lores2.get(i)))
return false;
}
return (lores2.hashCode() == lores2.hashCode());
}
private boolean enchMatches(ItemMeta meta1, ItemMeta meta2) {
if (!this.enchs)
return true;
if (meta1.hasEnchants() != meta2.hasEnchants())
return false;
if (meta1.hasEnchants()) {
Map<Enchantment, Integer> enchMap1 = meta1.getEnchants();
Map<Enchantment, Integer> enchMap2 = meta2.getEnchants();
if (!Util.mapDuoMatches(enchMap1, enchMap2))
return false;
}
if (meta1 instanceof EnchantmentStorageMeta != meta2 instanceof EnchantmentStorageMeta)
return false;
if (meta1 instanceof EnchantmentStorageMeta) {
Map<Enchantment, Integer> stor1 = ((EnchantmentStorageMeta) meta1).getStoredEnchants();
Map<Enchantment, Integer> stor2 = ((EnchantmentStorageMeta) meta2).getStoredEnchants();
return Util.mapDuoMatches(stor1, stor2);
}
return true;
}
private boolean potionMatches(ItemMeta meta1, ItemMeta meta2) {
if (!this.potions)
return true;
@@ -231,32 +255,8 @@ public class ItemMatcher {
return true;
}
private boolean attributeModifiersMatches(ItemMeta meta1, ItemMeta meta2) {
if (!this.attributes)
return true;
if (meta1.hasAttributeModifiers() != meta2.hasAttributeModifiers())
return false;
if (!meta1.hasAttributeModifiers())
return true; //No attributeModifiers need to be checked.
return (meta1.getAttributeModifiers().hashCode() == meta2.getAttributeModifiers().hashCode());
}
private boolean itemFlagsMatches(ItemMeta meta1, ItemMeta meta2) {
if (!this.itemflags)
return true;
return (meta1.getItemFlags().hashCode() == meta2.getItemFlags().hashCode());
}
private boolean customModelDataMatches(ItemMeta meta1, ItemMeta meta2) {
if (!this.custommodeldata)
return true;
if (meta1.hasCustomModelData() != meta2.hasCustomModelData())
return false;
if (!meta1.hasCustomModelData())
return true; //No customModelData needs to be checked.
return (meta1.getCustomModelData() == meta2.getCustomModelData());
private boolean rootMatches(ItemMeta meta1, ItemMeta meta2) {
return (meta1.hashCode() == meta2.hashCode());
}
}
@@ -1,54 +1,54 @@
package org.maxgamer.quickshop.Util;
import java.lang.reflect.Method;
import lombok.*;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.*;
import org.maxgamer.quickshop.QuickShop;
@Getter
public abstract class ItemNMS {
private static Method craftItemStack_asNMSCopyMethod;
private static Class<?> nbtTagCompoundClass;
private static Method itemStack_saveMethod;
static {
String name = Bukkit.getServer().getClass().getPackage().getName();
String nmsVersion = name.substring(name.lastIndexOf('.') + 1);
try {
craftItemStack_asNMSCopyMethod = Class.forName("org.bukkit.craftbukkit." + nmsVersion + ".inventory.CraftItemStack")
.getDeclaredMethod("asNMSCopy", ItemStack.class);
nbtTagCompoundClass = Class.forName("net.minecraft.server." + nmsVersion + ".NBTTagCompound");
itemStack_saveMethod = Class.forName("net.minecraft.server." + nmsVersion + ".ItemStack")
.getDeclaredMethod("save", nbtTagCompoundClass);
} catch (Throwable t) {
QuickShop.instance.getLogger().info("A error happend:");
t.printStackTrace();
QuickShop.instance.getLogger().info("Try to update QSRR and leave feedback about the bug on issue tracker if it continues.");
}
}
/**
* Save ItemStack to Json passthrough the NMS.
*
* @param bStack ItemStack
* @return The json for ItemStack.
* @throws Throwable throws
*/
public static String saveJsonfromNMS(@NotNull ItemStack bStack) throws Throwable {
if (bStack.getType() == Material.AIR)
return null;
Object mcStack = craftItemStack_asNMSCopyMethod.invoke(null, bStack);
Object nbtTagCompound = nbtTagCompoundClass.newInstance();
itemStack_saveMethod.invoke(mcStack, nbtTagCompound);
return nbtTagCompound.toString();
}
}
package org.maxgamer.quickshop.Util;
import java.lang.reflect.Method;
import lombok.*;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.*;
import org.maxgamer.quickshop.QuickShop;
@Getter
public abstract class ItemNMS {
private static Method craftItemStack_asNMSCopyMethod;
private static Method itemStack_saveMethod;
private static Class<?> nbtTagCompoundClass;
static {
String name = Bukkit.getServer().getClass().getPackage().getName();
String nmsVersion = name.substring(name.lastIndexOf('.') + 1);
try {
craftItemStack_asNMSCopyMethod = Class.forName("org.bukkit.craftbukkit." + nmsVersion + ".inventory.CraftItemStack")
.getDeclaredMethod("asNMSCopy", ItemStack.class);
nbtTagCompoundClass = Class.forName("net.minecraft.server." + nmsVersion + ".NBTTagCompound");
itemStack_saveMethod = Class.forName("net.minecraft.server." + nmsVersion + ".ItemStack")
.getDeclaredMethod("save", nbtTagCompoundClass);
} catch (Throwable t) {
QuickShop.instance.getLogger().info("A error happend:");
t.printStackTrace();
QuickShop.instance.getLogger().info("Try to update QSRR and leave feedback about the bug on issue tracker if it continues.");
}
}
/**
* Save ItemStack to Json passthrough the NMS.
*
* @param bStack ItemStack
* @return The json for ItemStack.
* @throws Throwable throws
*/
public static String saveJsonfromNMS(@NotNull ItemStack bStack) throws Throwable {
if (bStack.getType() == Material.AIR)
return null;
Object mcStack = craftItemStack_asNMSCopyMethod.invoke(null, bStack);
Object nbtTagCompound = nbtTagCompoundClass.newInstance();
itemStack_saveMethod.invoke(mcStack, nbtTagCompound);
return nbtTagCompound.toString();
}
}
File diff suppressed because it is too large. Load diff
@@ -27,16 +27,16 @@ import org.maxgamer.quickshop.QuickShop;
* Auto report errors to qs's sentry.
*/
public class SentryErrorReporter {
private Context context;
private final String dsn = "https://6a7881aa07164412bcb84a0f76253ae9@sentry.io/1473041?" + "stacktrace.app.packages=org.maxgamer.quickshop";
private final ArrayList<String> reported = new ArrayList<>();
private Context context;
private boolean disable;
private boolean enabled;
private List<Class> ignoredException = new ArrayList<>();
private QuickShop plugin;
/* Pre-init it if it called before the we create it... */
private SentryClient sentryClient;
private boolean enabled;
private final ArrayList<String> reported = new ArrayList<>();
private QuickShop plugin;
private boolean tempDisable;
private boolean disable;
private List<Class> ignoredException = new ArrayList<>();
public SentryErrorReporter(@NotNull QuickShop plugin) {
this.plugin = plugin;
@@ -80,19 +80,71 @@ public class SentryErrorReporter {
}
/**
* Unload Sentry error reporter
* Dupe report check
* @param throwable Throws
* @return dupecated
*/
private void unit() {
enabled = false;
private boolean canReport(@NotNull Throwable throwable) {
if (!enabled) {
return false;
}
StackTraceElement stackTraceElement;
if (throwable.getStackTrace().length < 3) {
stackTraceElement = throwable.getStackTrace()[1];
} else {
stackTraceElement = throwable.getStackTrace()[2];
}
String text = stackTraceElement.getClassName() + "#" + stackTraceElement.getMethodName() + "#" + stackTraceElement
.getLineNumber();
if (!reported.contains(text)) {
reported.add(text);
return true;
} else {
return false;
}
}
private String getPluginInfo() {
StringBuilder buffer = new StringBuilder();
for (Plugin bplugin : Bukkit.getPluginManager().getPlugins()) {
buffer.append("\t").append(bplugin.getName()).append("@").append(bplugin.isEnabled() ? "Enabled" : "Disabled")
.append("\n");
/**
* Check a throw is cause by QS
* @param throwable Throws
* @return Cause or not
*/
private boolean checkWasCauseByQS(@Nullable Throwable throwable) {
if (throwable == null)
return false;
while (throwable.getCause() != null) {
throwable = throwable.getCause();
}
return buffer.toString();
long element = Arrays.stream(throwable.getStackTrace())
.limit(10)
.filter(stackTraceElement -> stackTraceElement.getClassName().contains("org.maxgamer.quickshop"))
.count();
return element > 0;
}
/**
* Set ignore throw.
* It will unlocked after accept a throw
*/
public void ignoreThrow() {
tempDisable = true;
}
/**
* Set ignore throws.
* It will unlocked after called method resetIgnores.
*/
public void ignoreThrows() {
disable = true;
}
/**
* Reset ignore throw(s).
*/
public void resetIgnores() {
tempDisable = false;
disable = false;
}
/**
@@ -161,71 +213,19 @@ public class SentryErrorReporter {
}
/**
* Check a throw is cause by QS
* @param throwable Throws
* @return Cause or not
* Unload Sentry error reporter
*/
private boolean checkWasCauseByQS(@Nullable Throwable throwable) {
if (throwable == null)
return false;
while (throwable.getCause() != null) {
throwable = throwable.getCause();
}
long element = Arrays.stream(throwable.getStackTrace())
.limit(10)
.filter(stackTraceElement -> stackTraceElement.getClassName().contains("org.maxgamer.quickshop"))
.count();
return element > 0;
private void unit() {
enabled = false;
}
/**
* Dupe report check
* @param throwable Throws
* @return dupecated
*/
private boolean canReport(@NotNull Throwable throwable) {
if (!enabled) {
return false;
}
StackTraceElement stackTraceElement;
if (throwable.getStackTrace().length < 3) {
stackTraceElement = throwable.getStackTrace()[1];
} else {
stackTraceElement = throwable.getStackTrace()[2];
}
String text = stackTraceElement.getClassName() + "#" + stackTraceElement.getMethodName() + "#" + stackTraceElement
.getLineNumber();
if (!reported.contains(text)) {
reported.add(text);
return true;
} else {
return false;
}
}
class QuickShopExceptionFilter implements Filter {
/**
* Check if a given log record should be published.
*
* @param record a LogRecord
* @return true if the log record should be published.
*/
@Override
public boolean isLoggable(@NotNull LogRecord record) {
if (!enabled)
return true;
Level level = record.getLevel();
if (level != Level.WARNING && level != Level.SEVERE)
return true;
if (Util.isDevMode()) {
sendError(record.getThrown(), record.getMessage());
return true;
} else {
return sendError(record.getThrown(), record.getMessage()) == null;
}
private String getPluginInfo() {
StringBuilder buffer = new StringBuilder();
for (Plugin bplugin : Bukkit.getPluginManager().getPlugins()) {
buffer.append("\t").append(bplugin.getName()).append("@").append(bplugin.isEnabled() ? "Enabled" : "Disabled")
.append("\n");
}
return buffer.toString();
}
class GlobalExceptionFilter implements Filter {
@@ -252,28 +252,28 @@ public class SentryErrorReporter {
}
}
/**
* Set ignore throw.
* It will unlocked after accept a throw
*/
public void ignoreThrow() {
tempDisable = true;
}
class QuickShopExceptionFilter implements Filter {
/**
* Set ignore throws.
* It will unlocked after called method resetIgnores.
*/
public void ignoreThrows() {
disable = true;
}
/**
* Reset ignore throw(s).
*/
public void resetIgnores() {
tempDisable = false;
disable = false;
/**
* Check if a given log record should be published.
*
* @param record a LogRecord
* @return true if the log record should be published.
*/
@Override
public boolean isLoggable(@NotNull LogRecord record) {
if (!enabled)
return true;
Level level = record.getLevel();
if (level != Level.WARNING && level != Level.SEVERE)
return true;
if (Util.isDevMode()) {
sendError(record.getThrown(), record.getMessage());
return true;
} else {
return sendError(record.getThrown(), record.getMessage()) == null;
}
}
}
}
@@ -32,6 +32,27 @@ public class Timer {
this.startTime = startTime;
}
/**
* Return how long time running when timer set and destory the timer.
*
* @return time
*/
public long endTimer() {
long time = System.currentTimeMillis() - startTime;
startTime = 0;
return time;
}
/**
* Return how long time running after atTimeS. THIS NOT WILL DESTORY AND STOP THE TIMER
*
* @param atTime The inited time
* @return time
*/
public long getTimerAt(long atTime) {
return atTime - startTime;
}
/**
* Create a Timer.
* Time Unit: ms
@@ -48,25 +69,4 @@ public class Timer {
public long getTimer() {
return System.currentTimeMillis() - startTime;
}
/**
* Return how long time running after atTimeS. THIS NOT WILL DESTORY AND STOP THE TIMER
*
* @param atTime The inited time
* @return time
*/
public long getTimerAt(long atTime) {
return atTime - startTime;
}
/**
* Return how long time running when timer set and destory the timer.
*
* @return time
*/
public long endTimer() {
long time = System.currentTimeMillis() - startTime;
startTime = 0;
return time;
}
}
@@ -5,9 +5,10 @@ import org.jetbrains.annotations.*;
@AllArgsConstructor
@ToString
@Getter
@Setter
@Data
@EqualsAndHashCode
public class UpdateInfomation {
@Nullable private String version;
private boolean isBeta;
@Nullable private String version;
}
@@ -25,7 +25,7 @@ public class Updater {
*/
public static UpdateInfomation checkUpdate() {
if (!QuickShop.instance.getConfig().getBoolean("updater")) {
return new UpdateInfomation(null, false);
return new UpdateInfomation(false, null);
}
try {
HttpsURLConnection connection = (HttpsURLConnection) new URL("https://api.spigotmc.org/legacy/update.php?resource=62575")
@@ -37,47 +37,17 @@ public class Updater {
String spigotPluginVersion = new BufferedReader(new InputStreamReader(connection.getInputStream())).readLine();
if (spigotPluginVersion != null && !spigotPluginVersion.equals(localPluginVersion)) {
connection.disconnect();
return new UpdateInfomation(spigotPluginVersion, spigotPluginVersion.toLowerCase().contains("beta"));
return new UpdateInfomation(spigotPluginVersion.toLowerCase().contains("beta"), spigotPluginVersion);
}
connection.disconnect();
return new UpdateInfomation(spigotPluginVersion, false);
return new UpdateInfomation(false, spigotPluginVersion);
} catch (IOException e) {
Bukkit.getConsoleSender()
.sendMessage(ChatColor.RED + "[QuickShop] Failed to check for an update on SpigotMC.org! It might be an internet issue or the SpigotMC host is down. If you want disable the update checker, you can disable in config.yml, but we still high-recommend check for updates on SpigotMC.org often.");
return new UpdateInfomation(null, false);
return new UpdateInfomation(false, null);
}
}
public static void replaceTheJar(byte[] data) throws RuntimeException, IOException {
File pluginFolder = new File("plugins");
if (!pluginFolder.exists())
throw new RuntimeException("Can't find the plugins folder.");
if (!pluginFolder.isDirectory())
throw new RuntimeException("Plugins not a folder.");
File[] plugins = pluginFolder.listFiles();
if (plugins == null)
throw new IOException("Can't get the files in plugins folder");
File quickshop = null;
for (File plugin : plugins) {
try {
PluginDescriptionFile desc = QuickShop.instance.getPluginLoader().getPluginDescription(plugin);
if (!desc.getName().equals(QuickShop.instance.getDescription().getName()))
continue;
Util.debugLog("Selected: " + plugin.getPath());
quickshop = plugin;
break;
} catch (InvalidDescriptionException e) { //Ignore }
}
}
if (quickshop == null)
throw new RuntimeException("Failed to get QuickShop Jar File.");
OutputStream outputStream = new FileOutputStream(quickshop, false);
outputStream.write(data);
outputStream.flush();
outputStream.close();
}
public static byte[] downloadUpdatedJar() throws IOException {
org.kohsuke.github.GHRelease ghRelease = GitHub.connectAnonymously().getUser("Ghost-chu")
.getRepository("QuickShop-Reremake").getLatestRelease();
@@ -122,4 +92,34 @@ public class Updater {
Util.debugLog("Download complete.");
return os.toByteArray();
}
public static void replaceTheJar(byte[] data) throws RuntimeException, IOException {
File pluginFolder = new File("plugins");
if (!pluginFolder.exists())
throw new RuntimeException("Can't find the plugins folder.");
if (!pluginFolder.isDirectory())
throw new RuntimeException("Plugins not a folder.");
File[] plugins = pluginFolder.listFiles();
if (plugins == null)
throw new IOException("Can't get the files in plugins folder");
File quickshop = null;
for (File plugin : plugins) {
try {
PluginDescriptionFile desc = QuickShop.instance.getPluginLoader().getPluginDescription(plugin);
if (!desc.getName().equals(QuickShop.instance.getDescription().getName()))
continue;
Util.debugLog("Selected: " + plugin.getPath());
quickshop = plugin;
break;
} catch (InvalidDescriptionException e) { //Ignore }
}
}
if (quickshop == null)
throw new RuntimeException("Failed to get QuickShop Jar File.");
OutputStream outputStream = new FileOutputStream(quickshop, false);
outputStream.write(data);
outputStream.flush();
outputStream.close();
}
}
File diff suppressed because it is too large. Load diff
@@ -10,10 +10,23 @@ import org.maxgamer.quickshop.QuickShop;
import org.maxgamer.quickshop.Shop.Shop;
import org.maxgamer.quickshop.Util.Util;
class DisplayRunnable implements Runnable {
@Override
public void run() {
@SuppressWarnings("unchecked") ArrayList<Shop> pendingCheckDisplayCopy = (ArrayList<Shop>) QuickShop.instance
.getDisplayWatcher().getPendingCheckDisplay().clone();
for (Shop shop : pendingCheckDisplayCopy) {
shop.checkDisplay();
}
pendingCheckDisplayCopy.clear();
QuickShop.instance.getDisplayWatcher().getPendingCheckDisplay().clear();
}
}
@Data
public class DisplayWatcher {
private QuickShop plugin;
private ArrayList<Shop> pendingCheckDisplay = new ArrayList<>();
private QuickShop plugin;
public DisplayWatcher(QuickShop plugin) {
this.plugin = plugin;
@@ -47,16 +60,3 @@ public class DisplayWatcher {
}
}
class DisplayRunnable implements Runnable {
@Override
public void run() {
@SuppressWarnings("unchecked") ArrayList<Shop> pendingCheckDisplayCopy = (ArrayList<Shop>) QuickShop.instance
.getDisplayWatcher().getPendingCheckDisplay().clone();
for (Shop shop : pendingCheckDisplayCopy) {
shop.checkDisplay();
}
pendingCheckDisplayCopy.clear();
QuickShop.instance.getDisplayWatcher().getPendingCheckDisplay().clear();
}
}
@@ -13,8 +13,8 @@ import org.jetbrains.annotations.*;
import org.maxgamer.quickshop.QuickShop;
public class LogWatcher implements Runnable {
private PrintStream ps;
private Queue<String> logs = new LinkedList<>();
private PrintStream ps;
public LogWatcher(QuickShop plugin, File log) {
try {
@@ -32,6 +32,27 @@ public class LogWatcher implements Runnable {
}
}
public void add(@NotNull String s) {
new BukkitRunnable() {
public void run() {
logs.add(s);
}
}.runTask(QuickShop.instance);
}
public void close() {
if (ps != null)
this.ps.close();
ps = null;
}
public void log(@NonNull String log) {
Date date = Calendar.getInstance().getTime();
Timestamp time = new Timestamp(date.getTime());
this.add("[" + time.toString() + "] " + log);
}
@Override
public void run() {
new BukkitRunnable() {
@@ -46,24 +67,4 @@ public class LogWatcher implements Runnable {
}
}.runTask(QuickShop.instance);
}
public void add(@NotNull String s) {
new BukkitRunnable() {
public void run() {
logs.add(s);
}
}.runTask(QuickShop.instance);
}
public void close() {
if (ps != null)
this.ps.close();
ps = null;
}
public void log(@NonNull String log) {
Date date = Calendar.getInstance().getTime();
Timestamp time = new Timestamp(date.getTime());
this.add("[" + time.toString() + "] " + log);
}
}
@@ -11,10 +11,10 @@ import org.bukkit.scheduler.BukkitRunnable;
import org.maxgamer.quickshop.QuickShop;
public class SyncTaskWatcher {
private QuickShop plugin;
@Getter private Queue<Entity> entityRemoveQueue = new LinkedList<>();
@Getter private Queue<ItemStack> itemStackRemoveQueue = new LinkedList<>();
@Getter private Queue<InventoryEditContainer> inventoryEditQueue = new LinkedList<>();
@Getter private Queue<ItemStack> itemStackRemoveQueue = new LinkedList<>();
private QuickShop plugin;
/**
* SyncTaskWatcher is a loop task runner, it can be add from async thread and run in Bukkit main thread.
@@ -1,137 +1,137 @@
package org.maxgamer.quickshop.Watcher;
import java.util.List;
import java.util.Random;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
import org.jetbrains.annotations.*;
import org.maxgamer.quickshop.QuickShop;
import org.maxgamer.quickshop.Util.MsgUtil;
import org.maxgamer.quickshop.Util.UpdateInfomation;
import org.maxgamer.quickshop.Util.Updater;
public class UpdateWatcher implements Listener {
private static BukkitTask cronTask = null;
private static boolean hasNewUpdate = false;
private static UpdateInfomation info = null;
public static void init() {
cronTask = new BukkitRunnable() {
@Override
public void run() {
info = Updater.checkUpdate();
if (info.getVersion() == null) {
hasNewUpdate = false;
return;
}
if (info.getVersion().equals(QuickShop.getVersion())) {
hasNewUpdate = false;
return;
}
hasNewUpdate = true;
if (!info.isBeta()) {
QuickShop.instance.getLogger().info("A new version of QuickShop has been released!");
QuickShop.instance.getLogger().info("Update here: https://www.spigotmc.org/resources/62575/");
Bukkit.getOnlinePlayers().forEach(player -> {
if (player.hasPermission("quickshop.alert")) {
List<String> notifys = MsgUtil.getI18nYaml().getStringList("updatenotify.list");
Random random = new Random();
int notifyNum = -1;
if (notifys.size() > 1)
notifyNum = random.nextInt(notifys.size());
String notify;
if (notifyNum > 0) { //Translate bug.
notify = notifys.get(notifyNum);
} else {
notify = "New update {0} now avaliable! Please update!";
}
notify = MsgUtil.fillArgs(notify, info.getVersion(), QuickShop.getVersion());
TextComponent updatenow = new TextComponent(ChatColor.AQUA + MsgUtil
.getMessage("updatenotify.buttontitle"));
TextComponent onekeyupdate = new TextComponent(ChatColor.YELLOW + MsgUtil
.getMessage("updatenotify.onekeybuttontitle"));
updatenow
.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://www.spigotmc.org/resources/62575/"));
onekeyupdate.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/qs update"));
TextComponent finallyText = new TextComponent(updatenow, new TextComponent(" "), onekeyupdate);
player.sendMessage(ChatColor.GREEN + "---------------------------------------------------");
player.sendMessage(ChatColor.GREEN + notify);
player.spigot().sendMessage(finallyText);
player.sendMessage(ChatColor.GREEN + "---------------------------------------------------");
}
});
} else {
QuickShop.instance.getLogger().info("A new BETA version of QuickShop is available!");
QuickShop.instance.getLogger().info("Update here: https://www.spigotmc.org/resources/62575/");
QuickShop.instance.getLogger().info("This is a BETA version, which means you should use it with caution.");
}
}
}.runTaskTimerAsynchronously(QuickShop.instance, 1, 20 * 60 * 60);
}
public static void uninit() {
hasNewUpdate = false;
if (cronTask == null) {
return;
}
cronTask.cancel();
}
@EventHandler
public void playerJoin(PlayerJoinEvent e) {
new BukkitRunnable() {
@Override
public void run() {
if (hasNewUpdate && e.getPlayer().hasPermission("quickshop.alert")) {
if (!info.isBeta()) {
List<String> notifys = MsgUtil.getI18nYaml().getStringList("updatenotify.list");
Random random = new Random();
int notifyNum = random.nextInt(notifys.size());
String notify = notifys.get(notifyNum);
notify = MsgUtil.fillArgs(notify, info.getVersion(), QuickShop.getVersion());
TextComponent updatenow = new TextComponent(ChatColor.AQUA + MsgUtil
.getMessage("updatenotify.buttontitle"));
TextComponent onekeyupdate = new TextComponent(ChatColor.YELLOW + MsgUtil
.getMessage("updatenotify.onekeybuttontitle"));
updatenow
.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://www.spigotmc.org/resources/62575/"));
onekeyupdate.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/qs update"));
TextComponent finallyText = new TextComponent(updatenow, new TextComponent(" "), onekeyupdate);
e.getPlayer().sendMessage(ChatColor.GREEN + "---------------------------------------------------");
e.getPlayer().sendMessage(ChatColor.GREEN + notify);
e.getPlayer().spigot().sendMessage(finallyText);
e.getPlayer().sendMessage(ChatColor.GREEN + "---------------------------------------------------");
} else {
e.getPlayer().sendMessage(ChatColor.GRAY + "A new BETA version of QuickShop has been released!");
e.getPlayer().sendMessage(ChatColor.GRAY + "Update here: https://www.spigotmc.org/resources/62575/");
e.getPlayer()
.sendMessage(ChatColor.GRAY + "This is a BETA version, which means you should use it with caution.");
}
}
}
}.runTaskLater(QuickShop.instance, 80);
}
public static String fixVer(@NotNull String originalVer) {
originalVer = originalVer.replaceAll("Reremake", "");
originalVer = originalVer.trim();
return originalVer;
}
}
package org.maxgamer.quickshop.Watcher;
import java.util.List;
import java.util.Random;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
import org.jetbrains.annotations.*;
import org.maxgamer.quickshop.QuickShop;
import org.maxgamer.quickshop.Util.MsgUtil;
import org.maxgamer.quickshop.Util.UpdateInfomation;
import org.maxgamer.quickshop.Util.Updater;
public class UpdateWatcher implements Listener {
private static BukkitTask cronTask = null;
private static boolean hasNewUpdate = false;
private static UpdateInfomation info = null;
public static String fixVer(@NotNull String originalVer) {
originalVer = originalVer.replaceAll("Reremake", "");
originalVer = originalVer.trim();
return originalVer;
}
public static void init() {
cronTask = new BukkitRunnable() {
@Override
public void run() {
info = Updater.checkUpdate();
if (info.getVersion() == null) {
hasNewUpdate = false;
return;
}
if (info.getVersion().equals(QuickShop.getVersion())) {
hasNewUpdate = false;
return;
}
hasNewUpdate = true;
if (!info.isBeta()) {
QuickShop.instance.getLogger().info("A new version of QuickShop has been released!");
QuickShop.instance.getLogger().info("Update here: https://www.spigotmc.org/resources/62575/");
Bukkit.getOnlinePlayers().forEach(player -> {
if (player.hasPermission("quickshop.alert")) {
List<String> notifys = MsgUtil.getI18nYaml().getStringList("updatenotify.list");
Random random = new Random();
int notifyNum = -1;
if (notifys.size() > 1)
notifyNum = random.nextInt(notifys.size());
String notify;
if (notifyNum > 0) { //Translate bug.
notify = notifys.get(notifyNum);
} else {
notify = "New update {0} now avaliable! Please update!";
}
notify = MsgUtil.fillArgs(notify, info.getVersion(), QuickShop.getVersion());
TextComponent updatenow = new TextComponent(ChatColor.AQUA + MsgUtil
.getMessage("updatenotify.buttontitle"));
TextComponent onekeyupdate = new TextComponent(ChatColor.YELLOW + MsgUtil
.getMessage("updatenotify.onekeybuttontitle"));
updatenow
.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://www.spigotmc.org/resources/62575/"));
onekeyupdate.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/qs update"));
TextComponent finallyText = new TextComponent(updatenow, new TextComponent(" "), onekeyupdate);
player.sendMessage(ChatColor.GREEN + "---------------------------------------------------");
player.sendMessage(ChatColor.GREEN + notify);
player.spigot().sendMessage(finallyText);
player.sendMessage(ChatColor.GREEN + "---------------------------------------------------");
}
});
} else {
QuickShop.instance.getLogger().info("A new BETA version of QuickShop is available!");
QuickShop.instance.getLogger().info("Update here: https://www.spigotmc.org/resources/62575/");
QuickShop.instance.getLogger().info("This is a BETA version, which means you should use it with caution.");
}
}
}.runTaskTimerAsynchronously(QuickShop.instance, 1, 20 * 60 * 60);
}
public static void uninit() {
hasNewUpdate = false;
if (cronTask == null) {
return;
}
cronTask.cancel();
}
@EventHandler
public void playerJoin(PlayerJoinEvent e) {
new BukkitRunnable() {
@Override
public void run() {
if (hasNewUpdate && e.getPlayer().hasPermission("quickshop.alert")) {
if (!info.isBeta()) {
List<String> notifys = MsgUtil.getI18nYaml().getStringList("updatenotify.list");
Random random = new Random();
int notifyNum = random.nextInt(notifys.size());
String notify = notifys.get(notifyNum);
notify = MsgUtil.fillArgs(notify, info.getVersion(), QuickShop.getVersion());
TextComponent updatenow = new TextComponent(ChatColor.AQUA + MsgUtil
.getMessage("updatenotify.buttontitle"));
TextComponent onekeyupdate = new TextComponent(ChatColor.YELLOW + MsgUtil
.getMessage("updatenotify.onekeybuttontitle"));
updatenow
.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://www.spigotmc.org/resources/62575/"));
onekeyupdate.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/qs update"));
TextComponent finallyText = new TextComponent(updatenow, new TextComponent(" "), onekeyupdate);
e.getPlayer().sendMessage(ChatColor.GREEN + "---------------------------------------------------");
e.getPlayer().sendMessage(ChatColor.GREEN + notify);
e.getPlayer().spigot().sendMessage(finallyText);
e.getPlayer().sendMessage(ChatColor.GREEN + "---------------------------------------------------");
} else {
e.getPlayer().sendMessage(ChatColor.GRAY + "A new BETA version of QuickShop has been released!");
e.getPlayer().sendMessage(ChatColor.GRAY + "Update here: https://www.spigotmc.org/resources/62575/");
e.getPlayer()
.sendMessage(ChatColor.GRAY + "This is a BETA version, which means you should use it with caution.");
}
}
}
}.runTaskLater(QuickShop.instance, 80);
}
}