From 83d8965c233ada492287b4779d5829818d704d0f Mon Sep 17 00:00:00 2001 From: AppleDash Date: Mon, 4 Nov 2019 12:25:17 -0500 Subject: [PATCH] General code cleanup --- .../appledash/saneeconomy/SaneEconomy.java | 90 +++++++++---------- .../saneeconomy/command/BalanceCommand.java | 4 +- .../command/BalanceTopCommand.java | 1 - .../command/EconomyAdminCommand.java | 10 +-- .../saneeconomy/command/PayCommand.java | 2 +- .../saneeconomy/command/SaneEcoCommand.java | 2 +- .../saneeconomy/economy/Currency.java | 17 ++-- .../saneeconomy/economy/EconomyManager.java | 37 ++++---- .../backend/EconomyStorageBackend.java | 1 - .../type/EconomyStorageBackendCaching.java | 12 +-- .../type/EconomyStorageBackendJSON.java | 24 ++--- .../type/EconomyStorageBackendMySQL.java | 72 +++++++-------- .../economy/economable/EconomableFaction.java | 2 +- .../economy/economable/EconomableGeneric.java | 4 +- .../economy/economable/EconomablePlayer.java | 4 +- .../logger/TransactionLoggerMySQL.java | 12 +-- .../economy/transaction/Transaction.java | 16 ++-- .../transaction/TransactionReason.java | 2 +- .../transaction/TransactionResult.java | 10 +-- .../event/SaneEconomyTransactionEvent.java | 4 +- .../listeners/JoinQuitListener.java | 20 ++--- .../updates/GithubVersionChecker.java | 8 +- .../saneeconomy/updates/VersionComparer.java | 7 +- .../appledash/saneeconomy/utils/MapUtil.java | 6 +- .../saneeconomy/utils/NumberUtils.java | 5 +- .../saneeconomy/utils/PlayerUtils.java | 5 +- .../utils/SaneEconomyConfiguration.java | 62 ++++++------- .../appledash/saneeconomy/utils/WebUtils.java | 14 ++- .../utils/database/MySQLConnection.java | 16 ++-- .../saneeconomy/vault/EconomySaneEconomy.java | 52 +++++------ .../saneeconomy/vault/VaultHook.java | 4 +- .../saneeconomy/test/EconomyManagerTest.java | 46 +++++----- .../saneeconomy/test/NumberUtilsTest.java | 2 +- .../test/mock/MockEconomyStorageBackend.java | 2 +- .../test/mock/MockOfflinePlayer.java | 4 +- .../saneeconomy/test/mock/MockServer.java | 8 +- .../SaneEconomyMobKills.java | 18 ++-- .../listeners/EntityDamageListener.java | 28 +++--- .../saneeconomy/onlinetime/Payout.java | 14 +-- .../onlinetime/SaneEconomyOnlineTime.java | 21 ++--- .../SaneEconomySignShop.java | 32 +++---- .../listeners/BreakListener.java | 4 +- .../listeners/InteractListener.java | 18 ++-- .../listeners/SignChangeListener.java | 20 ++--- .../signshop/ShopTransaction.java | 16 ++-- .../signshop/SignShop.java | 20 ++--- .../signshop/SignShopManager.java | 8 +- .../signshop/storage/SignShopStorageJSON.java | 25 +++--- .../util/DefaultHashMap.java | 2 +- .../util/ItemDatabase.java | 14 +-- .../saneeconomysignshop/util/ItemInfo.java | 4 +- .../saneeconomysignshop/util/ItemLimits.java | 4 +- .../util/LimitManager.java | 22 ++--- .../saneeconomysignshop/util/Pair.java | 4 +- .../util/SerializableLocation.java | 2 +- 55 files changed, 435 insertions(+), 428 deletions(-) diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/SaneEconomy.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/SaneEconomy.java index ac7cb59..7c00fce 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/SaneEconomy.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/SaneEconomy.java @@ -38,11 +38,11 @@ public class SaneEconomy extends SanePlugin implements ISaneEconomy { private final Map COMMANDS = new HashMap() { { - put("balance", new BalanceCommand(SaneEconomy.this)); - put("ecoadmin", new EconomyAdminCommand(SaneEconomy.this)); - put("pay", new PayCommand(SaneEconomy.this)); - put("saneeconomy", new SaneEcoCommand(SaneEconomy.this)); - put("balancetop", new BalanceTopCommand(SaneEconomy.this)); + this.put("balance", new BalanceCommand(SaneEconomy.this)); + this.put("ecoadmin", new EconomyAdminCommand(SaneEconomy.this)); + this.put("pay", new PayCommand(SaneEconomy.this)); + this.put("saneeconomy", new SaneEcoCommand(SaneEconomy.this)); + this.put("balancetop", new BalanceTopCommand(SaneEconomy.this)); } }; @@ -54,8 +54,8 @@ public class SaneEconomy extends SanePlugin implements ISaneEconomy { public void onEnable() { super.onEnable(); - if (!loadConfig()) { /* Invalid backend type or connection error of some sort */ - shutdown(); + if (!this.loadConfig()) { /* Invalid backend type or connection error of some sort */ + this.shutdown(); return; } @@ -63,24 +63,24 @@ public class SaneEconomy extends SanePlugin implements ISaneEconomy { Locale.setDefault(Locale.ENGLISH); } - loadCommands(); - loadListeners(); + this.loadCommands(); + this.loadListeners(); - if (getServer().getPluginManager().isPluginEnabled("Vault")) { - vaultHook = new VaultHook(this); - vaultHook.hook(); - getLogger().info("Hooked into Vault."); + if (this.getServer().getPluginManager().isPluginEnabled("Vault")) { + this.vaultHook = new VaultHook(this); + this.vaultHook.hook(); + this.getLogger().info("Hooked into Vault."); } else { - getLogger().info("Not hooking into Vault because it isn't loaded."); + this.getLogger().info("Not hooking into Vault because it isn't loaded."); } if (this.getConfig().getBoolean("update-check", true)) { - versionChecker = new GithubVersionChecker("SaneEconomyCore", this.getDescription().getVersion().replace("-SNAPSHOT", "")); - this.getServer().getScheduler().runTaskAsynchronously(this, versionChecker::checkUpdateAvailable); + this.versionChecker = new GithubVersionChecker("SaneEconomyCore", this.getDescription().getVersion().replace("-SNAPSHOT", "")); + this.getServer().getScheduler().runTaskAsynchronously(this, this.versionChecker::checkUpdateAvailable); } - getServer().getScheduler().runTaskTimerAsynchronously(this, () -> { - economyManager.getBackend().reloadTopPlayerBalances(); + this.getServer().getScheduler().runTaskTimerAsynchronously(this, () -> { + this.economyManager.getBackend().reloadTopPlayerBalances(); }, 0L, (20L * this.getConfig().getLong("economy.baltop-update-interval", 300L)) /* Update baltop every 5 minutes by default */); if (this.getConfig().getBoolean("multi-server-sync", false)) { @@ -129,9 +129,9 @@ public class SaneEconomy extends SanePlugin implements ISaneEconomy { @Override public void onDisable() { - if (vaultHook != null) { - getLogger().info("Unhooking from Vault."); - vaultHook.unhook(); + if (this.vaultHook != null) { + this.getLogger().info("Unhooking from Vault."); + this.vaultHook.unhook(); } this.flushEconomyManager(); @@ -143,8 +143,8 @@ public class SaneEconomy extends SanePlugin implements ISaneEconomy { this.economyManager.getBackend().waitUntilFlushed(); if (this.economyManager.getBackend() instanceof EconomyStorageBackendMySQL) { - ((EconomyStorageBackendMySQL) economyManager.getBackend()).closeConnections(); - if (!((EconomyStorageBackendMySQL) economyManager.getBackend()).getConnection().getConnection().isFinished()) { + ((EconomyStorageBackendMySQL) this.economyManager.getBackend()).closeConnections(); + if (!((EconomyStorageBackendMySQL) this.economyManager.getBackend()).getConnection().getConnection().isFinished()) { this.getLogger().warning("SaneDatabase didn't terminate all threads, something weird is going on?"); } } @@ -152,15 +152,15 @@ public class SaneEconomy extends SanePlugin implements ISaneEconomy { } public boolean loadConfig() { - File configFile = new File(getDataFolder(), "config.yml"); + File configFile = new File(this.getDataFolder(), "config.yml"); - if (configFile.exists() && getConfig().getBoolean("debug", false)) { - getLogger().info("Resetting configuration to default since debug == true."); + if (configFile.exists() && this.getConfig().getBoolean("debug", false)) { + this.getLogger().info("Resetting configuration to default since debug == true."); configFile.delete(); - saveDefaultConfig(); - reloadConfig(); - getConfig().set("debug", true); - saveConfig(); + this.saveDefaultConfig(); + this.reloadConfig(); + this.getConfig().set("debug", true); + this.saveConfig(); } else { if (!configFile.exists()) { this.saveDefaultConfig(); @@ -172,32 +172,32 @@ public class SaneEconomy extends SanePlugin implements ISaneEconomy { SaneEconomyConfiguration config = new SaneEconomyConfiguration(this); - economyManager = config.loadEconomyBackend(); - transactionLogger = config.loadLogger(); + this.economyManager = config.loadEconomyBackend(); + this.transactionLogger = config.loadLogger(); - saveConfig(); + this.saveConfig(); - return economyManager != null; + return this.economyManager != null; } private void loadCommands() { - getLogger().info("Initializing commands..."); - COMMANDS.forEach((name, command) -> getCommand(name).setExecutor(command)); - getLogger().info("Initialized commands."); + this.getLogger().info("Initializing commands..."); + this.COMMANDS.forEach((name, command) -> this.getCommand(name).setExecutor(command)); + this.getLogger().info("Initialized commands."); } private void loadListeners() { - getLogger().info("Initializing listeners..."); - getServer().getPluginManager().registerEvents(new JoinQuitListener(this), this); - getLogger().info("Initialized listeners."); + this.getLogger().info("Initializing listeners..."); + this.getServer().getPluginManager().registerEvents(new JoinQuitListener(this), this); + this.getLogger().info("Initialized listeners."); } private void shutdown() { - getServer().getPluginManager().disablePlugin(this); + this.getServer().getPluginManager().disablePlugin(this); } public GithubVersionChecker getVersionChecker() { - return versionChecker; + return this.versionChecker; } /** @@ -206,7 +206,7 @@ public class SaneEconomy extends SanePlugin implements ISaneEconomy { */ @Override public EconomyManager getEconomyManager() { - return economyManager; + return this.economyManager; } /** @@ -215,7 +215,7 @@ public class SaneEconomy extends SanePlugin implements ISaneEconomy { */ @Override public Optional getTransactionLogger() { - return Optional.ofNullable(transactionLogger); + return Optional.ofNullable(this.transactionLogger); } /** @@ -237,6 +237,6 @@ public class SaneEconomy extends SanePlugin implements ISaneEconomy { @Override public VaultHook getVaultHook() { - return vaultHook; + return this.vaultHook; } } diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/command/BalanceCommand.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/command/BalanceCommand.java index 9328330..388954c 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/command/BalanceCommand.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/command/BalanceCommand.java @@ -66,9 +66,9 @@ public class BalanceCommand extends SaneCommand { } if (sender == player) { - this.saneEconomy.getMessenger().sendMessage(sender, "Your balance is {1}.", saneEconomy.getEconomyManager().getFormattedBalance(Economable.wrap(player))); + this.saneEconomy.getMessenger().sendMessage(sender, "Your balance is {1}.", this.saneEconomy.getEconomyManager().getFormattedBalance(Economable.wrap(player))); } else { - this.saneEconomy.getMessenger().sendMessage(sender, "Balance for {1} is {2}.", playerName, saneEconomy.getEconomyManager().getFormattedBalance(Economable.wrap(player))); + this.saneEconomy.getMessenger().sendMessage(sender, "Balance for {1} is {2}.", playerName, this.saneEconomy.getEconomyManager().getFormattedBalance(Economable.wrap(player))); } } } diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/command/BalanceTopCommand.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/command/BalanceTopCommand.java index 5bc64e0..93192c1 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/command/BalanceTopCommand.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/command/BalanceTopCommand.java @@ -4,7 +4,6 @@ import org.appledash.saneeconomy.SaneEconomy; import org.appledash.sanelib.command.SaneCommand; import org.appledash.sanelib.command.exception.CommandException; import org.appledash.sanelib.command.exception.type.usage.TooManyArgumentsException; -import org.bukkit.OfflinePlayer; import org.bukkit.command.CommandSender; import java.math.BigDecimal; diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/command/EconomyAdminCommand.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/command/EconomyAdminCommand.java index c12d0c2..dd1c54b 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/command/EconomyAdminCommand.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/command/EconomyAdminCommand.java @@ -72,7 +72,7 @@ public class EconomyAdminCommand extends SaneCommand { return; } - EconomyManager ecoMan = saneEconomy.getEconomyManager(); + EconomyManager ecoMan = this.saneEconomy.getEconomyManager(); Economable economable = Economable.wrap(targetPlayer); BigDecimal amount = NumberUtils.parseAndFilter(ecoMan.getCurrency(), sAmount); @@ -95,7 +95,7 @@ public class EconomyAdminCommand extends SaneCommand { ); if (this.saneEconomy.getConfig().getBoolean("economy.notify-admin-give") && targetPlayer.isOnline()) { - this.saneEconomy.getMessenger().sendMessage((Player) targetPlayer, "{1} has given you {2}. Your balance is now {3}.", + this.saneEconomy.getMessenger().sendMessage((CommandSender) targetPlayer, "{1} has given you {2}. Your balance is now {3}.", sender.getName(), ecoMan.getCurrency().formatAmount(amount), ecoMan.getCurrency().formatAmount(newAmount) @@ -118,7 +118,7 @@ public class EconomyAdminCommand extends SaneCommand { ); if (this.saneEconomy.getConfig().getBoolean("economy.notify-admin-take") && targetPlayer.isOnline()) { - this.saneEconomy.getMessenger().sendMessage((Player) targetPlayer, "{1} has taken {2} from you. Your balance is now {3}.", + this.saneEconomy.getMessenger().sendMessage((CommandSender) targetPlayer, "{1} has taken {2} from you. Your balance is now {3}.", sender.getName(), ecoMan.getCurrency().formatAmount(amount), ecoMan.getCurrency().formatAmount(newAmount) @@ -133,7 +133,7 @@ public class EconomyAdminCommand extends SaneCommand { ecoMan.setBalance(economable, amount); this.saneEconomy.getMessenger().sendMessage(sender, "Balance for {1} set to {2}.", sTargetPlayer, ecoMan.getCurrency().formatAmount(amount)); - saneEconomy.getTransactionLogger().ifPresent((logger) -> { + this.saneEconomy.getTransactionLogger().ifPresent((logger) -> { // FIXME: This is a silly hack to get it to log. if (oldBal.compareTo(BigDecimal.ZERO) > 0) { logger.logTransaction(new Transaction( @@ -147,7 +147,7 @@ public class EconomyAdminCommand extends SaneCommand { }); if (this.saneEconomy.getConfig().getBoolean("economy.notify-admin-set") && targetPlayer.isOnline()) { - this.saneEconomy.getMessenger().sendMessage((Player) targetPlayer, "{1} has set your balance to {2}.", + this.saneEconomy.getMessenger().sendMessage((CommandSender) targetPlayer, "{1} has set your balance to {2}.", sender.getName(), ecoMan.getCurrency().formatAmount(amount) diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/command/PayCommand.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/command/PayCommand.java index 53689eb..38fdaf7 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/command/PayCommand.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/command/PayCommand.java @@ -52,7 +52,7 @@ public class PayCommand extends SaneCommand { throw new NeedPlayerException(); } - EconomyManager ecoMan = saneEconomy.getEconomyManager(); + EconomyManager ecoMan = this.saneEconomy.getEconomyManager(); Player fromPlayer = (Player) sender; String sToPlayer = args[0]; diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/command/SaneEcoCommand.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/command/SaneEcoCommand.java index 0613ecf..1c5bd46 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/command/SaneEcoCommand.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/command/SaneEcoCommand.java @@ -42,7 +42,7 @@ public class SaneEcoCommand extends SaneCommand { if (subCommand.equalsIgnoreCase("reload-database")) { this.saneEconomy.getMessenger().sendMessage(sender, "Reloading database..."); - saneEconomy.getEconomyManager().getBackend().reloadDatabase(); + this.saneEconomy.getEconomyManager().getBackend().reloadDatabase(); this.saneEconomy.getMessenger().sendMessage(sender, "Database reloaded."); } else if (subCommand.equalsIgnoreCase("reload-config")) { this.saneEconomy.getMessenger().sendMessage(sender, "Reloading configuration..."); diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/Currency.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/Currency.java index 826ec55..c474ea6 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/Currency.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/Currency.java @@ -76,14 +76,9 @@ public class Currency { * @return Formatted amount string. */ public String formatAmount(BigDecimal amount) { - String formatted; - if (amount.equals(BigDecimal.ONE)) { - formatted = MessageUtils.indexedFormat(balanceFormat, format.format(amount), nameSingular); - } else { - formatted = MessageUtils.indexedFormat(balanceFormat, format.format(amount), namePlural); - } - - return ChatColor.translateAlternateColorCodes('&', formatted); + return ChatColor.translateAlternateColorCodes('&', + MessageUtils.indexedFormat(this.balanceFormat, this.format.format(amount), amount.equals(BigDecimal.ONE) ? this.nameSingular : this.namePlural) + ); } /** @@ -92,7 +87,7 @@ public class Currency { * @return Singular name. */ public String getSingularName() { - return nameSingular; + return this.nameSingular; } /** @@ -101,7 +96,7 @@ public class Currency { * @return Plural name. */ public String getPluralName() { - return namePlural; + return this.namePlural; } /** @@ -109,6 +104,6 @@ public class Currency { * @return DecimalFormat instance */ public DecimalFormat getFormat() { - return format; + return this.format; } } diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/EconomyManager.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/EconomyManager.java index 8fba8e9..4b4d1be 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/EconomyManager.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/EconomyManager.java @@ -10,13 +10,10 @@ import org.appledash.saneeconomy.event.SaneEconomyTransactionEvent; import org.appledash.saneeconomy.utils.MapUtil; import org.appledash.saneeconomy.utils.NumberUtils; import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import java.awt.*; import java.math.BigDecimal; import java.util.LinkedHashMap; import java.util.Map; -import java.util.UUID; import java.util.concurrent.*; /** @@ -43,7 +40,7 @@ public class EconomyManager { * @return Currency */ public Currency getCurrency() { - return currency; + return this.currency; } /** @@ -52,7 +49,7 @@ public class EconomyManager { * @return Formatted balance */ public String getFormattedBalance(Economable player) { - return currency.formatAmount(backend.getBalance(player)); + return this.currency.formatAmount(this.backend.getBalance(player)); } /** @@ -61,7 +58,7 @@ public class EconomyManager { * @return True if they have used the economy system before, false otherwise */ public boolean accountExists(Economable player) { - return backend.accountExists(player); + return this.backend.accountExists(player); } /** @@ -74,7 +71,7 @@ public class EconomyManager { return new BigDecimal(Double.MAX_VALUE); } - return backend.getBalance(targetPlayer); + return this.backend.getBalance(targetPlayer); } @@ -85,7 +82,7 @@ public class EconomyManager { * @return True if they have requiredBalance or more, false otherwise */ public boolean hasBalance(Economable targetPlayer, BigDecimal requiredBalance) { - return (targetPlayer == Economable.CONSOLE) || (getBalance(targetPlayer).compareTo(requiredBalance) >= 0); + return (targetPlayer == Economable.CONSOLE) || (this.getBalance(targetPlayer).compareTo(requiredBalance) >= 0); } @@ -97,7 +94,7 @@ public class EconomyManager { * @throws IllegalArgumentException If amount is negative */ private void addBalance(Economable targetPlayer, BigDecimal amount) { - setBalance(targetPlayer, backend.getBalance(targetPlayer).add(amount)); + this.setBalance(targetPlayer, this.backend.getBalance(targetPlayer).add(amount)); } /** @@ -111,7 +108,7 @@ public class EconomyManager { */ private void subtractBalance(Economable targetPlayer, BigDecimal amount) { // Ensure we don't go negative. - setBalance(targetPlayer, backend.getBalance(targetPlayer).subtract(amount).max(BigDecimal.ZERO)); + this.setBalance(targetPlayer, this.backend.getBalance(targetPlayer).subtract(amount).max(BigDecimal.ZERO)); } /** @@ -121,13 +118,13 @@ public class EconomyManager { * @throws IllegalArgumentException If amount is negative */ public void setBalance(Economable targetPlayer, BigDecimal amount) { - amount = NumberUtils.filterAmount(currency, amount); + amount = NumberUtils.filterAmount(this.currency, amount); if (targetPlayer == Economable.CONSOLE) { return; } - backend.setBalance(targetPlayer, amount); + this.backend.setBalance(targetPlayer, amount); } /** @@ -172,20 +169,20 @@ public class EconomyManager { } if (transaction.isSenderAffected()) { // Sender should have balance taken from them - if (!hasBalance(sender, amount)) { + if (!this.hasBalance(sender, amount)) { return new TransactionResult(transaction, TransactionResult.Status.ERR_NOT_ENOUGH_FUNDS); } - subtractBalance(sender, amount); + this.subtractBalance(sender, amount); } if (transaction.isReceiverAffected()) { // Receiver should have balance added to them - addBalance(receiver, amount); + this.addBalance(receiver, amount); } - saneEconomy.getTransactionLogger().ifPresent((logger) -> logger.logTransaction(transaction)); + this.saneEconomy.getTransactionLogger().ifPresent((logger) -> logger.logTransaction(transaction)); - return new TransactionResult(transaction, getBalance(sender), getBalance(receiver)); + return new TransactionResult(transaction, this.getBalance(sender), this.getBalance(receiver)); } /** @@ -194,7 +191,7 @@ public class EconomyManager { * @return Map of OfflinePlayer to Double */ public Map getTopBalances(int amount, int offset) { - LinkedHashMap uuidBalances = backend.getTopBalances(); + LinkedHashMap uuidBalances = this.backend.getTopBalances(); /* TODO uuidBalances.forEach((uuid, balance) -> { @@ -211,7 +208,7 @@ public class EconomyManager { } public EconomyStorageBackend getBackend() { - return backend; + return this.backend; } /** @@ -219,6 +216,6 @@ public class EconomyManager { * @return Server economy account, or null if none. */ public String getServerAccountName() { - return serverAccountName; + return this.serverAccountName; } } diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/backend/EconomyStorageBackend.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/backend/EconomyStorageBackend.java index c50a566..90d371a 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/backend/EconomyStorageBackend.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/backend/EconomyStorageBackend.java @@ -5,7 +5,6 @@ import org.appledash.saneeconomy.economy.economable.Economable; import java.math.BigDecimal; import java.util.LinkedHashMap; import java.util.Map; -import java.util.UUID; /** * Created by AppleDash on 6/13/2016. diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/backend/type/EconomyStorageBackendCaching.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/backend/type/EconomyStorageBackendCaching.java index 19c3ffc..9cf17bc 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/backend/type/EconomyStorageBackendCaching.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/backend/type/EconomyStorageBackendCaching.java @@ -24,20 +24,20 @@ public abstract class EconomyStorageBackendCaching implements EconomyStorageBack @Override public boolean accountExists(Economable economable) { - return balances.containsKey(economable.getUniqueIdentifier()); + return this.balances.containsKey(economable.getUniqueIdentifier()); } @Override public BigDecimal getBalance(Economable economable) { - if (!accountExists(economable)) { + if (!this.accountExists(economable)) { return BigDecimal.ZERO; } - return balances.get(economable.getUniqueIdentifier()); + return this.balances.get(economable.getUniqueIdentifier()); } public LinkedHashMap getTopBalances() { - return topBalances; + return this.topBalances; } @Override @@ -48,12 +48,12 @@ public abstract class EconomyStorageBackendCaching implements EconomyStorageBack balances.put(this.uuidToName.get(identifier), balance); }); - topBalances = MapUtil.sortByValue(balances); + this.topBalances = MapUtil.sortByValue(balances); } @Override public Map getAllBalances() { - return ImmutableMap.copyOf(balances); + return ImmutableMap.copyOf(this.balances); } @Override diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/backend/type/EconomyStorageBackendJSON.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/backend/type/EconomyStorageBackendJSON.java index d395e20..2eb52c6 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/backend/type/EconomyStorageBackendJSON.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/backend/type/EconomyStorageBackendJSON.java @@ -1,7 +1,5 @@ package org.appledash.saneeconomy.economy.backend.type; -import com.avaje.ebeaninternal.server.cluster.DataHolder; -import com.google.common.reflect.TypeToken; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.annotations.SerializedName; @@ -18,7 +16,7 @@ import java.util.concurrent.ConcurrentHashMap; */ public class EconomyStorageBackendJSON extends EconomyStorageBackendCaching { private final Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().create(); - private File file; + private final File file; public EconomyStorageBackendJSON(File file) { this.file = file; @@ -26,21 +24,21 @@ public class EconomyStorageBackendJSON extends EconomyStorageBackendCaching { @Override public void setBalance(Economable economable, BigDecimal newBalance) { - balances.put(economable.getUniqueIdentifier(), newBalance); - saveDatabase(); + this.balances.put(economable.getUniqueIdentifier(), newBalance); + this.saveDatabase(); } @Override @SuppressWarnings("unchecked") public void reloadDatabase() { - if (!file.exists()) { + if (!this.file.exists()) { return; } try { // try to load the old format and convert it // if that fails, load the new format - DataHolderOld dataHolder = gson.fromJson(new FileReader(file), DataHolderOld.class); + DataHolderOld dataHolder = this.gson.fromJson(new FileReader(this.file), DataHolderOld.class); this.balances = new ConcurrentHashMap<>(); this.uuidToName = new ConcurrentHashMap<>(dataHolder.uuidToName); @@ -53,7 +51,7 @@ public class EconomyStorageBackendJSON extends EconomyStorageBackendCaching { throw new RuntimeException("Failed to load database!", e); } catch (Exception e) { try { - DataHolder dataHolder = gson.fromJson(new FileReader(file), DataHolder.class); + DataHolder dataHolder = this.gson.fromJson(new FileReader(this.file), DataHolder.class); this.balances = new ConcurrentHashMap<>(dataHolder.balances); this.uuidToName = new ConcurrentHashMap<>(dataHolder.uuidToName); } catch (FileNotFoundException ex) { @@ -68,33 +66,35 @@ public class EconomyStorageBackendJSON extends EconomyStorageBackendCaching { } private synchronized void saveDatabase() { - try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file, false))) { + try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(this.file, false))) { DataHolder dataHolder = new DataHolder(this.balances, this.uuidToName); - bufferedWriter.write(gson.toJson(dataHolder)); + bufferedWriter.write(this.gson.toJson(dataHolder)); } catch (IOException e) { throw new RuntimeException("Failed to save database", e); } } + @SuppressWarnings("FieldMayBeFinal") private static class DataHolderOld { @SerializedName("balances") private Map balances; @SerializedName("uuidToName") private Map uuidToName; - public DataHolderOld(Map balances, Map uuidToName) { + DataHolderOld(Map balances, Map uuidToName) { this.balances = balances; this.uuidToName = uuidToName; } } + @SuppressWarnings("FieldMayBeFinal") private static class DataHolder { @SerializedName("balances") private Map balances; @SerializedName("uuidToName") private Map uuidToName; - public DataHolder(Map balances, Map uuidToName) { + DataHolder(Map balances, Map uuidToName) { this.balances = balances; this.uuidToName = uuidToName; } diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/backend/type/EconomyStorageBackendMySQL.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/backend/type/EconomyStorageBackendMySQL.java index f21034d..777687d 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/backend/type/EconomyStorageBackendMySQL.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/backend/type/EconomyStorageBackendMySQL.java @@ -31,13 +31,13 @@ public class EconomyStorageBackendMySQL extends EconomyStorageBackendCaching { } private void createTables() { - try (Connection conn = dbConn.openConnection()) { + try (Connection conn = this.dbConn.openConnection()) { int schemaVersion; - if (!checkTableExists(dbConn.getTable(SANEECONOMY_SCHEMA))) { + if (!this.checkTableExists(this.dbConn.getTable(SANEECONOMY_SCHEMA))) { schemaVersion = -1; } else { - PreparedStatement ps = conn.prepareStatement(String.format("SELECT `val` FROM `%s` WHERE `key` = 'schema_version'", dbConn.getTable(SANEECONOMY_SCHEMA))); + PreparedStatement ps = conn.prepareStatement(String.format("SELECT `val` FROM `%s` WHERE `key` = 'schema_version'", this.dbConn.getTable(SANEECONOMY_SCHEMA))); ResultSet rs = ps.executeQuery(); if (!rs.next()) { @@ -48,25 +48,25 @@ public class EconomyStorageBackendMySQL extends EconomyStorageBackendCaching { } if (schemaVersion == -1) { - conn.prepareStatement(String.format("CREATE TABLE IF NOT EXISTS `%s` (`key` VARCHAR(32) PRIMARY KEY, `val` TEXT)", dbConn.getTable(SANEECONOMY_SCHEMA))).executeUpdate(); - conn.prepareStatement(String.format("REPLACE INTO %s (`key`, `val`) VALUES ('schema_version', 4)", dbConn.getTable(SANEECONOMY_SCHEMA))).executeUpdate(); - conn.prepareStatement(String.format("CREATE TABLE `%s` (unique_identifier VARCHAR(128) PRIMARY KEY, last_name VARCHAR(16), balance TEXT)", dbConn.getTable(SANEECONOMY_BALANCES))).executeUpdate(); + conn.prepareStatement(String.format("CREATE TABLE IF NOT EXISTS `%s` (`key` VARCHAR(32) PRIMARY KEY, `val` TEXT)", this.dbConn.getTable(SANEECONOMY_SCHEMA))).executeUpdate(); + conn.prepareStatement(String.format("REPLACE INTO %s (`key`, `val`) VALUES ('schema_version', 4)", this.dbConn.getTable(SANEECONOMY_SCHEMA))).executeUpdate(); + conn.prepareStatement(String.format("CREATE TABLE `%s` (unique_identifier VARCHAR(128) PRIMARY KEY, last_name VARCHAR(16), balance TEXT)", this.dbConn.getTable(SANEECONOMY_BALANCES))).executeUpdate(); schemaVersion = 4; } if (schemaVersion == 2) { - conn.prepareStatement(String.format("ALTER TABLE `%s` ADD `last_name` VARCHAR(16)", dbConn.getTable(SANEECONOMY_BALANCES))).executeUpdate(); - conn.prepareStatement(String.format("REPLACE INTO %s (`key`, `val`) VALUES ('schema_version', 3)", dbConn.getTable(SANEECONOMY_SCHEMA))).executeUpdate(); + conn.prepareStatement(String.format("ALTER TABLE `%s` ADD `last_name` VARCHAR(16)", this.dbConn.getTable(SANEECONOMY_BALANCES))).executeUpdate(); + conn.prepareStatement(String.format("REPLACE INTO %s (`key`, `val`) VALUES ('schema_version', 3)", this.dbConn.getTable(SANEECONOMY_SCHEMA))).executeUpdate(); schemaVersion = 3; } if (schemaVersion == 3) { - conn.prepareStatement(String.format("ALTER TABLE `%s` ADD `balance_new` TEXT", dbConn.getTable(SANEECONOMY_BALANCES))).executeUpdate(); - conn.prepareStatement(String.format("UPDATE `%s` SET balance_new = balance", dbConn.getTable(SANEECONOMY_BALANCES))).executeUpdate(); - conn.prepareStatement(String.format("ALTER TABLE `%s` DROP COLUMN `balance`", dbConn.getTable(SANEECONOMY_BALANCES))).executeUpdate(); - conn.prepareStatement(String.format("ALTER TABLE `%s` CHANGE COLUMN `balance_new` `balance` TEXT", dbConn.getTable(SANEECONOMY_BALANCES))).executeUpdate(); - conn.prepareStatement(String.format("REPLACE INTO %s (`key`, `val`) VALUES ('schema_version', 4)", dbConn.getTable(SANEECONOMY_SCHEMA))).executeUpdate(); + conn.prepareStatement(String.format("ALTER TABLE `%s` ADD `balance_new` TEXT", this.dbConn.getTable(SANEECONOMY_BALANCES))).executeUpdate(); + conn.prepareStatement(String.format("UPDATE `%s` SET balance_new = balance", this.dbConn.getTable(SANEECONOMY_BALANCES))).executeUpdate(); + conn.prepareStatement(String.format("ALTER TABLE `%s` DROP COLUMN `balance`", this.dbConn.getTable(SANEECONOMY_BALANCES))).executeUpdate(); + conn.prepareStatement(String.format("ALTER TABLE `%s` CHANGE COLUMN `balance_new` `balance` TEXT", this.dbConn.getTable(SANEECONOMY_BALANCES))).executeUpdate(); + conn.prepareStatement(String.format("REPLACE INTO %s (`key`, `val`) VALUES ('schema_version', 4)", this.dbConn.getTable(SANEECONOMY_SCHEMA))).executeUpdate(); schemaVersion = 4; } @@ -80,9 +80,9 @@ public class EconomyStorageBackendMySQL extends EconomyStorageBackendCaching { } private boolean checkTableExists(String tableName) { - try (Connection conn = dbConn.openConnection()) { + try (Connection conn = this.dbConn.openConnection()) { PreparedStatement ps = conn.prepareStatement("SELECT * FROM information_schema.tables WHERE table_schema = ? AND table_name = ? LIMIT 1"); - ps.setString(1, dbConn.getCredentials().getDatabaseName()); + ps.setString(1, this.dbConn.getCredentials().getDatabaseName()); ps.setString(2, tableName); ps.executeQuery(); ResultSet rs = ps.getResultSet(); @@ -95,16 +95,16 @@ public class EconomyStorageBackendMySQL extends EconomyStorageBackendCaching { @Override public synchronized void reloadDatabase() { - waitUntilFlushed(); - createTables(); - try (Connection conn = dbConn.openConnection()) { - PreparedStatement ps = dbConn.prepareStatement(conn, String.format("SELECT * FROM `%s`", dbConn.getTable(SANEECONOMY_BALANCES))); + this.waitUntilFlushed(); + this.createTables(); + try (Connection conn = this.dbConn.openConnection()) { + PreparedStatement ps = this.dbConn.prepareStatement(conn, String.format("SELECT * FROM `%s`", this.dbConn.getTable(SANEECONOMY_BALANCES))); ResultSet rs = ps.executeQuery(); - balances.clear(); + this.balances.clear(); while (rs.next()) { - balances.put(rs.getString("unique_identifier"), new BigDecimal(rs.getString("balance"))); + this.balances.put(rs.getString("unique_identifier"), new BigDecimal(rs.getString("balance"))); } } catch (SQLException e) { throw new RuntimeException("Failed to reload data from SQL.", e); @@ -112,30 +112,30 @@ public class EconomyStorageBackendMySQL extends EconomyStorageBackendCaching { } @Override - public void setBalance(final Economable economable, final BigDecimal newBalance) { - final BigDecimal oldBalance = getBalance(economable); - balances.put(economable.getUniqueIdentifier(), newBalance); + public void setBalance(Economable economable, BigDecimal newBalance) { + BigDecimal oldBalance = this.getBalance(economable); + this.balances.put(economable.getUniqueIdentifier(), newBalance); - dbConn.executeAsyncOperation("set_balance_" + economable.getUniqueIdentifier(), (conn) -> { + this.dbConn.executeAsyncOperation("set_balance_" + economable.getUniqueIdentifier(), (conn) -> { try { - ensureAccountExists(economable, conn); - conn.prepareStatement("LOCK TABLE " + dbConn.getTable(SANEECONOMY_BALANCES) + " WRITE").execute(); - PreparedStatement statement = dbConn.prepareStatement(conn, String.format("UPDATE `%s` SET balance = ?, last_name = ? WHERE `unique_identifier` = ?", dbConn.getTable(SANEECONOMY_BALANCES))); + this.ensureAccountExists(economable, conn); + conn.prepareStatement("LOCK TABLE " + this.dbConn.getTable(SANEECONOMY_BALANCES) + " WRITE").execute(); + PreparedStatement statement = this.dbConn.prepareStatement(conn, String.format("UPDATE `%s` SET balance = ?, last_name = ? WHERE `unique_identifier` = ?", this.dbConn.getTable(SANEECONOMY_BALANCES))); statement.setString(1, newBalance.toString()); statement.setString(2, economable.getName()); statement.setString(3, economable.getUniqueIdentifier()); statement.executeUpdate(); conn.prepareStatement("UNLOCK TABLES").execute(); } catch (Exception e) { - balances.put(economable.getUniqueIdentifier(), oldBalance); + this.balances.put(economable.getUniqueIdentifier(), oldBalance); throw new RuntimeException("SQL error has occurred.", e); } }); } private void ensureAccountExists(Economable economable, Connection conn) throws SQLException { - if (!accountExists(economable, conn)) { - PreparedStatement statement = dbConn.prepareStatement(conn, String.format("INSERT INTO `%s` (unique_identifier, last_name, balance) VALUES (?, ?, 0.0)", dbConn.getTable(SANEECONOMY_BALANCES))); + if (!this.accountExists(economable, conn)) { + PreparedStatement statement = this.dbConn.prepareStatement(conn, String.format("INSERT INTO `%s` (unique_identifier, last_name, balance) VALUES (?, ?, 0.0)", this.dbConn.getTable(SANEECONOMY_BALANCES))); statement.setString(1, economable.getUniqueIdentifier()); statement.setString(2, economable.getName()); statement.executeUpdate(); @@ -143,7 +143,7 @@ public class EconomyStorageBackendMySQL extends EconomyStorageBackendCaching { } private boolean accountExists(Economable economable, Connection conn) throws SQLException { - PreparedStatement statement = dbConn.prepareStatement(conn, String.format("SELECT 1 FROM `%s` WHERE `unique_identifier` = ?", dbConn.getTable(SANEECONOMY_BALANCES))); + PreparedStatement statement = this.dbConn.prepareStatement(conn, String.format("SELECT 1 FROM `%s` WHERE `unique_identifier` = ?", this.dbConn.getTable(SANEECONOMY_BALANCES))); statement.setString(1, economable.getUniqueIdentifier()); ResultSet rs = statement.executeQuery(); @@ -153,11 +153,11 @@ public class EconomyStorageBackendMySQL extends EconomyStorageBackendCaching { @Override public void waitUntilFlushed() { - dbConn.waitUntilFlushed(); + this.dbConn.waitUntilFlushed(); } public MySQLConnection getConnection() { - return dbConn; + return this.dbConn; } public void closeConnections() { @@ -167,9 +167,9 @@ public class EconomyStorageBackendMySQL extends EconomyStorageBackendCaching { @Override public void reloadEconomable(String uniqueIdentifier, EconomableReloadReason reason) { - dbConn.executeAsyncOperation("reload_economable_" + uniqueIdentifier, (conn) -> { + this.dbConn.executeAsyncOperation("reload_economable_" + uniqueIdentifier, (conn) -> { try { - PreparedStatement ps = conn.prepareStatement(String.format("SELECT balance FROM `%s` WHERE `unique_identifier` = ?", dbConn.getTable(SANEECONOMY_BALANCES))); + PreparedStatement ps = conn.prepareStatement(String.format("SELECT balance FROM `%s` WHERE `unique_identifier` = ?", this.dbConn.getTable(SANEECONOMY_BALANCES))); ps.setString(1, uniqueIdentifier); ResultSet rs = ps.executeQuery(); diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/economable/EconomableFaction.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/economable/EconomableFaction.java index b18461c..bde4c0e 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/economable/EconomableFaction.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/economable/EconomableFaction.java @@ -13,7 +13,7 @@ public class EconomableFaction implements Economable { @Override public String getUniqueIdentifier() { - return "faction:" + factionUuid; + return "faction:" + this.factionUuid; } @Override diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/economable/EconomableGeneric.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/economable/EconomableGeneric.java index bad8fa4..0116e92 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/economable/EconomableGeneric.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/economable/EconomableGeneric.java @@ -13,11 +13,11 @@ public class EconomableGeneric implements Economable { @Override public String getUniqueIdentifier() { - return uniqueIdentifier; + return this.uniqueIdentifier; } @Override public String getName() { - return uniqueIdentifier.substring(16); + return this.uniqueIdentifier.substring(16); } } diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/economable/EconomablePlayer.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/economable/EconomablePlayer.java index 9f75eca..1b425af 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/economable/EconomablePlayer.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/economable/EconomablePlayer.java @@ -15,12 +15,12 @@ public class EconomablePlayer implements Economable { @Override public String getName() { - return handle.getName(); + return this.handle.getName(); } @Override public String getUniqueIdentifier() { - return "player:" + handle.getUniqueId(); + return "player:" + this.handle.getUniqueId(); } @Override diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/logger/TransactionLoggerMySQL.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/logger/TransactionLoggerMySQL.java index 6c8dffe..bb9bd4c 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/logger/TransactionLoggerMySQL.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/logger/TransactionLoggerMySQL.java @@ -24,7 +24,7 @@ public class TransactionLoggerMySQL implements TransactionLogger { private void logGeneric(String from, String to, BigDecimal change, TransactionReason reason) { this.dbConn.executeAsyncOperation("log_transaction", (conn) -> { try { - PreparedStatement ps = conn.prepareStatement(String.format("INSERT INTO `%s` (`source`, `destination`, `amount`, `reason`) VALUES (?, ?, ?, ?)", dbConn.getTable("transaction_logs"))); + PreparedStatement ps = conn.prepareStatement(String.format("INSERT INTO `%s` (`source`, `destination`, `amount`, `reason`) VALUES (?, ?, ?, ?)", this.dbConn.getTable("transaction_logs"))); ps.setString(1, from); ps.setString(2, to); ps.setString(3, change.toString()); @@ -37,8 +37,8 @@ public class TransactionLoggerMySQL implements TransactionLogger { } public boolean testConnection() { - if (dbConn.testConnection()) { - createTables(); + if (this.dbConn.testConnection()) { + this.createTables(); return true; } @@ -46,8 +46,8 @@ public class TransactionLoggerMySQL implements TransactionLogger { } private void createTables() { - try (Connection conn = dbConn.openConnection()) { - PreparedStatement ps = conn.prepareStatement(String.format("CREATE TABLE IF NOT EXISTS `%s` (`source` VARCHAR(128), `destination` VARCHAR(128), `amount` DECIMAL(18, 2), `reason` VARCHAR(128), `logged` TIMESTAMP NOT NULL default CURRENT_TIMESTAMP)", dbConn.getTable("transaction_logs"))); + try (Connection conn = this.dbConn.openConnection()) { + PreparedStatement ps = conn.prepareStatement(String.format("CREATE TABLE IF NOT EXISTS `%s` (`source` VARCHAR(128), `destination` VARCHAR(128), `amount` DECIMAL(18, 2), `reason` VARCHAR(128), `logged` TIMESTAMP NOT NULL default CURRENT_TIMESTAMP)", this.dbConn.getTable("transaction_logs"))); ps.executeUpdate(); } catch (SQLException e) { throw new RuntimeException("Failed to create transaction logger tables", e); @@ -56,6 +56,6 @@ public class TransactionLoggerMySQL implements TransactionLogger { @Override public void logTransaction(Transaction transaction) { - logGeneric(transaction.getSender().getUniqueIdentifier(), transaction.getReceiver().getUniqueIdentifier(), transaction.getAmount(), transaction.getReason()); + this.logGeneric(transaction.getSender().getUniqueIdentifier(), transaction.getReceiver().getUniqueIdentifier(), transaction.getAmount(), transaction.getReason()); } } diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/transaction/Transaction.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/transaction/Transaction.java index 507cb3b..9db53cd 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/transaction/Transaction.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/transaction/Transaction.java @@ -30,34 +30,34 @@ public class Transaction { } public Economable getSender() { - return sender; + return this.sender; } public Economable getReceiver() { - return receiver; + return this.receiver; } public BigDecimal getAmount() { - return amount; + return this.amount; } public TransactionReason getReason() { - return reason; + return this.reason; } public boolean isSenderAffected() { - if (sender == Economable.CONSOLE) { + if (this.sender == Economable.CONSOLE) { return false; } - return (reason.getAffectedParties() == AffectedParties.SENDER) || (reason.getAffectedParties() == AffectedParties.BOTH); + return (this.reason.getAffectedParties() == AffectedParties.SENDER) || (this.reason.getAffectedParties() == AffectedParties.BOTH); } public boolean isReceiverAffected() { - if (receiver == Economable.CONSOLE) { + if (this.receiver == Economable.CONSOLE) { return false; } - return (reason.getAffectedParties() == AffectedParties.RECEIVER) || (reason.getAffectedParties() == AffectedParties.BOTH); + return (this.reason.getAffectedParties() == AffectedParties.RECEIVER) || (this.reason.getAffectedParties() == AffectedParties.BOTH); } } diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/transaction/TransactionReason.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/transaction/TransactionReason.java index c4c778d..0836174 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/transaction/TransactionReason.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/transaction/TransactionReason.java @@ -36,7 +36,7 @@ public enum TransactionReason { } public AffectedParties getAffectedParties() { - return affectedParties; + return this.affectedParties; } public enum AffectedParties { diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/transaction/TransactionResult.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/transaction/TransactionResult.java index 209bc4c..019a0d2 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/transaction/TransactionResult.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/economy/transaction/TransactionResult.java @@ -25,19 +25,19 @@ public class TransactionResult { } public Transaction getTransaction() { - return transaction; + return this.transaction; } public BigDecimal getFromBalance() { - return fromBalance; + return this.fromBalance; } public BigDecimal getToBalance() { - return toBalance; + return this.toBalance; } public Status getStatus() { - return status; + return this.status; } public enum Status { @@ -52,7 +52,7 @@ public class TransactionResult { } public String getMessage() { - return message; + return this.message; } } } diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/event/SaneEconomyTransactionEvent.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/event/SaneEconomyTransactionEvent.java index cdb57cf..fccc9d0 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/event/SaneEconomyTransactionEvent.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/event/SaneEconomyTransactionEvent.java @@ -12,7 +12,7 @@ import org.bukkit.event.HandlerList; * This event is called whenever a Transaction occurs in the plugin. If you cancel this event, the transaction will be cancelled as well. */ public class SaneEconomyTransactionEvent extends Event implements Cancellable { - private static HandlerList handlerList = new HandlerList(); + private static final HandlerList handlerList = new HandlerList(); private final Transaction transaction; private boolean isCancelled; @@ -36,7 +36,7 @@ public class SaneEconomyTransactionEvent extends Event implements Cancellable { } public Transaction getTransaction() { - return transaction; + return this.transaction; } public static HandlerList getHandlerList() { diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/listeners/JoinQuitListener.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/listeners/JoinQuitListener.java index 3da9f66..e417c06 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/listeners/JoinQuitListener.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/listeners/JoinQuitListener.java @@ -31,28 +31,28 @@ public class JoinQuitListener implements Listener { public void onPlayerJoin(PlayerJoinEvent evt) { Player player = evt.getPlayer(); Economable economable = Economable.wrap((OfflinePlayer) player); - BigDecimal startBalance = new BigDecimal(plugin.getConfig().getDouble("economy.start-balance", 0.0D)); + BigDecimal startBalance = new BigDecimal(this.plugin.getConfig().getDouble("economy.start-balance", 0.0D)); /* A starting balance is configured AND they haven't been given it yet. */ - if ((startBalance.compareTo(BigDecimal.ZERO) > 0) && !plugin.getEconomyManager().accountExists(economable)) { - plugin.getEconomyManager().transact(new Transaction( - plugin.getEconomyManager().getCurrency(), Economable.CONSOLE, economable, startBalance, TransactionReason.STARTING_BALANCE + if ((startBalance.compareTo(BigDecimal.ZERO) > 0) && !this.plugin.getEconomyManager().accountExists(economable)) { + this.plugin.getEconomyManager().transact(new Transaction( + this.plugin.getEconomyManager().getCurrency(), Economable.CONSOLE, economable, startBalance, TransactionReason.STARTING_BALANCE )); - if (plugin.getConfig().getBoolean("economy.notify-start-balance", true)) { - this.plugin.getMessenger().sendMessage(player, "You've been issued a starting balance of {1}!", plugin.getEconomyManager().getCurrency().formatAmount(startBalance)); + if (this.plugin.getConfig().getBoolean("economy.notify-start-balance", true)) { + this.plugin.getMessenger().sendMessage(player, "You've been issued a starting balance of {1}!", this.plugin.getEconomyManager().getCurrency().formatAmount(startBalance)); } } /* Update notification */ - if ((plugin.getVersionChecker() != null) && player.hasPermission("saneeconomy.update-notify") && plugin.getVersionChecker().isUpdateAvailable()) { - this.plugin.getMessenger().sendMessage(player, "An update is available! The currently-installed version is {1}, but the newest available is {2}. Please go to {3} to update!", plugin.getDescription().getVersion(), plugin.getVersionChecker().getNewestVersion(), GithubVersionChecker.DOWNLOAD_URL); + if ((this.plugin.getVersionChecker() != null) && player.hasPermission("saneeconomy.update-notify") && this.plugin.getVersionChecker().isUpdateAvailable()) { + this.plugin.getMessenger().sendMessage(player, "An update is available! The currently-installed version is {1}, but the newest available is {2}. Please go to {3} to update!", this.plugin.getDescription().getVersion(), this.plugin.getVersionChecker().getNewestVersion(), GithubVersionChecker.DOWNLOAD_URL); } } @EventHandler public void onPlayerLogin(AsyncPlayerPreLoginEvent evt) { - Bukkit.getServer().getScheduler().runTaskAsynchronously(plugin, () -> { - plugin.getEconomyManager().getBackend().reloadEconomable(String.format("player:%s", evt.getUniqueId()), EconomyStorageBackend.EconomableReloadReason.PLAYER_JOIN); // TODO: If servers start to lag when lots of people join, this is why. + Bukkit.getServer().getScheduler().runTaskAsynchronously(this.plugin, () -> { + this.plugin.getEconomyManager().getBackend().reloadEconomable(String.format("player:%s", evt.getUniqueId()), EconomyStorageBackend.EconomableReloadReason.PLAYER_JOIN); // TODO: If servers start to lag when lots of people join, this is why. }); } } diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/updates/GithubVersionChecker.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/updates/GithubVersionChecker.java index 82e4545..45411a8 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/updates/GithubVersionChecker.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/updates/GithubVersionChecker.java @@ -44,7 +44,7 @@ public class GithubVersionChecker { String releaseName = releaseObj.get("name").getAsString().split(" ")[0]; - if (!releaseName.equalsIgnoreCase(pluginName)) { // Not for this plugin. + if (!releaseName.equalsIgnoreCase(this.pluginName)) { // Not for this plugin. continue; } @@ -57,12 +57,12 @@ public class GithubVersionChecker { } } - updateChecked = true; - updateAvailable = VersionComparer.isSemVerGreaterThan(currentVersion, newestFound); + this.updateChecked = true; + this.updateAvailable = VersionComparer.isSemVerGreaterThan(currentVersion, newestFound); } public boolean isUpdateAvailable() { - return updateChecked && updateAvailable; + return this.updateChecked && this.updateAvailable; } public String getNewestVersion() { diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/updates/VersionComparer.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/updates/VersionComparer.java index a8ae125..2d8ccf1 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/updates/VersionComparer.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/updates/VersionComparer.java @@ -4,7 +4,10 @@ package org.appledash.saneeconomy.updates; * Created by appledash on 7/15/17. * Blackjack is best pony. */ -public class VersionComparer { +public final class VersionComparer { + private VersionComparer() { + } + public static boolean isSemVerGreaterThan(String first, String second) { if (first == null) { return true; @@ -23,7 +26,7 @@ public class VersionComparer { private static int[] intifyParts(String version) { String[] firstParts = version.split("\\."); - return new int[] { Integer.valueOf(firstParts[0]), Integer.valueOf(firstParts[1]), Integer.valueOf(firstParts[2]) }; + return new int[] { Integer.parseInt(firstParts[0]), Integer.parseInt(firstParts[1]), Integer.parseInt(firstParts[2]) }; } private static int computeInt(int[] parts) { diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/utils/MapUtil.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/utils/MapUtil.java index bbb8a66..68f3b3c 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/utils/MapUtil.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/utils/MapUtil.java @@ -6,7 +6,10 @@ import java.util.*; * Created by appledash on 7/11/16. * Blackjack is still best pony. */ -public class MapUtil { +public final class MapUtil { + private MapUtil() { + } + /* Originally found on StackOverflow: http://stackoverflow.com/a/2581754/1849152 */ public static > LinkedHashMap sortByValue(Map map) { List> list = @@ -27,6 +30,7 @@ public class MapUtil { * @param nSkip Number of items to skip * @return New LinkedHashMap, may be empty. */ + @SuppressWarnings("CollectionDeclaredAsConcreteClass") public static LinkedHashMap skip(LinkedHashMap map, int nSkip) { LinkedHashMap newMap = new LinkedHashMap<>(); diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/utils/NumberUtils.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/utils/NumberUtils.java index 7f4615f..b9a5ac1 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/utils/NumberUtils.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/utils/NumberUtils.java @@ -12,9 +12,12 @@ import java.text.ParseException; * Created by AppleDash on 6/14/2016. * Blackjack is still best pony. */ -public class NumberUtils { +public final class NumberUtils { private static final BigDecimal INVALID_DOUBLE = BigDecimal.ONE.negate(); + private NumberUtils() { + } + public static BigDecimal parsePositiveDouble(String sDouble) { if (Strings.isNullOrEmpty(sDouble)) { return INVALID_DOUBLE; diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/utils/PlayerUtils.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/utils/PlayerUtils.java index 18c3090..bbf9f5b 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/utils/PlayerUtils.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/utils/PlayerUtils.java @@ -9,7 +9,10 @@ import java.util.UUID; * Created by appledash on 7/19/16. * Blackjack is still best pony. */ -public class PlayerUtils { +public final class PlayerUtils { + private PlayerUtils() { + } + /** * Get an online or offline player from Bukkit. * This is guaranteed to be a player who has played before, but is not guaranteed to be currently online. diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/utils/SaneEconomyConfiguration.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/utils/SaneEconomyConfiguration.java index 66878d6..06c89f9 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/utils/SaneEconomyConfiguration.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/utils/SaneEconomyConfiguration.java @@ -33,38 +33,38 @@ public class SaneEconomyConfiguration { } public EconomyManager loadEconomyBackend() { - logger.info("Initializing currency..."); - Currency currency = Currency.fromConfig(rootConfig.getConfigurationSection("currency")); - logger.info("Initialized currency: " + currency.getPluralName()); + this.logger.info("Initializing currency..."); + Currency currency = Currency.fromConfig(this.rootConfig.getConfigurationSection("currency")); + this.logger.info("Initialized currency: " + currency.getPluralName()); - logger.info("Initializing economy storage backend..."); + this.logger.info("Initializing economy storage backend..."); - EconomyStorageBackend backend = loadBackend(rootConfig.getConfigurationSection("backend")); + EconomyStorageBackend backend = this.loadBackend(this.rootConfig.getConfigurationSection("backend")); if (backend == null) { - logger.severe("Failed to load backend!"); + this.logger.severe("Failed to load backend!"); return null; } - logger.info("Performing initial data load..."); + this.logger.info("Performing initial data load..."); backend.reloadDatabase(); - logger.info("Data loaded!"); + this.logger.info("Data loaded!"); - if (!Strings.isNullOrEmpty(rootConfig.getString("old-backend.type", null))) { - logger.info("Old backend detected, converting... (This may take a minute or two.)"); - EconomyStorageBackend oldBackend = loadBackend(rootConfig.getConfigurationSection("old-backend")); + if (!Strings.isNullOrEmpty(this.rootConfig.getString("old-backend.type", null))) { + this.logger.info("Old backend detected, converting... (This may take a minute or two.)"); + EconomyStorageBackend oldBackend = this.loadBackend(this.rootConfig.getConfigurationSection("old-backend")); if (oldBackend == null) { - logger.severe("Failed to load old backend!"); + this.logger.severe("Failed to load old backend!"); return null; } oldBackend.reloadDatabase(); - convertBackends(oldBackend, backend); - logger.info("Data converted, removing old config section."); - rootConfig.set("old-backend", null); + this.convertBackends(oldBackend, backend); + this.logger.info("Data converted, removing old config section."); + this.rootConfig.set("old-backend", null); } - return new EconomyManager(saneEconomy, currency, backend, rootConfig.getString("economy.server-account", null)); + return new EconomyManager(this.saneEconomy, currency, backend, this.rootConfig.getString("economy.server-account", null)); } /** @@ -78,24 +78,24 @@ public class SaneEconomyConfiguration { if (backendType.equalsIgnoreCase("json")) { String backendFileName = config.getString("file", "economy.json"); - File backendFile = new File(saneEconomy.getDataFolder(), backendFileName); + File backendFile = new File(this.saneEconomy.getDataFolder(), backendFileName); backend = new EconomyStorageBackendJSON(backendFile); - logger.info("Initialized JSON backend with file " + backendFile.getAbsolutePath()); + this.logger.info("Initialized JSON backend with file " + backendFile.getAbsolutePath()); } else if (backendType.equalsIgnoreCase("mysql")) { - EconomyStorageBackendMySQL mySQLBackend = new EconomyStorageBackendMySQL(loadCredentials(config)); + EconomyStorageBackendMySQL mySQLBackend = new EconomyStorageBackendMySQL(this.loadCredentials(config)); backend = mySQLBackend; - logger.info("Initialized MySQL backend."); - logger.info("Testing connection..."); + this.logger.info("Initialized MySQL backend."); + this.logger.info("Testing connection..."); if (!mySQLBackend.getConnection().testConnection()) { - logger.severe("MySQL connection failed - cannot continue!"); + this.logger.severe("MySQL connection failed - cannot continue!"); return null; } - logger.info("Connection successful!"); + this.logger.info("Connection successful!"); } else { - logger.severe("Unknown storage backend " + backendType + "!"); + this.logger.severe("Unknown storage backend " + backendType + "!"); return null; } @@ -116,27 +116,27 @@ public class SaneEconomyConfiguration { } public TransactionLogger loadLogger() { - if (!rootConfig.getBoolean("log-transactions", false)) { + if (!this.rootConfig.getBoolean("log-transactions", false)) { return null; } - logger.info("Attempting to load transaction logger..."); + this.logger.info("Attempting to load transaction logger..."); - if (rootConfig.getConfigurationSection("logger-database") == null) { - logger.severe("No transaction logger database defined, cannot possibly connect!"); + if (this.rootConfig.getConfigurationSection("logger-database") == null) { + this.logger.severe("No transaction logger database defined, cannot possibly connect!"); return null; } - DatabaseCredentials credentials = loadCredentials(rootConfig.getConfigurationSection("logger-database")); + DatabaseCredentials credentials = this.loadCredentials(this.rootConfig.getConfigurationSection("logger-database")); TransactionLoggerMySQL transactionLogger = new TransactionLoggerMySQL(credentials); if (transactionLogger.testConnection()) { - logger.info("Initialized MySQL transaction logger."); + this.logger.info("Initialized MySQL transaction logger."); return transactionLogger; } - logger.severe("Failed to connect to MySQL database for transaction logger!"); + this.logger.severe("Failed to connect to MySQL database for transaction logger!"); return null; } diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/utils/WebUtils.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/utils/WebUtils.java index 2149d5e..4369086 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/utils/WebUtils.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/utils/WebUtils.java @@ -11,19 +11,25 @@ import java.net.URL; * Created by appledash on 7/11/16. * Blackjack is still best pony. */ -public class WebUtils { +public final class WebUtils { + private WebUtils() { + } + public static String getContents(String url) { try { - String out = ""; + StringBuilder out = new StringBuilder(); URL uri = new URL(url); BufferedReader br = new BufferedReader(new InputStreamReader(uri.openConnection().getInputStream())); String line; + //noinspection NestedAssignment while ((line = br.readLine()) != null) { - out += line + "\n"; + out.append(line).append("\n"); } - return out; + br.close(); + + return out.toString(); } catch (IOException e) { SaneEconomy.logger().warning("Failed to get contents of URL " + url); throw new RuntimeException("Failed to get URL contents!", e); diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/utils/database/MySQLConnection.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/utils/database/MySQLConnection.java index fb7bc36..edcfb63 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/utils/database/MySQLConnection.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/utils/database/MySQLConnection.java @@ -34,13 +34,13 @@ public class MySQLConnection { public PreparedStatement prepareStatement(Connection conn, String sql) throws SQLException { PreparedStatement preparedStatement = conn.prepareStatement(sql); - preparedStatement.setQueryTimeout(dbCredentials.getQueryTimeout()); // 5 second timeout + preparedStatement.setQueryTimeout(this.dbCredentials.getQueryTimeout()); // 5 second timeout return preparedStatement; } public boolean testConnection() { - try (Connection ignored = openConnection()) { + try (Connection ignored = this.openConnection()) { return true; } catch (Exception e) { e.printStackTrace(); @@ -49,31 +49,31 @@ public class MySQLConnection { } public void executeAsyncOperation(String tag, Consumer callback) { - this.saneDatabase.runDatabaseOperationAsync(tag, () -> doExecuteAsyncOperation(1, callback)); + this.saneDatabase.runDatabaseOperationAsync(tag, () -> this.doExecuteAsyncOperation(1, callback)); } // This is a bit weird because it has to account for recursion... private void doExecuteAsyncOperation(int levels, Consumer callback) { - try (Connection conn = openConnection()) { + try (Connection conn = this.openConnection()) { callback.accept(conn); } catch (Exception e) { - if (levels > dbCredentials.getMaxRetries()) { + if (levels > this.dbCredentials.getMaxRetries()) { throw new RuntimeException("This shouldn't happen (database error)", e); } LOGGER.severe("An internal SQL error has occured, trying up to " + (5 - levels) + " more times..."); e.printStackTrace(); levels++; - doExecuteAsyncOperation(levels, callback); + this.doExecuteAsyncOperation(levels, callback); } } public DatabaseCredentials getCredentials() { - return dbCredentials; + return this.dbCredentials; } public String getTable(String tableName) { - return dbCredentials.getTablePrefix() + tableName; + return this.dbCredentials.getTablePrefix() + tableName; } public void waitUntilFlushed() { diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/vault/EconomySaneEconomy.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/vault/EconomySaneEconomy.java index 016351d..c309420 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/vault/EconomySaneEconomy.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/vault/EconomySaneEconomy.java @@ -56,7 +56,7 @@ public class EconomySaneEconomy implements Economy { @Override public boolean hasAccount(String target) { - return SaneEconomy.getInstance().getEconomyManager().accountExists(makeEconomable(target)); + return SaneEconomy.getInstance().getEconomyManager().accountExists(this.makeEconomable(target)); } @Override @@ -66,17 +66,17 @@ public class EconomySaneEconomy implements Economy { @Override public boolean hasAccount(String target, String worldName) { - return hasAccount(target); + return this.hasAccount(target); } @Override public boolean hasAccount(OfflinePlayer offlinePlayer, String worldName) { - return hasAccount(offlinePlayer); + return this.hasAccount(offlinePlayer); } @Override public double getBalance(String target) { - return SaneEconomy.getInstance().getEconomyManager().getBalance(makeEconomable(target)).doubleValue(); + return SaneEconomy.getInstance().getEconomyManager().getBalance(this.makeEconomable(target)).doubleValue(); } @Override @@ -86,17 +86,17 @@ public class EconomySaneEconomy implements Economy { @Override public double getBalance(String target, String worldName) { - return getBalance(target); + return this.getBalance(target); } @Override public double getBalance(OfflinePlayer offlinePlayer, String worldName) { - return getBalance(offlinePlayer); + return this.getBalance(offlinePlayer); } @Override public boolean has(String target, double amount) { - return SaneEconomy.getInstance().getEconomyManager().hasBalance(makeEconomable(target), new BigDecimal(amount)); + return SaneEconomy.getInstance().getEconomyManager().hasBalance(this.makeEconomable(target), new BigDecimal(amount)); } @Override @@ -106,80 +106,80 @@ public class EconomySaneEconomy implements Economy { @Override public boolean has(String target, String worldName, double amount) { - return has(target, amount); + return this.has(target, amount); } @Override public boolean has(OfflinePlayer offlinePlayer, String worldName, double amount) { - return has(offlinePlayer, amount); + return this.has(offlinePlayer, amount); } @Override public EconomyResponse withdrawPlayer(String target, double amount) { if (amount == 0) { - return new EconomyResponse(amount, getBalance(target), EconomyResponse.ResponseType.SUCCESS, ""); + return new EconomyResponse(amount, this.getBalance(target), EconomyResponse.ResponseType.SUCCESS, ""); } - return transact(new Transaction( - SaneEconomy.getInstance().getEconomyManager().getCurrency(), makeEconomable(target), Economable.PLUGIN, new BigDecimal(amount), TransactionReason.PLUGIN_TAKE + return this.transact(new Transaction( + SaneEconomy.getInstance().getEconomyManager().getCurrency(), this.makeEconomable(target), Economable.PLUGIN, new BigDecimal(amount), TransactionReason.PLUGIN_TAKE )); } @Override public EconomyResponse withdrawPlayer(OfflinePlayer offlinePlayer, double amount) { if (amount == 0) { - return new EconomyResponse(amount, getBalance(offlinePlayer), EconomyResponse.ResponseType.SUCCESS, ""); + return new EconomyResponse(amount, this.getBalance(offlinePlayer), EconomyResponse.ResponseType.SUCCESS, ""); } - if (!has(offlinePlayer, amount)) { - return new EconomyResponse(amount, getBalance(offlinePlayer), EconomyResponse.ResponseType.FAILURE, "Insufficient funds."); + if (!this.has(offlinePlayer, amount)) { + return new EconomyResponse(amount, this.getBalance(offlinePlayer), EconomyResponse.ResponseType.FAILURE, "Insufficient funds."); } - return transact(new Transaction( + return this.transact(new Transaction( SaneEconomy.getInstance().getEconomyManager().getCurrency(), Economable.wrap(offlinePlayer), Economable.PLUGIN, new BigDecimal(amount), TransactionReason.PLUGIN_TAKE )); } @Override public EconomyResponse withdrawPlayer(String playerName, String worldName, double v) { - return withdrawPlayer(playerName, v); + return this.withdrawPlayer(playerName, v); } @Override public EconomyResponse withdrawPlayer(OfflinePlayer offlinePlayer, String s, double v) { - return withdrawPlayer(offlinePlayer, v); + return this.withdrawPlayer(offlinePlayer, v); } @Override public EconomyResponse depositPlayer(String target, double amount) { if (amount == 0) { - return new EconomyResponse(amount, getBalance(target), EconomyResponse.ResponseType.SUCCESS, ""); + return new EconomyResponse(amount, this.getBalance(target), EconomyResponse.ResponseType.SUCCESS, ""); } - return transact(new Transaction( - SaneEconomy.getInstance().getEconomyManager().getCurrency(), Economable.PLUGIN, makeEconomable(target), new BigDecimal(amount), TransactionReason.PLUGIN_GIVE + return this.transact(new Transaction( + SaneEconomy.getInstance().getEconomyManager().getCurrency(), Economable.PLUGIN, this.makeEconomable(target), new BigDecimal(amount), TransactionReason.PLUGIN_GIVE )); } @Override public EconomyResponse depositPlayer(OfflinePlayer offlinePlayer, double v) { if (v == 0) { - return new EconomyResponse(v, getBalance(offlinePlayer), EconomyResponse.ResponseType.SUCCESS, ""); + return new EconomyResponse(v, this.getBalance(offlinePlayer), EconomyResponse.ResponseType.SUCCESS, ""); } - return transact(new Transaction( + return this.transact(new Transaction( SaneEconomy.getInstance().getEconomyManager().getCurrency(), Economable.PLUGIN, Economable.wrap(offlinePlayer), new BigDecimal(v), TransactionReason.PLUGIN_GIVE )); } @Override public EconomyResponse depositPlayer(String playerName, String worldName, double v) { - return depositPlayer(playerName, v); + return this.depositPlayer(playerName, v); } @Override public EconomyResponse depositPlayer(OfflinePlayer offlinePlayer, String worldName, double v) { - return depositPlayer(offlinePlayer, v); + return this.depositPlayer(offlinePlayer, v); } @Override @@ -271,7 +271,7 @@ public class EconomySaneEconomy implements Economy { return Economable.CONSOLE; } - if (validatePlayer(input)) { + if (this.validatePlayer(input)) { return Economable.wrap(PlayerUtils.getOfflinePlayer(input)); } diff --git a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/vault/VaultHook.java b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/vault/VaultHook.java index 9cc454e..ab413d8 100644 --- a/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/vault/VaultHook.java +++ b/SaneEconomyCore/src/main/java/org/appledash/saneeconomy/vault/VaultHook.java @@ -22,11 +22,11 @@ public class VaultHook { } public void hook() { - Bukkit.getServicesManager().register(Economy.class, provider, plugin, ServicePriority.Normal); + Bukkit.getServicesManager().register(Economy.class, this.provider, this.plugin, ServicePriority.Normal); } public void unhook() { - Bukkit.getServicesManager().unregister(Economy.class, provider); + Bukkit.getServicesManager().unregister(Economy.class, this.provider); } public boolean hasPermission(OfflinePlayer offlinePlayer, String permNode) { diff --git a/SaneEconomyCore/src/test/java/org/appledash/saneeconomy/test/EconomyManagerTest.java b/SaneEconomyCore/src/test/java/org/appledash/saneeconomy/test/EconomyManagerTest.java index 52d6346..de2897b 100644 --- a/SaneEconomyCore/src/test/java/org/appledash/saneeconomy/test/EconomyManagerTest.java +++ b/SaneEconomyCore/src/test/java/org/appledash/saneeconomy/test/EconomyManagerTest.java @@ -28,7 +28,7 @@ public class EconomyManagerTest { @Before public void setupEconomyManager() { - economyManager = new EconomyManager(new MockSaneEconomy(), + this.economyManager = new EconomyManager(new MockSaneEconomy(), new Currency("test dollar", "test dollars", new DecimalFormat("0.00")), new MockEconomyStorageBackend(), null); } @@ -39,51 +39,51 @@ public class EconomyManagerTest { Economable playerTwo = Economable.wrap(new MockOfflinePlayer("Two")); // Accounts should not exist - Assert.assertFalse(economyManager.accountExists(playerOne)); - Assert.assertFalse(economyManager.accountExists(playerTwo)); - Assert.assertEquals(BigDecimal.ZERO, economyManager.getBalance(playerOne)); - Assert.assertEquals(BigDecimal.ZERO, economyManager.getBalance(playerTwo)); + Assert.assertFalse(this.economyManager.accountExists(playerOne)); + Assert.assertFalse(this.economyManager.accountExists(playerTwo)); + Assert.assertEquals(BigDecimal.ZERO, this.economyManager.getBalance(playerOne)); + Assert.assertEquals(BigDecimal.ZERO, this.economyManager.getBalance(playerTwo)); - economyManager.setBalance(playerOne, new BigDecimal(100.0)); + this.economyManager.setBalance(playerOne, new BigDecimal(100.0)); // Now one should have an account, but two should not - Assert.assertTrue(economyManager.accountExists(playerOne)); - Assert.assertFalse(economyManager.accountExists(playerTwo)); + Assert.assertTrue(this.economyManager.accountExists(playerOne)); + Assert.assertFalse(this.economyManager.accountExists(playerTwo)); // One should have balance, two should not - Assert.assertEquals(new BigDecimal("100.00"), economyManager.getBalance(playerOne)); - Assert.assertEquals(BigDecimal.ZERO, economyManager.getBalance(playerTwo)); + Assert.assertEquals(new BigDecimal("100.00"), this.economyManager.getBalance(playerOne)); + Assert.assertEquals(BigDecimal.ZERO, this.economyManager.getBalance(playerTwo)); // One should be able to transfer to two - Assert.assertSame(economyManager.transact(new Transaction(economyManager.getCurrency(), playerOne, playerTwo, new BigDecimal(50.0), TransactionReason.PLAYER_PAY)).getStatus(), TransactionResult.Status.SUCCESS); + Assert.assertSame(this.economyManager.transact(new Transaction(this.economyManager.getCurrency(), playerOne, playerTwo, new BigDecimal(50.0), TransactionReason.PLAYER_PAY)).getStatus(), TransactionResult.Status.SUCCESS); // One should now have only 50 left, two should have 50 now - Assert.assertEquals("Player one should have 50 dollars", new BigDecimal("50.00"), economyManager.getBalance(playerOne)); - Assert.assertEquals("Player two should have 50 dollars", new BigDecimal("50.00"), economyManager.getBalance(playerTwo)); + Assert.assertEquals("Player one should have 50 dollars", new BigDecimal("50.00"), this.economyManager.getBalance(playerOne)); + Assert.assertEquals("Player two should have 50 dollars", new BigDecimal("50.00"), this.economyManager.getBalance(playerTwo)); // Ensure that balance addition and subtraction works... - Assert.assertEquals(new BigDecimal("25.00"), economyManager.transact( - new Transaction(economyManager.getCurrency(), playerOne, Economable.CONSOLE, new BigDecimal("25.00"), TransactionReason.TEST_TAKE) + Assert.assertEquals(new BigDecimal("25.00"), this.economyManager.transact( + new Transaction(this.economyManager.getCurrency(), playerOne, Economable.CONSOLE, new BigDecimal("25.00"), TransactionReason.TEST_TAKE) ).getFromBalance()); - Assert.assertEquals(new BigDecimal("50.00"), economyManager.transact( - new Transaction(economyManager.getCurrency(), Economable.CONSOLE, playerOne, new BigDecimal("25.00"), TransactionReason.TEST_GIVE) + Assert.assertEquals(new BigDecimal("50.00"), this.economyManager.transact( + new Transaction(this.economyManager.getCurrency(), Economable.CONSOLE, playerOne, new BigDecimal("25.00"), TransactionReason.TEST_GIVE) ).getToBalance()); - Assert.assertEquals(TransactionResult.Status.ERR_NOT_ENOUGH_FUNDS, economyManager.transact( - new Transaction(economyManager.getCurrency(), playerTwo, Economable.CONSOLE, new BigDecimal(Double.MAX_VALUE), TransactionReason.TEST_TAKE) + Assert.assertEquals(TransactionResult.Status.ERR_NOT_ENOUGH_FUNDS, this.economyManager.transact( + new Transaction(this.economyManager.getCurrency(), playerTwo, Economable.CONSOLE, new BigDecimal(Double.MAX_VALUE), TransactionReason.TEST_TAKE) ).getStatus()); // Ensure that hasBalance works - Assert.assertTrue(economyManager.hasBalance(playerOne, new BigDecimal("50.00"))); - Assert.assertFalse(economyManager.hasBalance(playerOne, new BigDecimal("51.00"))); + Assert.assertTrue(this.economyManager.hasBalance(playerOne, new BigDecimal("50.00"))); + Assert.assertFalse(this.economyManager.hasBalance(playerOne, new BigDecimal("51.00"))); } @Test public void testTopBalances() { Random random = new Random(); List economables = new ArrayList<>(10); - Set names = new HashSet(); + Set names = new HashSet<>(); for (int i = 0; i < 10; i++) { Economable economable = Economable.wrap(new MockOfflinePlayer("Dude" + i)); @@ -97,7 +97,7 @@ public class EconomyManagerTest { List javaSortedBalances = economables.stream().map(this.economyManager::getBalance).sorted((left, right) -> -left.compareTo(right)).collect(Collectors.toList()); List ecoManTopBalances = ImmutableList.copyOf(this.economyManager.getTopBalances(10, 0).values()); - Assert.assertTrue("List is not correctly sorted!", areListsEqual(javaSortedBalances, ecoManTopBalances)); + Assert.assertTrue("List is not correctly sorted!", this.areListsEqual(javaSortedBalances, ecoManTopBalances)); Assert.assertEquals("Wrong number of top balances!", 5, this.economyManager.getTopBalances(5, 0).size()); this.economyManager.getTopBalances(10, 0).keySet().forEach(name -> Assert.assertTrue("Returned name in top balances not valid!", names.contains(name))); diff --git a/SaneEconomyCore/src/test/java/org/appledash/saneeconomy/test/NumberUtilsTest.java b/SaneEconomyCore/src/test/java/org/appledash/saneeconomy/test/NumberUtilsTest.java index 911a5a6..332e936 100644 --- a/SaneEconomyCore/src/test/java/org/appledash/saneeconomy/test/NumberUtilsTest.java +++ b/SaneEconomyCore/src/test/java/org/appledash/saneeconomy/test/NumberUtilsTest.java @@ -39,7 +39,7 @@ public class NumberUtilsTest { Locale old = Locale.getDefault(); Locale.setDefault(Locale.FRANCE); try { - testFilter(); + this.testFilter(); } catch (Throwable e) { Locale.setDefault(old); throw e; diff --git a/SaneEconomyCore/src/test/java/org/appledash/saneeconomy/test/mock/MockEconomyStorageBackend.java b/SaneEconomyCore/src/test/java/org/appledash/saneeconomy/test/mock/MockEconomyStorageBackend.java index a839b89..223825d 100644 --- a/SaneEconomyCore/src/test/java/org/appledash/saneeconomy/test/mock/MockEconomyStorageBackend.java +++ b/SaneEconomyCore/src/test/java/org/appledash/saneeconomy/test/mock/MockEconomyStorageBackend.java @@ -12,7 +12,7 @@ import java.math.BigDecimal; public class MockEconomyStorageBackend extends EconomyStorageBackendCaching { @Override public void setBalance(Economable player, BigDecimal newBalance) { - balances.put(player.getUniqueIdentifier(), newBalance); + this.balances.put(player.getUniqueIdentifier(), newBalance); this.uuidToName.put(player.getUniqueIdentifier(), player.getName()); } diff --git a/SaneEconomyCore/src/test/java/org/appledash/saneeconomy/test/mock/MockOfflinePlayer.java b/SaneEconomyCore/src/test/java/org/appledash/saneeconomy/test/mock/MockOfflinePlayer.java index b11a267..73ad905 100644 --- a/SaneEconomyCore/src/test/java/org/appledash/saneeconomy/test/mock/MockOfflinePlayer.java +++ b/SaneEconomyCore/src/test/java/org/appledash/saneeconomy/test/mock/MockOfflinePlayer.java @@ -34,12 +34,12 @@ public class MockOfflinePlayer implements OfflinePlayer { @Override public String getName() { - return name; + return this.name; } @Override public UUID getUniqueId() { - return uuid; + return this.uuid; } @Override diff --git a/SaneEconomyCore/src/test/java/org/appledash/saneeconomy/test/mock/MockServer.java b/SaneEconomyCore/src/test/java/org/appledash/saneeconomy/test/mock/MockServer.java index d455f2d..3e04fb5 100644 --- a/SaneEconomyCore/src/test/java/org/appledash/saneeconomy/test/mock/MockServer.java +++ b/SaneEconomyCore/src/test/java/org/appledash/saneeconomy/test/mock/MockServer.java @@ -47,8 +47,8 @@ public class MockServer implements Server { } - private Logger logger = Logger.getLogger("MockServer"); - private Map offlinePlayers = new HashMap<>(); + private final Logger logger = Logger.getLogger("MockServer"); + private final Map offlinePlayers = new HashMap<>(); public void addOfflinePlayer(OfflinePlayer offlinePlayer) { this.offlinePlayers.put(offlinePlayer.getUniqueId(), offlinePlayer); @@ -501,12 +501,12 @@ public class MockServer implements Server { } @Override - public CachedServerIcon loadServerIcon(File file) throws IllegalArgumentException, Exception { + public CachedServerIcon loadServerIcon(File file) throws Exception { return null; } @Override - public CachedServerIcon loadServerIcon(BufferedImage bufferedImage) throws IllegalArgumentException, Exception { + public CachedServerIcon loadServerIcon(BufferedImage bufferedImage) throws Exception { return null; } diff --git a/SaneEconomyMobKills/src/main/java/org/appledash/saneeconomymobkills/SaneEconomyMobKills.java b/SaneEconomyMobKills/src/main/java/org/appledash/saneeconomymobkills/SaneEconomyMobKills.java index a7cbc59..6d727e6 100644 --- a/SaneEconomyMobKills/src/main/java/org/appledash/saneeconomymobkills/SaneEconomyMobKills.java +++ b/SaneEconomyMobKills/src/main/java/org/appledash/saneeconomymobkills/SaneEconomyMobKills.java @@ -21,35 +21,35 @@ public class SaneEconomyMobKills extends SanePlugin { @Override public void onEnable() { - saneEconomy = (SaneEconomy)getServer().getPluginManager().getPlugin("SaneEconomy"); + this.saneEconomy = (SaneEconomy) this.getServer().getPluginManager().getPlugin("SaneEconomy"); super.onEnable(); YamlConfiguration amountsConfig; - if (!(new File(getDataFolder(), "amounts.yml").exists())) { - amountsConfig = YamlConfiguration.loadConfiguration(new InputStreamReader(getClass().getResourceAsStream("/amounts.yml"))); + if (!(new File(this.getDataFolder(), "amounts.yml").exists())) { + amountsConfig = YamlConfiguration.loadConfiguration(new InputStreamReader(this.getClass().getResourceAsStream("/amounts.yml"))); try { - amountsConfig.save(new File(getDataFolder(), "amounts.yml")); + amountsConfig.save(new File(this.getDataFolder(), "amounts.yml")); } catch (IOException e) { throw new RuntimeException("Failed to save amounts.yml to plugin data folder!"); } } else { - amountsConfig = YamlConfiguration.loadConfiguration(new File(getDataFolder(), "amounts.yml")); + amountsConfig = YamlConfiguration.loadConfiguration(new File(this.getDataFolder(), "amounts.yml")); } for (String entityTypeName : amountsConfig.getKeys(false)) { double value = amountsConfig.getDouble(entityTypeName); - killAmounts.put(entityTypeName, value); + this.killAmounts.put(entityTypeName, value); } - getServer().getPluginManager().registerEvents(new EntityDamageListener(this), this); + this.getServer().getPluginManager().registerEvents(new EntityDamageListener(this), this); } public SaneEconomy getSaneEconomy() { - return saneEconomy; + return this.saneEconomy; } public Map getKillAmounts() { - return killAmounts; + return this.killAmounts; } } diff --git a/SaneEconomyMobKills/src/main/java/org/appledash/saneeconomymobkills/listeners/EntityDamageListener.java b/SaneEconomyMobKills/src/main/java/org/appledash/saneeconomymobkills/listeners/EntityDamageListener.java index 7a94a4c..5737cfc 100644 --- a/SaneEconomyMobKills/src/main/java/org/appledash/saneeconomymobkills/listeners/EntityDamageListener.java +++ b/SaneEconomyMobKills/src/main/java/org/appledash/saneeconomymobkills/listeners/EntityDamageListener.java @@ -21,8 +21,8 @@ import java.util.UUID; * Blackjack is still best pony. */ public class EntityDamageListener implements Listener { - private SaneEconomyMobKills plugin; - private Map> damageDealt = new HashMap<>(); + private final SaneEconomyMobKills plugin; + private final Map> damageDealt = new HashMap<>(); public EntityDamageListener(SaneEconomyMobKills plugin) { this.plugin = plugin; @@ -41,16 +41,16 @@ public class EntityDamageListener implements Listener { return; } - if (!plugin.getKillAmounts().containsKey(getEntityType(damagee))) { + if (!this.plugin.getKillAmounts().containsKey(this.getEntityType(damagee))) { return; } Map damageDoneToThisEntity = new HashMap<>(); - if (damageDealt.containsKey(damagee.getEntityId())) { - damageDoneToThisEntity = damageDealt.get(damagee.getEntityId()); + if (this.damageDealt.containsKey(damagee.getEntityId())) { + damageDoneToThisEntity = this.damageDealt.get(damagee.getEntityId()); } else { - damageDealt.put(damagee.getEntityId(), damageDoneToThisEntity); + this.damageDealt.put(damagee.getEntityId(), damageDoneToThisEntity); } double totalDamageDealt = 0; @@ -66,32 +66,32 @@ public class EntityDamageListener implements Listener { @EventHandler public void onEntityDeath(EntityDeathEvent evt) { - Entity entity = evt.getEntity(); + LivingEntity entity = evt.getEntity(); - if (!damageDealt.containsKey(entity.getEntityId())) { + if (!this.damageDealt.containsKey(entity.getEntityId())) { return; } - Map damageDoneToThisEntity = damageDealt.get(entity.getEntityId()); - double totalDmg = ((LivingEntity) entity).getMaxHealth();//sumValues(damageDoneToThisEntity); + Map damageDoneToThisEntity = this.damageDealt.get(entity.getEntityId()); + double totalDmg = entity.getMaxHealth();//sumValues(damageDoneToThisEntity); for (Map.Entry entry : damageDoneToThisEntity.entrySet()) { double thisDmg = entry.getValue(); double thisPercent = (thisDmg / totalDmg) * 100.0D; - double thisAmount = plugin.getKillAmounts().get(getEntityType(entity)) * (thisPercent / 100); + double thisAmount = this.plugin.getKillAmounts().get(this.getEntityType(entity)) * (thisPercent / 100); OfflinePlayer offlinePlayer = Bukkit.getServer().getOfflinePlayer(entry.getKey()); if (offlinePlayer.isOnline()) { Player player = Bukkit.getServer().getPlayer(offlinePlayer.getUniqueId()); - this.plugin.getMessenger().sendMessage(player, "You have been awarded {1} for doing {2:.2f}% of the damage required to kill that {3}!", plugin.getSaneEconomy().getEconomyManager().getCurrency().formatAmount(thisAmount), thisPercent, entity.getName()); + this.plugin.getMessenger().sendMessage(player, "You have been awarded {1} for doing {2:.2f}% of the damage required to kill that {3}!", this.plugin.getSaneEconomy().getEconomyManager().getCurrency().formatAmount(thisAmount), thisPercent, entity.getName()); } - plugin.getSaneEconomy().getEconomyManager().transact(new Transaction( + this.plugin.getSaneEconomy().getEconomyManager().transact(new Transaction( this.plugin.getSaneEconomy().getEconomyManager().getCurrency(), Economable.PLUGIN, Economable.wrap(offlinePlayer), thisAmount, TransactionReason.PLUGIN_GIVE )); } - damageDealt.remove(evt.getEntity().getEntityId()); + this.damageDealt.remove(evt.getEntity().getEntityId()); } private String getEntityType(Entity entity) { diff --git a/SaneEconomyOnlineTime/src/main/java/org/appledash/saneeconomy/onlinetime/Payout.java b/SaneEconomyOnlineTime/src/main/java/org/appledash/saneeconomy/onlinetime/Payout.java index c8b52c3..e7650d7 100644 --- a/SaneEconomyOnlineTime/src/main/java/org/appledash/saneeconomy/onlinetime/Payout.java +++ b/SaneEconomyOnlineTime/src/main/java/org/appledash/saneeconomy/onlinetime/Payout.java @@ -11,7 +11,7 @@ public class Payout { private final double amount; private final String message; private String permission; - private long reportInterval; + private final long reportInterval; public Payout(int secondsInterval, double amount, String message, long reportInterval) { this.secondsInterval = secondsInterval; @@ -21,26 +21,26 @@ public class Payout { } public int getSecondsInterval() { - return secondsInterval; + return this.secondsInterval; } public double getAmount() { - return amount; + return this.amount; } public String getMessage() { - return message; + return this.message; } public static Payout fromConfigMap(Map values) { - return new Payout(Integer.valueOf(String.valueOf(values.get("seconds"))), Double.valueOf(String.valueOf(values.get("amount"))), String.valueOf(values.get("message")), Long.valueOf(String.valueOf(values.get("report_interval")))); + return new Payout(Integer.parseInt(String.valueOf(values.get("seconds"))), Double.parseDouble(String.valueOf(values.get("amount"))), String.valueOf(values.get("message")), Long.parseLong(String.valueOf(values.get("report_interval")))); } public String getPermission() { - return permission; + return this.permission; } public long getReportInterval() { - return reportInterval; + return this.reportInterval; } } diff --git a/SaneEconomyOnlineTime/src/main/java/org/appledash/saneeconomy/onlinetime/SaneEconomyOnlineTime.java b/SaneEconomyOnlineTime/src/main/java/org/appledash/saneeconomy/onlinetime/SaneEconomyOnlineTime.java index 29824f4..8f87d32 100644 --- a/SaneEconomyOnlineTime/src/main/java/org/appledash/saneeconomy/onlinetime/SaneEconomyOnlineTime.java +++ b/SaneEconomyOnlineTime/src/main/java/org/appledash/saneeconomy/onlinetime/SaneEconomyOnlineTime.java @@ -17,9 +17,9 @@ import java.util.*; * Blackjack is best pony. */ public class SaneEconomyOnlineTime extends SanePlugin implements Listener { - private Map onlineSeconds = new HashMap<>(); - private Map reportingAmounts = new HashMap<>(); - private List payouts = new ArrayList<>(); + private final Map onlineSeconds = new HashMap<>(); + private final Map reportingAmounts = new HashMap<>(); + private final List payouts = new ArrayList<>(); private SaneEconomy saneEconomy; @Override @@ -40,7 +40,7 @@ public class SaneEconomyOnlineTime extends SanePlugin implements Listener { this.onlineSeconds.put(player.getUniqueId(), onlineSeconds); - for (Payout payout : payouts) { + for (Payout payout : this.payouts) { if (payout.getPermission() != null && !player.hasPermission(payout.getPermission())) { continue; } @@ -56,8 +56,8 @@ public class SaneEconomyOnlineTime extends SanePlugin implements Listener { } if ((onlineSeconds % payout.getReportInterval()) == 0) { - this.getMessenger().sendMessage(player, payout.getMessage(), this.saneEconomy.getEconomyManager().getCurrency().formatAmount(this.reportingAmounts.getOrDefault(player.getUniqueId(), 0D)), payout.getReportInterval()); - this.reportingAmounts.put(player.getUniqueId(), 0D); + this.getMessenger().sendMessage(player, payout.getMessage(), this.saneEconomy.getEconomyManager().getCurrency().formatAmount(this.reportingAmounts.getOrDefault(player.getUniqueId(), 0.0D)), payout.getReportInterval()); + this.reportingAmounts.put(player.getUniqueId(), 0.0D); } } @@ -69,12 +69,7 @@ public class SaneEconomyOnlineTime extends SanePlugin implements Listener { @EventHandler public void onPlayerQuit(PlayerQuitEvent evt) { - if (this.onlineSeconds.containsKey(evt.getPlayer().getUniqueId())) { - this.onlineSeconds.remove(evt.getPlayer().getUniqueId()); - } - - if (this.reportingAmounts.containsKey(evt.getPlayer().getUniqueId())) { - this.reportingAmounts.remove(evt.getPlayer().getUniqueId()); - } + this.onlineSeconds.remove(evt.getPlayer().getUniqueId()); + this.reportingAmounts.remove(evt.getPlayer().getUniqueId()); } } diff --git a/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/SaneEconomySignShop.java b/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/SaneEconomySignShop.java index f377265..1ea1c79 100644 --- a/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/SaneEconomySignShop.java +++ b/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/SaneEconomySignShop.java @@ -21,14 +21,14 @@ import java.io.InputStreamReader; */ public class SaneEconomySignShop extends SanePlugin { private ISaneEconomy saneEconomy; - private final SignShopManager signShopManager = new SignShopManager(new SignShopStorageJSON(new File(getDataFolder(), "shops.json"))); + private final SignShopManager signShopManager = new SignShopManager(new SignShopStorageJSON(new File(this.getDataFolder(), "shops.json"))); private final LimitManager limitManager = new LimitManager(); @Override public void onEnable() { - if (!getServer().getPluginManager().isPluginEnabled("SaneEconomy")) { - getLogger().severe("SaneEconomy is not enabled on this server - something is wrong here!"); - getServer().getPluginManager().disablePlugin(this); + if (!this.getServer().getPluginManager().isPluginEnabled("SaneEconomy")) { + this.getLogger().severe("SaneEconomy is not enabled on this server - something is wrong here!"); + this.getServer().getPluginManager().disablePlugin(this); return; } @@ -36,32 +36,32 @@ public class SaneEconomySignShop extends SanePlugin { ItemDatabase.initItemDB(); - saneEconomy = (ISaneEconomy)getServer().getPluginManager().getPlugin("SaneEconomy"); + this.saneEconomy = (ISaneEconomy) this.getServer().getPluginManager().getPlugin("SaneEconomy"); // If it's stupid but it works... it's probably still stupid. - getLogger().info(String.format("Hooked into SaneEconomy version %s.", ((Plugin)saneEconomy).getDescription().getVersion())); + this.getLogger().info(String.format("Hooked into SaneEconomy version %s.", ((Plugin) this.saneEconomy).getDescription().getVersion())); - saveDefaultConfig(); + this.saveDefaultConfig(); - limitManager.loadLimits(YamlConfiguration.loadConfiguration(new InputStreamReader(getClass().getResourceAsStream("/limits.yml")))); // Always load from JAR - signShopManager.loadSignShops(); + this.limitManager.loadLimits(YamlConfiguration.loadConfiguration(new InputStreamReader(this.getClass().getResourceAsStream("/limits.yml")))); // Always load from JAR + this.signShopManager.loadSignShops(); - getServer().getScheduler().scheduleSyncRepeatingTask(this, limitManager::incrementLimitsHourly, 0, 20 * 60 * 60); + this.getServer().getScheduler().scheduleSyncRepeatingTask(this, this.limitManager::incrementLimitsHourly, 0, 20 * 60 * 60); - getServer().getPluginManager().registerEvents(new SignChangeListener(this), this); - getServer().getPluginManager().registerEvents(new InteractListener(this), this); - getServer().getPluginManager().registerEvents(new BreakListener(this), this); + this.getServer().getPluginManager().registerEvents(new SignChangeListener(this), this); + this.getServer().getPluginManager().registerEvents(new InteractListener(this), this); + this.getServer().getPluginManager().registerEvents(new BreakListener(this), this); } public SignShopManager getSignShopManager() { - return signShopManager; + return this.signShopManager; } public ISaneEconomy getSaneEconomy() { - return saneEconomy; + return this.saneEconomy; } public LimitManager getLimitManager() { - return limitManager; + return this.limitManager; } } diff --git a/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/listeners/BreakListener.java b/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/listeners/BreakListener.java index 2616dc9..e20035b 100644 --- a/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/listeners/BreakListener.java +++ b/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/listeners/BreakListener.java @@ -18,14 +18,14 @@ public class BreakListener implements Listener { @EventHandler public void onBlockBreak(BlockBreakEvent evt) { - plugin.getSignShopManager().getSignShop(evt.getBlock().getLocation()).ifPresent((shop) -> { + this.plugin.getSignShopManager().getSignShop(evt.getBlock().getLocation()).ifPresent((shop) -> { if (!evt.getPlayer().hasPermission("saneeconomy.signshop.destroy.admin")) { this.plugin.getMessenger().sendMessage(evt.getPlayer(), "You may not destroy that!"); evt.setCancelled(true); return; } - plugin.getSignShopManager().removeSignShop(shop); + this.plugin.getSignShopManager().removeSignShop(shop); this.plugin.getMessenger().sendMessage(evt.getPlayer(), "Sign shop destroyed!"); }); } diff --git a/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/listeners/InteractListener.java b/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/listeners/InteractListener.java index 1276ad5..911ddc1 100644 --- a/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/listeners/InteractListener.java +++ b/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/listeners/InteractListener.java @@ -49,7 +49,7 @@ public class InteractListener implements Listener { return; } - Optional shopOptional = plugin.getSignShopManager().getSignShop(evt.getClickedBlock().getLocation()); + Optional shopOptional = this.plugin.getSignShopManager().getSignShop(evt.getClickedBlock().getLocation()); if (!shopOptional.isPresent()) { return; @@ -65,7 +65,7 @@ public class InteractListener implements Listener { return; } - doBuy(shop, evt.getPlayer()); + this.doBuy(shop, evt.getPlayer()); } // Sell @@ -76,12 +76,12 @@ public class InteractListener implements Listener { return; } - doSell(shop, evt.getPlayer()); + this.doSell(shop, evt.getPlayer()); } } private void doBuy(SignShop shop, Player player) { - EconomyManager ecoMan = plugin.getSaneEconomy().getEconomyManager(); + EconomyManager ecoMan = this.plugin.getSaneEconomy().getEconomyManager(); int quantity = player.isSneaking() ? 1 : shop.getQuantity(); ShopTransaction shopTransaction = shop.makeTransaction(ecoMan.getCurrency(), player, TransactionDirection.BUY, quantity); @@ -103,7 +103,7 @@ public class InteractListener implements Listener { return; } - ItemStack stack = shop.getItemStack().clone(); + ItemStack stack = new ItemStack(shop.getItemStack()); /* Clone it so we don't modify the stack size in the shop */ stack.setAmount(quantity); player.getInventory().addItem(stack); @@ -112,7 +112,7 @@ public class InteractListener implements Listener { } private void doSell(SignShop shop, Player player) { // TODO: Selling enchanted items - EconomyManager ecoMan = plugin.getSaneEconomy().getEconomyManager(); + EconomyManager ecoMan = this.plugin.getSaneEconomy().getEconomyManager(); int quantity = player.isSneaking() ? 1 : shop.getQuantity(); double price = shop.getSellPrice(quantity); @@ -123,15 +123,15 @@ public class InteractListener implements Listener { ShopTransaction shopTransaction = shop.makeTransaction(ecoMan.getCurrency(), player, TransactionDirection.SELL, quantity); - if (!plugin.getLimitManager().shouldAllowTransaction(shopTransaction)) { + if (!this.plugin.getLimitManager().shouldAllowTransaction(shopTransaction)) { this.plugin.getMessenger().sendMessage(player, "You have reached your selling limit for the time being. Try back in an hour or so."); return; } - plugin.getLimitManager().setRemainingLimit(player, TransactionDirection.SELL, shop.getItem(), plugin.getLimitManager().getRemainingLimit(player, TransactionDirection.SELL, shop.getItem()) - quantity); + this.plugin.getLimitManager().setRemainingLimit(player, TransactionDirection.SELL, shop.getItem(), this.plugin.getLimitManager().getRemainingLimit(player, TransactionDirection.SELL, shop.getItem()) - quantity); - ItemStack stack = shop.getItemStack().clone(); + ItemStack stack = new ItemStack(shop.getItemStack()); /* Clone it so we don't modify the stack size in the shop */ stack.setAmount(quantity); player.getInventory().removeItem(stack); // FIXME: This does not remove items with damage values that were detected by contains() diff --git a/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/listeners/SignChangeListener.java b/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/listeners/SignChangeListener.java index 8e91bb5..cbcbb4a 100644 --- a/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/listeners/SignChangeListener.java +++ b/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/listeners/SignChangeListener.java @@ -33,7 +33,7 @@ public class SignChangeListener implements Listener { return; } - ParsedSignShop pss = parseSignShop(evt); + ParsedSignShop pss = this.parseSignShop(evt); if (pss.error != null) { this.plugin.getMessenger().sendMessage(evt.getPlayer(), "Cannot create shop: {1}", pss.error); @@ -45,20 +45,20 @@ public class SignChangeListener implements Listener { } SignShop signShop = pss.shop; - plugin.getSignShopManager().addSignShop(signShop); - evt.setLine(0, ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("admin-shop-title"))); + this.plugin.getSignShopManager().addSignShop(signShop); + evt.setLine(0, ChatColor.translateAlternateColorCodes('&', this.plugin.getConfig().getString("admin-shop-title"))); this.plugin.getMessenger().sendMessage(evt.getPlayer(), "Sign shop created!"); this.plugin.getMessenger().sendMessage(evt.getPlayer(), "Item: {1} x {2}", signShop.getQuantity(), signShop.getItemStack()); if (signShop.canBuy()) { // The player be buying from the shop, not the other way around. this.plugin.getMessenger().sendMessage(evt.getPlayer(), "Will sell to players for {1}.", - plugin.getSaneEconomy().getEconomyManager().getCurrency().formatAmount(signShop.getBuyPrice()) + this.plugin.getSaneEconomy().getEconomyManager().getCurrency().formatAmount(signShop.getBuyPrice()) ); } if (signShop.canSell()) { // The player be selling to the shop, not the other way around. this.plugin.getMessenger().sendMessage(evt.getPlayer(), "Will buy from players for {1}.", - plugin.getSaneEconomy().getEconomyManager().getCurrency().formatAmount(signShop.getSellPrice()) + this.plugin.getSaneEconomy().getEconomyManager().getCurrency().formatAmount(signShop.getSellPrice()) ); } } @@ -68,7 +68,7 @@ public class SignChangeListener implements Listener { Player player = evt.getPlayer(); Location location = evt.getBlock().getLocation(); - if ((lines[0] == null) || !lines[0].equalsIgnoreCase(plugin.getConfig().getString("admin-shop-trigger"))) { // First line must contain the trigger + if ((lines[0] == null) || !lines[0].equalsIgnoreCase(this.plugin.getConfig().getString("admin-shop-trigger"))) { // First line must contain the trigger return new ParsedSignShop(); } @@ -101,8 +101,8 @@ public class SignChangeListener implements Listener { return new ParsedSignShop("Invalid buy/sell prices specified."); } - double buy = Strings.isNullOrEmpty(m.group("buy")) ? -1.0 : Double.valueOf(m.group("buy")); - double sell = Strings.isNullOrEmpty(m.group("sell")) ? -1.0 : Double.valueOf(m.group("sell")); + double buy = Strings.isNullOrEmpty(m.group("buy")) ? -1.0 : Double.parseDouble(m.group("buy")); + double sell = Strings.isNullOrEmpty(m.group("sell")) ? -1.0 : Double.parseDouble(m.group("sell")); if ((buy == -1) && (sell == -1)) { return new ParsedSignShop("Buy and sell amounts for this shop are both invalid."); @@ -111,7 +111,7 @@ public class SignChangeListener implements Listener { int itemAmount; try { - itemAmount = Integer.valueOf(amountRaw); + itemAmount = Integer.parseInt(amountRaw); if (itemAmount <= 0) { throw new NumberFormatException(); @@ -123,7 +123,7 @@ public class SignChangeListener implements Listener { return new ParsedSignShop(new SignShop(player.getUniqueId(), location, itemStack, itemAmount, buy, sell)); } - private class ParsedSignShop { + private static final class ParsedSignShop { private SignShop shop; private String error; diff --git a/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/signshop/ShopTransaction.java b/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/signshop/ShopTransaction.java index a1286fc..5b29f56 100644 --- a/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/signshop/ShopTransaction.java +++ b/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/signshop/ShopTransaction.java @@ -30,30 +30,30 @@ public class ShopTransaction { } public TransactionDirection getDirection() { - return direction; + return this.direction; } public Player getPlayer() { - return player; + return this.player; } public ItemInfo getItem() { - return item; + return this.item; } public int getQuantity() { - return quantity; + return this.quantity; } public double getPrice() { - return price; + return this.price; } public Transaction makeEconomyTransaction() { - if (direction == TransactionDirection.BUY) { - return new Transaction(this.currency, Economable.wrap(player), Economable.PLUGIN, price, TransactionReason.PLUGIN_TAKE); + if (this.direction == TransactionDirection.BUY) { + return new Transaction(this.currency, Economable.wrap(this.player), Economable.PLUGIN, this.price, TransactionReason.PLUGIN_TAKE); } else { - return new Transaction(this.currency, Economable.PLUGIN, Economable.wrap(player), price, TransactionReason.PLUGIN_GIVE); + return new Transaction(this.currency, Economable.PLUGIN, Economable.wrap(this.player), this.price, TransactionReason.PLUGIN_GIVE); } } diff --git a/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/signshop/SignShop.java b/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/signshop/SignShop.java index 41c91db..14b299a 100644 --- a/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/signshop/SignShop.java +++ b/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/signshop/SignShop.java @@ -45,7 +45,7 @@ public class SignShop implements Serializable { * @return Location */ public Location getLocation() { - return location.getBukkitLocation(); + return this.location.getBukkitLocation(); } /** @@ -53,7 +53,7 @@ public class SignShop implements Serializable { * @return Material representing item/block type */ public ItemStack getItemStack() { - return item.toItemStack(); + return this.item.toItemStack(); } /** @@ -61,7 +61,7 @@ public class SignShop implements Serializable { * @return ItemInfo representing the type and quantity of item */ public ItemInfo getItem() { - return item; + return this.item; } /** @@ -69,7 +69,7 @@ public class SignShop implements Serializable { * @return Buy price for this.getQuantity() items */ public double getBuyPrice() { - return buyPrice; + return this.buyPrice; } /** @@ -77,7 +77,7 @@ public class SignShop implements Serializable { * @return Buy price for this.getQuantity() items */ public double getSellPrice() { - return sellPrice; + return this.sellPrice; } /** @@ -105,7 +105,7 @@ public class SignShop implements Serializable { * @return True if they can, false if they can't */ public boolean canBuy() { - return buyPrice >= 0; + return this.buyPrice >= 0; } /** @@ -113,7 +113,7 @@ public class SignShop implements Serializable { * @return True if they can, false if they can't */ public boolean canSell() { - return sellPrice >= 0; + return this.sellPrice >= 0; } /** @@ -121,7 +121,7 @@ public class SignShop implements Serializable { * @return UUID */ public UUID getOwnerUuid() { - return ownerUuid; + return this.ownerUuid; } /** @@ -129,10 +129,10 @@ public class SignShop implements Serializable { * @return Number of items */ public int getQuantity() { - return quantity; + return this.quantity; } public ShopTransaction makeTransaction(Currency currency, Player player, TransactionDirection direction, int quantity) { - return new ShopTransaction(currency, direction, player, item, quantity, (direction == TransactionDirection.BUY) ? getBuyPrice(quantity) : getSellPrice(quantity)); + return new ShopTransaction(currency, direction, player, this.item, quantity, (direction == TransactionDirection.BUY) ? this.getBuyPrice(quantity) : this.getSellPrice(quantity)); } } diff --git a/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/signshop/SignShopManager.java b/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/signshop/SignShopManager.java index 9b7e8ae..8775d72 100644 --- a/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/signshop/SignShopManager.java +++ b/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/signshop/SignShopManager.java @@ -17,18 +17,18 @@ public class SignShopManager { } public void loadSignShops() { - storage.loadSignShops(); + this.storage.loadSignShops(); } public void addSignShop(SignShop signShop) { - storage.putSignShop(signShop); + this.storage.putSignShop(signShop); } public void removeSignShop(SignShop signShop) { - storage.removeSignShop(signShop); + this.storage.removeSignShop(signShop); } public Optional getSignShop(Location location) { - return Optional.ofNullable(storage.getSignShops().get(location)); + return Optional.ofNullable(this.storage.getSignShops().get(location)); } } diff --git a/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/signshop/storage/SignShopStorageJSON.java b/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/signshop/storage/SignShopStorageJSON.java index 20ef203..6cb28e3 100644 --- a/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/signshop/storage/SignShopStorageJSON.java +++ b/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/signshop/storage/SignShopStorageJSON.java @@ -29,36 +29,35 @@ public class SignShopStorageJSON implements SignShopStorage { @Override @SuppressWarnings("unchecked") public void loadSignShops() { - if (!storageFile.exists()) { + if (!this.storageFile.exists()) { return; } try { - List tempShops = gson.fromJson(new FileReader(storageFile), new TypeToken>() {} .getType()); - tempShops.forEach((shop) -> cachedSignShops.put(shop.getLocation(), shop)); + List tempShops = this.gson.fromJson(new FileReader(this.storageFile), new TypeToken>() {} .getType()); + tempShops.forEach((shop) -> this.cachedSignShops.put(shop.getLocation(), shop)); } catch (FileNotFoundException e) { - throw new IllegalStateException("This shouldn't happen - the file " + storageFile.getAbsolutePath() + " disappeared while we were trying to read it!", e); + throw new IllegalStateException("This shouldn't happen - the file " + this.storageFile.getAbsolutePath() + " disappeared while we were trying to read it!", e); } - saveSignShops(); + this.saveSignShops(); } @Override public void putSignShop(SignShop signShop) { - cachedSignShops.put(signShop.getLocation(), signShop); - saveSignShops(); + this.cachedSignShops.put(signShop.getLocation(), signShop); + this.saveSignShops(); } @Override public void removeSignShop(SignShop signShop) { - cachedSignShops.remove(signShop.getLocation()); - saveSignShops(); + this.cachedSignShops.remove(signShop.getLocation()); + this.saveSignShops(); } private synchronized void saveSignShops() { - try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(storageFile, false))) { - bufferedWriter.write(gson.toJson(ImmutableList.copyOf(cachedSignShops.values()))); - bufferedWriter.close(); + try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(this.storageFile, false))) { + bufferedWriter.write(this.gson.toJson(ImmutableList.copyOf(this.cachedSignShops.values()))); } catch (IOException e) { throw new RuntimeException("Failed to save sign shops!", e); } @@ -66,6 +65,6 @@ public class SignShopStorageJSON implements SignShopStorage { @Override public Map getSignShops() { - return ImmutableMap.copyOf(cachedSignShops); + return ImmutableMap.copyOf(this.cachedSignShops); } } diff --git a/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/util/DefaultHashMap.java b/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/util/DefaultHashMap.java index 07f183c..e4f14e1 100644 --- a/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/util/DefaultHashMap.java +++ b/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/util/DefaultHashMap.java @@ -24,7 +24,7 @@ public class DefaultHashMap extends HashMap { V value = super.get(key); if (value == null) { - value = defaultSupplier.get((K)key); + value = this.defaultSupplier.get((K)key); this.put((K) key, value); } diff --git a/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/util/ItemDatabase.java b/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/util/ItemDatabase.java index 964314d..9d94abe 100644 --- a/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/util/ItemDatabase.java +++ b/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/util/ItemDatabase.java @@ -15,13 +15,17 @@ import java.util.Optional; * Created by appledash on 8/3/16. * Blackjack is still best pony. */ -public class ItemDatabase { +public final class ItemDatabase { private static Map> itemMap = new HashMap<>(); + private ItemDatabase() { + } + public static void initItemDB() { try (BufferedReader br = new BufferedReader(new InputStreamReader(ItemDatabase.class.getResourceAsStream("/items.csv")))) { String line; + //noinspection NestedAssignment while ((line = br.readLine()) != null) { if (line.startsWith("#") || !line.contains(",")) { continue; @@ -29,15 +33,15 @@ public class ItemDatabase { String[] split = line.split(","); String name = split[0]; - int id = Integer.valueOf(split[1]); - short damage = Short.valueOf(split[2]); + int id = Integer.parseInt(split[1]); + short damage = Short.parseShort(split[2]); itemMap.put(name.toLowerCase(), Pair.of(id, damage)); } itemMap = ImmutableMap.copyOf(itemMap); } catch (IOException | NumberFormatException e) { - e.printStackTrace(); + throw new RuntimeException("Failed to initialize item database!", e); } } @@ -62,7 +66,7 @@ public class ItemDatabase { damage = 0; } else { // They typed 'tnt:something' try { - damage = Short.valueOf(splitItemName[1]); + damage = Short.parseShort(splitItemName[1]); } catch (NumberFormatException e) { throw new InvalidItemException("Damage value must be a number."); } diff --git a/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/util/ItemInfo.java b/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/util/ItemInfo.java index 02a0dc8..936c6e4 100644 --- a/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/util/ItemInfo.java +++ b/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/util/ItemInfo.java @@ -26,7 +26,7 @@ public class ItemInfo implements Serializable { } public ItemStack toItemStack() { - return new ItemStack(material, amount, damage); + return new ItemStack(this.material, this.amount, this.damage); } @Override @@ -42,6 +42,6 @@ public class ItemInfo implements Serializable { @Override public int hashCode() { - return Objects.hash(material, damage); + return Objects.hash(this.material, this.damage); } } diff --git a/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/util/ItemLimits.java b/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/util/ItemLimits.java index da6eed4..e144417 100644 --- a/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/util/ItemLimits.java +++ b/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/util/ItemLimits.java @@ -17,10 +17,10 @@ public class ItemLimits { } public int getHourlyGain() { - return hourlyGain; + return this.hourlyGain; } public int getLimit() { - return limit; + return this.limit; } } diff --git a/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/util/LimitManager.java b/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/util/LimitManager.java index 101f0e6..7b2c5fe 100644 --- a/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/util/LimitManager.java +++ b/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/util/LimitManager.java @@ -21,7 +21,7 @@ public class LimitManager { // private final Map buyItemLimits = new DefaultHashMap(() -> ItemLimits.DEFAULT); private final Map sellItemLimits = new DefaultHashMap<>(() -> ItemLimits.DEFAULT); @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") - private final Map> sellPlayerLimits = new DefaultHashMap<>(() -> new DefaultHashMap<>((info) -> sellItemLimits.get(info).getLimit())); + private final Map> sellPlayerLimits = new DefaultHashMap<>(() -> new DefaultHashMap<>((info) -> this.sellItemLimits.get(info).getLimit())); // private final Map> itemLimits = new DefaultHashMap<>(() -> new DefaultHashMap<>(() -> ItemLimits.DEFAULT)); // This is a slightly complex data structure. It works like this: // It's a map of (limit types to (maps of players to (maps of materials to the remaining limit))). @@ -31,7 +31,7 @@ public class LimitManager { public int getRemainingLimit(Player player, TransactionDirection type, ItemInfo stack) { if (type == TransactionDirection.SELL) { - return sellPlayerLimits.get(player.getUniqueId()).get(stack); + return this.sellPlayerLimits.get(player.getUniqueId()).get(stack); } throw new IllegalArgumentException("Don't know how to get limits for that TransactionDirection!"); @@ -39,14 +39,14 @@ public class LimitManager { public void setRemainingLimit(Player player, TransactionDirection type, ItemInfo stack, int limit) { if (type == TransactionDirection.SELL) { - if (sellPlayerLimits.get(player.getUniqueId()).get(stack) == -1) { + if (this.sellPlayerLimits.get(player.getUniqueId()).get(stack) == -1) { return; } - limit = Math.min(limit, sellItemLimits.get(stack).getLimit()); + limit = Math.min(limit, this.sellItemLimits.get(stack).getLimit()); limit = Math.max(0, limit); - sellPlayerLimits.get(player.getUniqueId()).put(stack, limit); + this.sellPlayerLimits.get(player.getUniqueId()).put(stack, limit); return; } @@ -55,7 +55,7 @@ public class LimitManager { public boolean shouldAllowTransaction(ShopTransaction transaction) { // System.out.printf("Limit: %d, quantity: %d\n", limit, transaction.getQuantity()); - return getRemainingLimit(transaction.getPlayer(), transaction.getDirection(), transaction.getItem()) >= transaction.getQuantity(); + return this.getRemainingLimit(transaction.getPlayer(), transaction.getDirection(), transaction.getItem()) >= transaction.getQuantity(); } public void incrementLimitsHourly() { @@ -64,11 +64,11 @@ public class LimitManager { // For every limit // Increment limit by the limit for the specific direction and item. - sellPlayerLimits.forEach((playerUuid, itemToLimit) -> { + this.sellPlayerLimits.forEach((playerUuid, itemToLimit) -> { Map newLimits = new HashMap<>(); itemToLimit.forEach((itemInfo, currentLimit) -> - newLimits.put(itemInfo, currentLimit + (sellItemLimits.get(itemInfo).getHourlyGain()))); + newLimits.put(itemInfo, currentLimit + (this.sellItemLimits.get(itemInfo).getHourlyGain()))); itemToLimit.putAll(newLimits); }); @@ -77,8 +77,8 @@ public class LimitManager { public void loadLimits(ConfigurationSection config) { for (Map map : config.getMapList("sell")) { String itemName = String.valueOf(map.get("item")); - int sellLimit = Integer.valueOf(String.valueOf(map.get("limit"))); - int hourlyGain = Integer.valueOf(String.valueOf(map.get("gain"))); + int sellLimit = Integer.parseInt(String.valueOf(map.get("limit"))); + int hourlyGain = Integer.parseInt(String.valueOf(map.get("gain"))); ItemStack stack; try { @@ -91,7 +91,7 @@ public class LimitManager { ItemInfo itemInfo = new ItemInfo(stack); - sellItemLimits.put(itemInfo, new ItemLimits(sellLimit, hourlyGain)); + this.sellItemLimits.put(itemInfo, new ItemLimits(sellLimit, hourlyGain)); } } diff --git a/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/util/Pair.java b/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/util/Pair.java index 2ebefdc..097c158 100644 --- a/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/util/Pair.java +++ b/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/util/Pair.java @@ -14,11 +14,11 @@ public class Pair { } public K getLeft() { - return left; + return this.left; } public V getRight() { - return right; + return this.right; } public static Pair of(K k, V v) { diff --git a/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/util/SerializableLocation.java b/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/util/SerializableLocation.java index 2929d5f..eba1fec 100644 --- a/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/util/SerializableLocation.java +++ b/SaneEconomySignShop/src/main/java/org/appledash/saneeconomysignshop/util/SerializableLocation.java @@ -28,6 +28,6 @@ public class SerializableLocation implements Serializable { } public Location getBukkitLocation() { - return new Location(Bukkit.getServer().getWorld(worldUuid), x, y, z, yaw, pitch); + return new Location(Bukkit.getServer().getWorld(this.worldUuid), this.x, this.y, this.z, this.yaw, this.pitch); } }