Compare commits

...

20 Commits

Author SHA1 Message Date
AppleDash ed3ccceb1d
Merge pull request #103 from A248/master
Solve #100
2020-06-06 13:11:42 -04:00
A248 78d6c70658 Add and test EconomyManager#hasBalance to solve #100 2020-06-06 08:10:52 -04:00
AppleDash 2756e0c2d9 Add option to disable paying of online players. 2020-06-03 08:11:30 -04:00
AppleDash bb02d78b88 Fix failing tests (bug with equals instead of compareTo) 2020-06-03 08:06:50 -04:00
AppleDash 77ba58e333 Add API to get player name from UUID. 2020-06-03 08:05:23 -04:00
AppleDash c47524f863 Version bump & make some changes to the way table locking is used in MySQL. 2020-03-20 11:03:02 -04:00
AppleDash afa4e9d36e Clean up code a bit 2020-02-02 10:05:26 -05:00
AppleDash 854c2f5f10 Experimental baltop fixes and actually use the value of the last name. 2020-02-02 08:53:31 -05:00
AppleDash 2856305330 Fix a bug where the CONSOLE account does not have an infinite balance on databases upgraded from older versions. 2020-01-24 02:06:54 -05:00
AppleDash eab4b59501 Update SaneLib version 2020-01-24 01:50:18 -05:00
AppleDash d2fea85ffe Improvements to tests & version bump to 0.16.1 2019-11-11 16:08:04 -05:00
AppleDash 5663077718 Possibly fix multi-server sync 2019-11-10 17:54:03 -05:00
AppleDash 83d8965c23 General code cleanup 2019-11-04 12:25:17 -05:00
AppleDash fe4fc5018d Format code 2019-11-04 12:08:24 -05:00
AppleDash c269fc1065 Fix MySQL storage backend 2019-11-04 11:51:25 -05:00
AppleDash 2c3fcea269 Remove flatfile DB backend 2019-11-04 05:02:01 -05:00
AppleDash 9fdb09fc79 JSON schema update, probably 2019-11-04 05:01:09 -05:00
AppleDash dfaca9285e Version bump & MySQL schema update 2019-11-04 04:57:29 -05:00
AppleDash e2cc0f3f03 Make async transactions not crash the server 2019-11-04 04:49:41 -05:00
AppleDash db8970ebbd Experimental conversion to BigDecimal 2019-11-04 04:43:33 -05:00
71 changed files with 898 additions and 732 deletions

View File

@ -9,7 +9,7 @@
<version>0</version>
</parent>
<artifactId>SaneEconomyCore</artifactId>
<version>0.15.0-SNAPSHOT</version>
<version>0.17.2-SNAPSHOT</version>
<dependencies>
<dependency>

View File

@ -5,6 +5,7 @@ import org.appledash.saneeconomy.economy.logger.TransactionLogger;
import org.appledash.saneeconomy.vault.VaultHook;
import java.util.Optional;
import java.util.UUID;
/**
* Created by appledash on 9/18/16.
@ -27,4 +28,6 @@ public interface ISaneEconomy {
Optional<TransactionLogger> getTransactionLogger();
VaultHook getVaultHook();
String getLastName(UUID uuid);
}

View File

@ -36,13 +36,15 @@ public class SaneEconomy extends SanePlugin implements ISaneEconomy {
private TransactionLogger transactionLogger;
private GithubVersionChecker versionChecker;
private final Map<String, SaneCommand> COMMANDS = new HashMap<String, SaneCommand>() {{
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));
}};
private final Map<String, SaneCommand> commands = new HashMap<String, SaneCommand>() {
{
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));
}
};
public SaneEconomy() {
instance = this;
@ -52,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;
}
@ -61,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)) {
@ -95,6 +97,8 @@ public class SaneEconomy extends SanePlugin implements ISaneEconomy {
Arrays.stream(playersToSync).filter(p -> (p != null) && !p.isOnline()).forEach(p -> {
ByteArrayDataOutput bado = ByteStreams.newDataOutput();
bado.writeUTF("Forward");
bado.writeUTF("ONLINE");
bado.writeUTF("SaneEconomy");
bado.writeUTF("SyncPlayer");
bado.writeUTF(p.getUniqueId().toString());
@ -127,9 +131,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();
@ -141,8 +145,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?");
}
}
@ -150,15 +154,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();
@ -170,32 +174,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);
private void shutdown() {
this.getServer().getPluginManager().disablePlugin(this);
}
public GithubVersionChecker getVersionChecker() {
return versionChecker;
return this.versionChecker;
}
/**
@ -204,7 +208,7 @@ public class SaneEconomy extends SanePlugin implements ISaneEconomy {
*/
@Override
public EconomyManager getEconomyManager() {
return economyManager;
return this.economyManager;
}
/**
@ -213,7 +217,7 @@ public class SaneEconomy extends SanePlugin implements ISaneEconomy {
*/
@Override
public Optional<TransactionLogger> getTransactionLogger() {
return Optional.ofNullable(transactionLogger);
return Optional.ofNullable(this.transactionLogger);
}
/**
@ -229,12 +233,17 @@ public class SaneEconomy extends SanePlugin implements ISaneEconomy {
* Get the logger for the plugin.
* @return Plugin logger.
*/
public static Logger logger(){
public static Logger logger() {
return instance.getLogger();
}
@Override
public VaultHook getVaultHook() {
return vaultHook;
return this.vaultHook;
}
@Override
public String getLastName(UUID uuid) {
return this.economyManager.getBackend().getLastName("player:" + uuid.toString());
}
}

View File

@ -30,8 +30,8 @@ public class BalanceCommand extends SaneCommand {
@Override
public String[] getUsage() {
return new String[] {
"/<command> [player]"
};
"/<command> [player]"
};
}
@Override
@ -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)));
}
}
}

View File

@ -4,9 +4,9 @@ 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;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
@ -30,9 +30,9 @@ public class BalanceTopCommand extends SaneCommand {
@Override
public String[] getUsage() {
return new String[] {
"/<command>",
"/<command> <page>"
};
"/<command>",
"/<command> <page>"
};
}
@Override
@ -48,14 +48,14 @@ public class BalanceTopCommand extends SaneCommand {
try {
page = Math.abs(Integer.parseInt(args[0]));
} catch (NumberFormatException e) {
this.saneEconomy.getMessenger().sendMessage(sender, "{1} is not a valid number.");
this.saneEconomy.getMessenger().sendMessage(sender, "{1} is not a valid number.", args[0]);
return;
}
}
int offset = (page - 1) * nPerPage;
Map<String, Double> topBalances = this.saneEconomy.getEconomyManager().getTopBalances(nPerPage, offset);
Map<String, BigDecimal> topBalances = this.saneEconomy.getEconomyManager().getTopBalances(nPerPage, offset);
if (topBalances.isEmpty()) {
this.saneEconomy.getMessenger().sendMessage(sender, "There aren't enough players to display that page.");
@ -65,6 +65,12 @@ public class BalanceTopCommand extends SaneCommand {
AtomicInteger index = new AtomicInteger(offset + 1); /* I know it's stupid, but you can't do some_int++ from within the lambda. */
this.saneEconomy.getMessenger().sendMessage(sender, "Top {1} players on page {2}:", topBalances.size(), page);
topBalances.forEach((player, balance) -> this.saneEconomy.getMessenger().sendMessage(sender, "[{1:02d}] {2} - {3}", index.getAndIncrement(), player == null ? "<unknown>" : player, this.saneEconomy.getEconomyManager().getCurrency().formatAmount(balance)));
topBalances.forEach((player, balance) ->
this.saneEconomy.getMessenger().sendMessage(sender, "[{1:02d}] {2} - {3}",
index.getAndIncrement(),
player == null ? "<unknown>" : player,
this.saneEconomy.getEconomyManager().getCurrency().formatAmount(balance))
);
}
}

View File

@ -17,6 +17,8 @@ import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.math.BigDecimal;
/**
* Created by AppleDash on 6/13/2016.
* Blackjack is still best pony.
@ -37,8 +39,8 @@ public class EconomyAdminCommand extends SaneCommand {
@Override
public String[] getUsage() {
return new String[] {
"/<command> <give/take/set> [player] <amount>"
};
"/<command> <give/take/set> [player] <amount>"
};
}
@Override
@ -70,13 +72,13 @@ public class EconomyAdminCommand extends SaneCommand {
return;
}
EconomyManager ecoMan = saneEconomy.getEconomyManager();
EconomyManager ecoMan = this.saneEconomy.getEconomyManager();
Economable economable = Economable.wrap(targetPlayer);
double amount = NumberUtils.parseAndFilter(ecoMan.getCurrency(), sAmount);
BigDecimal amount = NumberUtils.parseAndFilter(ecoMan.getCurrency(), sAmount);
if (!(subCommand.equalsIgnoreCase("set") && amount == 0) && amount <= 0) { // If they're setting it to 0 it's fine, otherwise reject numbers under 1.
this.saneEconomy.getMessenger().sendMessage(sender, "{1} is not a positive number.", ((amount == -1) ? sAmount : String.valueOf(amount)));
if (!(subCommand.equalsIgnoreCase("set") && amount.equals(BigDecimal.ZERO)) && amount.compareTo(BigDecimal.ZERO) <= 0) { // If they're setting it to 0 it's fine, otherwise reject numbers under 1.
this.saneEconomy.getMessenger().sendMessage(sender, "{1} is not a positive number.", ((amount.equals(BigDecimal.ONE.negate())) ? sAmount : String.valueOf(amount)));
return;
}
@ -84,21 +86,21 @@ public class EconomyAdminCommand extends SaneCommand {
Transaction transaction = new Transaction(ecoMan.getCurrency(), Economable.wrap(sender), Economable.wrap(targetPlayer), amount, TransactionReason.ADMIN_GIVE);
TransactionResult result = ecoMan.transact(transaction);
double newAmount = result.getToBalance();
BigDecimal newAmount = result.getToBalance();
this.saneEconomy.getMessenger().sendMessage(sender, "Added {1} to {2}. Their balance is now {3}.",
ecoMan.getCurrency().formatAmount(amount),
sTargetPlayer,
ecoMan.getCurrency().formatAmount(newAmount)
);
);
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)
);
);
}
return;
}
@ -107,49 +109,49 @@ public class EconomyAdminCommand extends SaneCommand {
Transaction transaction = new Transaction(ecoMan.getCurrency(), Economable.wrap(targetPlayer), Economable.wrap(sender), amount, TransactionReason.ADMIN_TAKE);
TransactionResult result = ecoMan.transact(transaction);
double newAmount = result.getFromBalance();
BigDecimal newAmount = result.getFromBalance();
this.saneEconomy.getMessenger().sendMessage(sender, "Took {1} from {2}. Their balance is now {3}.",
ecoMan.getCurrency().formatAmount(amount),
sTargetPlayer,
ecoMan.getCurrency().formatAmount(newAmount)
);
);
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)
);
);
}
return;
}
if (subCommand.equalsIgnoreCase("set")) {
double oldBal = ecoMan.getBalance(economable);
BigDecimal oldBal = ecoMan.getBalance(economable);
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 > 0.0) {
if (oldBal.compareTo(BigDecimal.ZERO) > 0) {
logger.logTransaction(new Transaction(
ecoMan.getCurrency(), economable, Economable.CONSOLE, oldBal, TransactionReason.ADMIN_TAKE
));
ecoMan.getCurrency(), economable, Economable.CONSOLE, oldBal, TransactionReason.ADMIN_TAKE
));
}
logger.logTransaction(new Transaction(
ecoMan.getCurrency(), Economable.CONSOLE, economable, amount, TransactionReason.ADMIN_GIVE
));
ecoMan.getCurrency(), Economable.CONSOLE, economable, amount, TransactionReason.ADMIN_GIVE
));
});
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)
);
);
}
return;

View File

@ -15,6 +15,8 @@ import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.math.BigDecimal;
/**
* Created by AppleDash on 6/14/2016.
* Blackjack is still best pony.
@ -35,8 +37,8 @@ public class PayCommand extends SaneCommand {
@Override
public String[] getUsage() {
return new String[] {
"/pay <player> <amount>"
};
"/pay <player> <amount>"
};
}
@Override
@ -50,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];
@ -66,11 +68,16 @@ public class PayCommand extends SaneCommand {
return;
}
String sAmount = args[1];
double amount = NumberUtils.parseAndFilter(ecoMan.getCurrency(), sAmount);
if (!this.saneEconomy.getConfig().getConfigurationSection("economy").getBoolean("pay-offline-players", true) && !toPlayer.isOnline()) {
this.saneEconomy.getMessenger().sendMessage(sender, "You cannot pay an offline player.");
return;
}
if (amount <= 0) {
this.saneEconomy.getMessenger().sendMessage(sender, "{1} is not a positive number.", ((amount == -1) ? sAmount : String.valueOf(amount)));
String sAmount = args[1];
BigDecimal amount = NumberUtils.parseAndFilter(ecoMan.getCurrency(), sAmount);
if (amount.compareTo(BigDecimal.ZERO) <= 0) {
this.saneEconomy.getMessenger().sendMessage(sender, "{1} is not a positive number.", ((amount.equals(BigDecimal.ONE.negate())) ? sAmount : String.valueOf(amount)));
return;
}
@ -82,7 +89,7 @@ public class PayCommand extends SaneCommand {
this.saneEconomy.getMessenger().sendMessage(sender, "You do not have enough money to transfer {1} to {2}.",
ecoMan.getCurrency().formatAmount(amount),
sToPlayer
);
);
return;
}
@ -92,13 +99,13 @@ public class PayCommand extends SaneCommand {
this.saneEconomy.getMessenger().sendMessage(sender, "You have transferred {1} to {2}.",
ecoMan.getCurrency().formatAmount(amount),
sToPlayer
);
);
if (toPlayer.isOnline()) {
this.saneEconomy.getMessenger().sendMessage(((CommandSender) toPlayer), "You have received {1} from {2}.",
ecoMan.getCurrency().formatAmount(amount),
fromPlayer.getDisplayName()
);
);
}
}
}

View File

@ -26,10 +26,10 @@ public class SaneEcoCommand extends SaneCommand {
@Override
public String[] getUsage() {
return new String[] {
"/<command> reload - Reload everything.",
"/<command> reload-database - Reload the database.",
"/<command> reload-config - Reload the configuration."
};
"/<command> reload - Reload everything.",
"/<command> reload-database - Reload the database.",
"/<command> reload-config - Reload the configuration."
};
}
@Override
@ -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...");

View File

@ -5,6 +5,7 @@ import org.appledash.sanelib.messages.MessageUtils;
import org.bukkit.ChatColor;
import org.bukkit.configuration.ConfigurationSection;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
@ -29,6 +30,8 @@ public class Currency {
this.namePlural = namePlural;
this.format = format;
this.balanceFormat = balanceFormat;
this.format.setParseBigDecimal(true);
}
public static Currency fromConfig(ConfigurationSection config) {
@ -60,11 +63,11 @@ public class Currency {
}
return new Currency(
config.getString("name.singular", "dollar"),
config.getString("name.plural", "dollars"),
format,
config.getString("balance-format", "{1} {2}")
);
config.getString("name.singular", "dollar"),
config.getString("name.plural", "dollars"),
format,
config.getString("balance-format", "{1} {2}")
);
}
/**
@ -72,15 +75,10 @@ public class Currency {
* @param amount Money amount.
* @return Formatted amount string.
*/
public String formatAmount(double amount) {
String formatted;
if (amount == 1) {
formatted = MessageUtils.indexedFormat(balanceFormat, format.format(amount), nameSingular);
} else {
formatted = MessageUtils.indexedFormat(balanceFormat, format.format(amount), namePlural);
}
return ChatColor.translateAlternateColorCodes('&', formatted);
public String formatAmount(BigDecimal amount) {
return ChatColor.translateAlternateColorCodes('&',
MessageUtils.indexedFormat(this.balanceFormat, this.format.format(amount), amount.compareTo(BigDecimal.ONE) == 0 ? this.nameSingular : this.namePlural)
);
}
/**
@ -89,7 +87,7 @@ public class Currency {
* @return Singular name.
*/
public String getSingularName() {
return nameSingular;
return this.nameSingular;
}
/**
@ -98,7 +96,7 @@ public class Currency {
* @return Plural name.
*/
public String getPluralName() {
return namePlural;
return this.namePlural;
}
/**
@ -106,6 +104,6 @@ public class Currency {
* @return DecimalFormat instance
*/
public DecimalFormat getFormat() {
return format;
return this.format;
}
}

View File

@ -4,6 +4,7 @@ import org.appledash.saneeconomy.ISaneEconomy;
import org.appledash.saneeconomy.SaneEconomy;
import org.appledash.saneeconomy.economy.backend.EconomyStorageBackend;
import org.appledash.saneeconomy.economy.economable.Economable;
import org.appledash.saneeconomy.economy.economable.EconomableConsole;
import org.appledash.saneeconomy.economy.transaction.Transaction;
import org.appledash.saneeconomy.economy.transaction.TransactionResult;
import org.appledash.saneeconomy.event.SaneEconomyTransactionEvent;
@ -12,12 +13,10 @@ 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.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.*;
/**
* Created by AppleDash on 6/13/2016.
@ -30,6 +29,8 @@ public class EconomyManager {
private final Currency currency;
private final EconomyStorageBackend backend;
private final String serverAccountName;
private static final BigDecimal REQUIRED_BALANCE_ACCURACY = new BigDecimal("0.0001");
public EconomyManager(ISaneEconomy saneEconomy, Currency currency, EconomyStorageBackend backend, String serverAccountName) {
this.saneEconomy = saneEconomy;
@ -43,7 +44,7 @@ public class EconomyManager {
* @return Currency
*/
public Currency getCurrency() {
return currency;
return this.currency;
}
/**
@ -52,7 +53,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 +62,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);
}
/**
@ -69,12 +70,12 @@ public class EconomyManager {
* @param targetPlayer Player to get balance of
* @return Player's balance
*/
public double getBalance(Economable targetPlayer) {
if (targetPlayer == Economable.CONSOLE) {
return Double.MAX_VALUE;
public BigDecimal getBalance(Economable targetPlayer) {
if (EconomableConsole.isConsole(targetPlayer)) {
return new BigDecimal(Double.MAX_VALUE);
}
return backend.getBalance(targetPlayer);
return this.backend.getBalance(targetPlayer);
}
@ -84,9 +85,26 @@ public class EconomyManager {
* @param requiredBalance How much money we're checking for
* @return True if they have requiredBalance or more, false otherwise
*/
public boolean hasBalance(Economable targetPlayer, double requiredBalance) {
return (targetPlayer == Economable.CONSOLE) || (getBalance(targetPlayer) >= requiredBalance);
public boolean hasBalance(Economable targetPlayer, BigDecimal requiredBalance) {
return (EconomableConsole.isConsole(targetPlayer)) || (hasBalance(this.getBalance(targetPlayer), requiredBalance));
}
/**
* Compare account balance and required balance to a reasonable degree of accuracy. <br>
* <b>Visible for testing</b>
*
* @param accountBalance account balance
* @param requiredBalance required balance
* @return true if the account has the required balance to some degree of accuracy, false otherwise
*/
public boolean hasBalance(BigDecimal accountBalance, BigDecimal requiredBalance) {
if (accountBalance.compareTo(requiredBalance) >= 0) {
return true;
}
// Must compare to degree of accuracy
// See https://github.com/AppleDash/SaneEconomy/issues/100
BigDecimal difference = requiredBalance.subtract(accountBalance);
return difference.compareTo(REQUIRED_BALANCE_ACCURACY) < 0; // difference < PRECISION
}
/**
@ -96,8 +114,8 @@ public class EconomyManager {
* @param amount Amount to add
* @throws IllegalArgumentException If amount is negative
*/
private void addBalance(Economable targetPlayer, double amount) {
setBalance(targetPlayer, backend.getBalance(targetPlayer) + amount);
private void addBalance(Economable targetPlayer, BigDecimal amount) {
this.setBalance(targetPlayer, this.backend.getBalance(targetPlayer).add(amount));
}
/**
@ -109,9 +127,9 @@ public class EconomyManager {
* @param amount Amount to subtract
* @throws IllegalArgumentException If amount is negative
*/
private void subtractBalance(Economable targetPlayer, double amount) {
private void subtractBalance(Economable targetPlayer, BigDecimal amount) {
// Ensure we don't go negative.
setBalance(targetPlayer, Math.max(0.0, backend.getBalance(targetPlayer) - amount));
this.setBalance(targetPlayer, this.backend.getBalance(targetPlayer).subtract(amount).max(BigDecimal.ZERO));
}
/**
@ -120,14 +138,14 @@ public class EconomyManager {
* @param amount Amount to set balance to
* @throws IllegalArgumentException If amount is negative
*/
public void setBalance(Economable targetPlayer, double amount) {
amount = NumberUtils.filterAmount(currency, amount);
public void setBalance(Economable targetPlayer, BigDecimal amount) {
amount = NumberUtils.filterAmount(this.currency, amount);
if (targetPlayer == Economable.CONSOLE) {
if (EconomableConsole.isConsole(targetPlayer)) {
return;
}
backend.setBalance(targetPlayer, amount);
this.backend.setBalance(targetPlayer, amount);
}
/**
@ -138,22 +156,30 @@ public class EconomyManager {
public TransactionResult transact(Transaction transaction) {
Economable sender = transaction.getSender();
Economable receiver = transaction.getReceiver();
double amount = transaction.getAmount(); // This amount is validated and filtered upon creation of Transaction
BigDecimal amount = transaction.getAmount(); // This amount is validated and filtered upon creation of Transaction
if (Bukkit.getServer().getPluginManager() != null) { // Bukkit.getServer().getPluginManager() == null from our JUnit tests.
SaneEconomyTransactionEvent evt = new SaneEconomyTransactionEvent(transaction);
Future<SaneEconomyTransactionEvent> future = Bukkit.getServer().getScheduler().callSyncMethod(SaneEconomy.getInstance(), () -> {
if (Bukkit.isPrimaryThread()) {
Bukkit.getServer().getPluginManager().callEvent(evt);
return evt;
});
try {
if (future.get().isCancelled()) {
if (evt.isCancelled()) {
return new TransactionResult(transaction, TransactionResult.Status.CANCELLED_BY_PLUGIN);
}
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
} else {
Future<SaneEconomyTransactionEvent> future = Bukkit.getServer().getScheduler().callSyncMethod(SaneEconomy.getInstance(), () -> {
Bukkit.getServer().getPluginManager().callEvent(evt);
return evt;
});
try {
if (future.get().isCancelled()) {
return new TransactionResult(transaction, TransactionResult.Status.CANCELLED_BY_PLUGIN);
}
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
/*
@ -164,20 +190,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));
}
/**
@ -185,25 +211,25 @@ public class EconomyManager {
* @param amount Maximum number of players to show.
* @return Map of OfflinePlayer to Double
*/
public Map<String, Double> getTopBalances(int amount, int offset) {
LinkedHashMap<String, Double> uuidBalances = backend.getTopBalances();
public Map<String, BigDecimal> getTopBalances(int amount, int offset) {
LinkedHashMap<String, BigDecimal> playerNamesToBalances = this.backend.getTopBalances();
/* TODO
uuidBalances.forEach((uuid, balance) -> {
OfflinePlayer offlinePlayer = Bukkit.getServer().getOfflinePlayer(uuid);
if (offlinePlayer != null) {
/*uuidBalances.re((uuid, balance) -> {
String playerName = this.backend.getLastName(uuid);
if (playerName != null) {
if ((this.saneEconomy.getVaultHook() == null) || !this.saneEconomy.getVaultHook().hasPermission(offlinePlayer, "saneeconomy.balancetop.hide")) {
playerBalances.put(Bukkit.getServer().getOfflinePlayer(uuid), balance);
}
}
});
*/
});*/
return MapUtil.skipAndTake(uuidBalances, offset, amount);
return MapUtil.skipAndTake(playerNamesToBalances, offset, amount);
}
public EconomyStorageBackend getBackend() {
return backend;
return this.backend;
}
/**
@ -211,6 +237,6 @@ public class EconomyManager {
* @return Server economy account, or null if none.
*/
public String getServerAccountName() {
return serverAccountName;
return this.serverAccountName;
}
}

View File

@ -2,9 +2,9 @@ package org.appledash.saneeconomy.economy.backend;
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.
@ -25,20 +25,20 @@ public interface EconomyStorageBackend {
* @param economable Economable
* @return Player's current balance
*/
double getBalance(Economable economable);
BigDecimal getBalance(Economable economable);
/**
* Set the balance of an Economable, overwriting the old balance.
* @param economable Economable
* @param newBalance Player's new balance
*/
void setBalance(Economable economable, double newBalance);
void setBalance(Economable economable, BigDecimal newBalance);
/**
* Get the UUIDs of the players who have the most money, along with how much money they have.
* @return Map of player UUIDs to amounts.
*/
LinkedHashMap<String, Double> getTopBalances();
LinkedHashMap<String, BigDecimal> getTopBalances();
/**
* Reload this backend's database from disk.
@ -60,13 +60,21 @@ public interface EconomyStorageBackend {
* Get the balances of all entities in this database.
* @return Map of unique identifiers to balances.
*/
Map<String, Double> getAllBalances();
Map<String, BigDecimal> getAllBalances();
/**
* Wait until all of the data in memory has been written out to disk.
*/
void waitUntilFlushed();
/**
* Get the last name associated with a unique ID.
*
* @param uuid Unique ID.
* @return Last name, or null if none.
*/
String getLastName(String uuid);
enum EconomableReloadReason {
CROSS_SERVER_SYNC, PLAYER_JOIN
}

View File

@ -6,6 +6,7 @@ import org.appledash.saneeconomy.economy.backend.EconomyStorageBackend;
import org.appledash.saneeconomy.economy.economable.Economable;
import org.appledash.saneeconomy.utils.MapUtil;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
@ -17,42 +18,42 @@ import java.util.concurrent.ConcurrentHashMap;
* Blackjack is still best pony.
*/
public abstract class EconomyStorageBackendCaching implements EconomyStorageBackend {
protected Map<String, Double> balances = new ConcurrentHashMap<>();
private LinkedHashMap<String, Double> topBalances = new LinkedHashMap<>();
protected Map<String, BigDecimal> balances = new ConcurrentHashMap<>();
private LinkedHashMap<String, BigDecimal> topBalances = new LinkedHashMap<>();
protected Map<String, String> uuidToName = new HashMap<>();
@Override
public boolean accountExists(Economable economable) {
return balances.containsKey(economable.getUniqueIdentifier());
return this.balances.containsKey(economable.getUniqueIdentifier());
}
@Override
public double getBalance(Economable economable) {
if (!accountExists(economable)) {
return 0.0D;
public BigDecimal getBalance(Economable economable) {
if (!this.accountExists(economable)) {
return BigDecimal.ZERO;
}
return balances.get(economable.getUniqueIdentifier());
return this.balances.get(economable.getUniqueIdentifier());
}
public LinkedHashMap<String, Double> getTopBalances() {
return topBalances;
public LinkedHashMap<String, BigDecimal> getTopBalances() {
return this.topBalances;
}
@Override
public void reloadTopPlayerBalances() {
Map<String, Double> balances = new HashMap<>();
Map<String, BigDecimal> balances = new HashMap<>();
this.balances.forEach((identifier, balance) -> {
balances.put(this.uuidToName.get(identifier), balance);
});
this.balances.forEach((identifier, balance) ->
balances.put(this.uuidToName.get(identifier), balance)
);
topBalances = MapUtil.sortByValue(balances);
this.topBalances = MapUtil.sortByValue(balances);
}
@Override
public Map<String, Double> getAllBalances() {
return ImmutableMap.copyOf(balances);
public Map<String, BigDecimal> getAllBalances() {
return ImmutableMap.copyOf(this.balances);
}
@Override
@ -63,4 +64,9 @@ public abstract class EconomyStorageBackendCaching implements EconomyStorageBack
this.reloadDatabase();
}
@Override
public String getLastName(String uuid) {
return this.uuidToName.get(uuid);
}
}

View File

@ -1,107 +0,0 @@
package org.appledash.saneeconomy.economy.backend.type;
import com.google.common.io.Files;
import org.appledash.saneeconomy.SaneEconomy;
import org.appledash.saneeconomy.economy.economable.Economable;
import java.io.*;
import java.util.Map;
import java.util.UUID;
/**
* Created by AppleDash on 6/13/2016.
* Blackjack is still best pony.
*/
public class EconomyStorageBackendFlatfile extends EconomyStorageBackendCaching {
private static final int SCHEMA_VERSION = 3;
private final File file;
public EconomyStorageBackendFlatfile(File file) {
this.file = file;
}
@SuppressWarnings("unchecked")
@Override
public synchronized void reloadDatabase() {
if (!file.exists()) {
return;
}
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
int schemaVer = ois.readInt();
if (schemaVer == 2) {
ois.close();
loadSchemaVersion1(file);
return;
}
if (schemaVer != SCHEMA_VERSION) {
// ???
SaneEconomy.logger().severe("Unrecognized flatfile database version " + schemaVer + ", cannot load database!");
return;
}
balances = (Map<String, Double>) ois.readObject();
uuidToName = (Map<String, String>) ois.readObject();
ois.close();
} catch (IOException | ClassNotFoundException | ClassCastException e) {
SaneEconomy.logger().severe("Failed to load flatfile database!");
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
private void loadSchemaVersion1(File file) {
SaneEconomy.logger().info("Upgrading flatfile database from version 2.");
try {
Files.copy(file, new File(file.getParentFile(), file.getName() + "-backup"));
SaneEconomy.logger().info("Backed up old flatfile database.");
} catch (IOException e) {
throw new RuntimeException("Failed to back up flatfile database!");
}
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
ois.readInt(); // We already know it's 2.
this.balances = (Map<String, Double>) ois.readObject();
/* Yes, this is kind of bad, but we want to make sure we're loading AND saving the new version of the DB. */
saveDatabase();
reloadDatabase();
} catch (IOException | ClassNotFoundException e) {
SaneEconomy.logger().severe("Failed to upgrade flatfile database! Recommend reporting this bug and reverting to an older version of the plugin.");
throw new RuntimeException("Failed to upgrade flatfile database!", e);
}
}
private void saveDatabase() {
if (file.exists()) {
file.delete();
}
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeInt(SCHEMA_VERSION);
oos.writeObject(balances);
oos.writeObject(uuidToName);
oos.close();
} catch (IOException e) {
SaneEconomy.logger().severe("Failed to save flatfile database!");
}
}
@Override
public synchronized void setBalance(Economable economable, double newBalance) {
this.balances.put(economable.getUniqueIdentifier(), newBalance);
this.uuidToName.put(economable.getUniqueIdentifier(), economable.getName());
saveDatabase();
}
@Override
public void waitUntilFlushed() {
// Do nothing, database is automatically flushed on every write.
}
}

View File

@ -1,12 +1,12 @@
package org.appledash.saneeconomy.economy.backend.type;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
import org.appledash.saneeconomy.economy.economable.Economable;
import java.io.*;
import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@ -16,39 +16,46 @@ 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;
}
@Override
public void setBalance(Economable economable, double newBalance) {
balances.put(economable.getUniqueIdentifier(), newBalance);
saveDatabase();
public void setBalance(Economable economable, BigDecimal newBalance) {
this.balances.put(economable.getUniqueIdentifier(), newBalance);
this.uuidToName.put(economable.getUniqueIdentifier(), economable.getName());
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
balances = new ConcurrentHashMap<>((Map)gson.fromJson(new FileReader(file), new TypeToken<Map<String, Double>>(){}.getType()));
// if that fails, load the new format
DataHolderOld dataHolder = this.gson.fromJson(new FileReader(this.file), DataHolderOld.class);
this.balances = new ConcurrentHashMap<>();
this.uuidToName = new ConcurrentHashMap<>(dataHolder.uuidToName);
dataHolder.balances.forEach((s, bal) ->
this.balances.put(s, new BigDecimal(bal))
);
this.saveDatabase();
} catch (FileNotFoundException e) {
throw new RuntimeException("Failed to load database!", e);
} catch (Exception e) {
// if that fails, load the new format
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 e1) {
throw new RuntimeException("Failed to load database!", e1);
} catch (FileNotFoundException ex) {
throw new RuntimeException("Failed to load database!", ex);
}
}
}
@ -59,21 +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);
}
}
private static class DataHolder {
@SuppressWarnings({"FieldMayBeFinal", "CanBeFinal"})
private static class DataHolderOld {
@SerializedName("balances")
private Map<String, Double> balances;
@SerializedName("uuidToName")
private Map<String, String> uuidToName;
public DataHolder(Map<String, Double> balances, Map<String, String> uuidToName) {
DataHolderOld(Map<String, Double> balances, Map<String, String> uuidToName) {
this.balances = balances;
this.uuidToName = uuidToName;
}
}
@SuppressWarnings("FieldMayBeFinal")
private static class DataHolder {
@SerializedName("balances")
private Map<String, BigDecimal> balances;
@SerializedName("uuidToName")
private Map<String, String> uuidToName;
DataHolder(Map<String, BigDecimal> balances, Map<String, String> uuidToName) {
this.balances = balances;
this.uuidToName = uuidToName;
}

View File

@ -4,6 +4,7 @@ import org.appledash.saneeconomy.economy.economable.Economable;
import org.appledash.saneeconomy.utils.database.MySQLConnection;
import org.appledash.sanelib.database.DatabaseCredentials;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@ -17,6 +18,9 @@ import java.util.logging.Logger;
*/
public class EconomyStorageBackendMySQL extends EconomyStorageBackendCaching {
private static final Logger LOGGER = Logger.getLogger("EconomyStorageBackendMySQL");
private static final String SANEECONOMY_BALANCES = "saneeconomy_balances";
private static final String SANEECONOMY_SCHEMA = "saneeconomy_schema";
static {
LOGGER.setLevel(Level.FINEST);
}
@ -27,37 +31,47 @@ 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()) {
throw new RuntimeException("Invalid database schema!");
}
schemaVersion = Integer.valueOf(rs.getString("val"));
schemaVersion = Integer.parseInt(rs.getString("val"));
}
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', 3)", dbConn.getTable("saneeconomy_schema"))).executeUpdate();
conn.prepareStatement(String.format("CREATE TABLE `%s` (unique_identifier VARCHAR(128) PRIMARY KEY, last_name VARCHAR(16), balance DECIMAL(18, 2))", dbConn.getTable("saneeconomy_balances"))).executeUpdate();
schemaVersion = 3;
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) {
if (schemaVersion == 3) {
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;
}
if (schemaVersion != 4) {
throw new RuntimeException("Invalid database schema version!");
}
} catch (SQLException e) {
@ -66,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();
@ -81,16 +95,17 @@ 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"), rs.getDouble("balance"));
this.balances.put(rs.getString("unique_identifier"), new BigDecimal(rs.getString("balance")));
this.uuidToName.put(rs.getString("unique_identifier"), rs.getString("last_name"));
}
} catch (SQLException e) {
throw new RuntimeException("Failed to reload data from SQL.", e);
@ -98,30 +113,31 @@ public class EconomyStorageBackendMySQL extends EconomyStorageBackendCaching {
}
@Override
public void setBalance(final Economable economable, final double newBalance) {
final double 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);
this.uuidToName.put(economable.getUniqueIdentifier(), economable.getName());
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")));
statement.setDouble(1, newBalance);
this.ensureAccountExists(economable, conn);
this.dbConn.lockTable(conn, SANEECONOMY_BALANCES);
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();
this.dbConn.unlockTables(conn);
} 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();
@ -129,7 +145,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();
@ -139,11 +155,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() {
@ -153,14 +169,14 @@ 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();
if (rs.next()) {
this.balances.put(uniqueIdentifier, rs.getDouble("balance"));
this.balances.put(uniqueIdentifier, new BigDecimal(rs.getString("balance")));
}
} catch (SQLException e) {
throw new RuntimeException("SQL error has occured", e);

View File

@ -1,10 +1,14 @@
package org.appledash.saneeconomy.economy.economable;
import java.util.UUID;
/**
* Created by appledash on 9/21/16.
* Blackjack is best pony.
*/
public class EconomableConsole implements Economable {
public static final UUID CONSOLE_UUID = new UUID( 0xf88708c237d84a0bL, 0x944259c68e517557L); // Pregenerated for performance
@Override
public String getName() {
return "CONSOLE";
@ -12,6 +16,17 @@ public class EconomableConsole implements Economable {
@Override
public String getUniqueIdentifier() {
return "CONSOLE";
return "console:" + CONSOLE_UUID;
}
public static boolean isConsole(Economable economable) {
try {
UUID uuid = UUID.fromString(economable.getUniqueIdentifier().split(":")[1]);
// Fast comparison + fix for bugs with older databases
return economable == Economable.CONSOLE || (uuid.getLeastSignificantBits() == CONSOLE_UUID.getLeastSignificantBits() || uuid.getMostSignificantBits() == CONSOLE_UUID.getMostSignificantBits());
} catch (Exception e) {
return false;
}
}
}

View File

@ -13,7 +13,7 @@ public class EconomableFaction implements Economable {
@Override
public String getUniqueIdentifier() {
return "faction:" + factionUuid;
return "faction:" + this.factionUuid;
}
@Override

View File

@ -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); // FIXME: Why 16?
}
}

View File

@ -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

View File

@ -5,6 +5,7 @@ import org.appledash.saneeconomy.economy.transaction.TransactionReason;
import org.appledash.saneeconomy.utils.database.MySQLConnection;
import org.appledash.sanelib.database.DatabaseCredentials;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
@ -20,13 +21,13 @@ public class TransactionLoggerMySQL implements TransactionLogger {
this.dbConn = new MySQLConnection(credentials);
}
private void logGeneric(String from, String to, double change, TransactionReason reason) {
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.setDouble(3, change);
ps.setString(3, change.toString());
ps.setString(4, reason.toString());
ps.executeUpdate();
} catch (SQLException e) {
@ -36,8 +37,8 @@ public class TransactionLoggerMySQL implements TransactionLogger {
}
public boolean testConnection() {
if (dbConn.testConnection()) {
createTables();
if (this.dbConn.testConnection()) {
this.createTables();
return true;
}
@ -45,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);
@ -55,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());
}
}

View File

@ -2,9 +2,12 @@ package org.appledash.saneeconomy.economy.transaction;
import org.appledash.saneeconomy.economy.Currency;
import org.appledash.saneeconomy.economy.economable.Economable;
import org.appledash.saneeconomy.economy.economable.EconomableConsole;
import org.appledash.saneeconomy.economy.transaction.TransactionReason.AffectedParties;
import org.appledash.saneeconomy.utils.NumberUtils;
import java.math.BigDecimal;
/**
* Created by appledash on 9/21/16.
* Blackjack is best pony.
@ -12,11 +15,11 @@ import org.appledash.saneeconomy.utils.NumberUtils;
public class Transaction {
private final Economable sender;
private final Economable receiver;
private final double amount;
private final BigDecimal amount;
private final TransactionReason reason;
public Transaction(Currency currency, Economable sender, Economable receiver, double amount, TransactionReason reason) {
if (amount <= 0.0) {
public Transaction(Currency currency, Economable sender, Economable receiver, BigDecimal amount, TransactionReason reason) {
if (amount.compareTo(BigDecimal.ZERO) <= 0) {
throw new IllegalArgumentException("Cannot transact a zero or negative amount!");
}
@ -28,34 +31,34 @@ public class Transaction {
}
public Economable getSender() {
return sender;
return this.sender;
}
public Economable getReceiver() {
return receiver;
return this.receiver;
}
public double getAmount() {
return amount;
public BigDecimal getAmount() {
return this.amount;
}
public TransactionReason getReason() {
return reason;
return this.reason;
}
public boolean isSenderAffected() {
if (sender == Economable.CONSOLE) {
if (EconomableConsole.isConsole(this.sender)) {
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 (EconomableConsole.isConsole(this.receiver)) {
return false;
}
return (reason.getAffectedParties() == AffectedParties.RECEIVER) || (reason.getAffectedParties() == AffectedParties.BOTH);
return (this.reason.getAffectedParties() == AffectedParties.RECEIVER) || (this.reason.getAffectedParties() == AffectedParties.BOTH);
}
}

View File

@ -36,7 +36,7 @@ public enum TransactionReason {
}
public AffectedParties getAffectedParties() {
return affectedParties;
return this.affectedParties;
}
public enum AffectedParties {

View File

@ -1,16 +1,18 @@
package org.appledash.saneeconomy.economy.transaction;
import java.math.BigDecimal;
/**
* Created by appledash on 9/21/16.
* Blackjack is best pony.
*/
public class TransactionResult {
private final Transaction transaction;
private final double fromBalance;
private final double toBalance;
private final BigDecimal fromBalance;
private final BigDecimal toBalance;
private Status status;
public TransactionResult(Transaction transaction, double fromBalance, double toBalance) {
public TransactionResult(Transaction transaction, BigDecimal fromBalance, BigDecimal toBalance) {
this.transaction = transaction;
this.fromBalance = fromBalance;
this.toBalance = toBalance;
@ -18,24 +20,24 @@ public class TransactionResult {
}
public TransactionResult(Transaction transaction, Status status) {
this(transaction, -1, -1);
this(transaction, BigDecimal.ONE.negate(), BigDecimal.ONE.negate());
this.status = status;
}
public Transaction getTransaction() {
return transaction;
return this.transaction;
}
public double getFromBalance() {
return fromBalance;
public BigDecimal getFromBalance() {
return this.fromBalance;
}
public double getToBalance() {
return toBalance;
public BigDecimal getToBalance() {
return this.toBalance;
}
public Status getStatus() {
return status;
return this.status;
}
public enum Status {
@ -50,7 +52,7 @@ public class TransactionResult {
}
public String getMessage() {
return message;
return this.message;
}
}
}

View File

@ -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() {

View File

@ -14,6 +14,8 @@ import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import java.math.BigDecimal;
/**
* Created by AppleDash on 6/13/2016.
* Blackjack is still best pony.
@ -29,28 +31,28 @@ public class JoinQuitListener implements Listener {
public void onPlayerJoin(PlayerJoinEvent evt) {
Player player = evt.getPlayer();
Economable economable = Economable.wrap((OfflinePlayer) player);
double startBalance = plugin.getConfig().getDouble("economy.start-balance", 0.0D);
BigDecimal startBalance = BigDecimal.valueOf(this.plugin.getConfig().getDouble("economy.start-balance", 0.0D));
/* A starting balance is configured AND they haven't been given it yet. */
if ((startBalance > 0) && !plugin.getEconomyManager().accountExists(economable)) {
plugin.getEconomyManager().transact(new Transaction(
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 ((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 (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.
});
}
}

View File

@ -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() {

View File

@ -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) {

View File

@ -6,11 +6,14 @@ 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 <K, V extends Comparable<? super V>> LinkedHashMap<K, V> sortByValue(Map<K, V> map) {
List<Map.Entry<K, V>> list =
new LinkedList<>(map.entrySet());
new LinkedList<>(map.entrySet());
list.sort((o1, o2) -> -((o1.getValue()).compareTo(o2.getValue())));
@ -27,6 +30,7 @@ public class MapUtil {
* @param nSkip Number of items to skip
* @return New LinkedHashMap, may be empty.
*/
@SuppressWarnings("CollectionDeclaredAsConcreteClass")
public static <K, V> LinkedHashMap<K, V> skip(LinkedHashMap<K, V> map, int nSkip) {
LinkedHashMap<K, V> newMap = new LinkedHashMap<>();

View File

@ -3,6 +3,8 @@ package org.appledash.saneeconomy.utils;
import com.google.common.base.Strings;
import org.appledash.saneeconomy.economy.Currency;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
@ -10,10 +12,13 @@ import java.text.ParseException;
* Created by AppleDash on 6/14/2016.
* Blackjack is still best pony.
*/
public class NumberUtils {
private static final double INVALID_DOUBLE = -1;
public final class NumberUtils {
private static final BigDecimal INVALID_DOUBLE = BigDecimal.ONE.negate();
public static double parsePositiveDouble(String sDouble) {
private NumberUtils() {
}
public static BigDecimal parsePositiveDouble(String sDouble) {
if (Strings.isNullOrEmpty(sDouble)) {
return INVALID_DOUBLE;
}
@ -24,34 +29,54 @@ public class NumberUtils {
return INVALID_DOUBLE;
}
double doub;
BigDecimal doub;
try {
doub = NumberFormat.getInstance().parse(sDouble).doubleValue();
doub = (BigDecimal) constructDecimalFormat().parseObject(sDouble);
} catch (ParseException | NumberFormatException e) {
return INVALID_DOUBLE;
}
if (doub < 0) {
if (doub.compareTo(BigDecimal.ZERO) < 0) {
return INVALID_DOUBLE;
}
if (Double.isInfinite(doub) || Double.isNaN(doub)) {
/*if (Double.isInfinite(doub) || Double.isNaN(doub)) {
return INVALID_DOUBLE;
}
}*/
return doub;
}
public static double filterAmount(Currency currency, double amount) {
public static BigDecimal filterAmount(Currency currency, BigDecimal amount) {
try {
return NumberFormat.getInstance().parse(currency.getFormat().format(Math.abs(amount))).doubleValue();
return (BigDecimal) constructDecimalFormat().parse(currency.getFormat().format(amount.abs()));
} catch (ParseException e) {
throw new NumberFormatException();
}
}
public static double parseAndFilter(Currency currency, String sDouble) {
public static BigDecimal parseAndFilter(Currency currency, String sDouble) {
return filterAmount(currency, parsePositiveDouble(sDouble));
}
public static boolean equals(BigDecimal left, BigDecimal right) {
if (left == null) {
throw new NullPointerException("left == null");
}
if (right == null) {
throw new NullPointerException("right == null");
}
return left.compareTo(right) == 0;
}
private static DecimalFormat constructDecimalFormat() {
DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getInstance();
decimalFormat.setParseBigDecimal(true);
return decimalFormat;
}
}

View File

@ -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.
@ -23,6 +26,7 @@ public class PlayerUtils {
return player;
}
//noinspection ReuseOfLocalVariable
player = Bukkit.getServer().getPlayer(playerNameOrUUID);
if (player == null) {

View File

@ -5,7 +5,6 @@ import org.appledash.saneeconomy.SaneEconomy;
import org.appledash.saneeconomy.economy.Currency;
import org.appledash.saneeconomy.economy.EconomyManager;
import org.appledash.saneeconomy.economy.backend.EconomyStorageBackend;
import org.appledash.saneeconomy.economy.backend.type.EconomyStorageBackendFlatfile;
import org.appledash.saneeconomy.economy.backend.type.EconomyStorageBackendJSON;
import org.appledash.saneeconomy.economy.backend.type.EconomyStorageBackendMySQL;
import org.appledash.saneeconomy.economy.economable.EconomableGeneric;
@ -34,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));
}
/**
@ -77,31 +76,26 @@ public class SaneEconomyConfiguration {
EconomyStorageBackend backend;
String backendType = config.getString("type");
if (backendType.equalsIgnoreCase("flatfile")) {
String backendFileName = config.getString("file", "economy.db");
File backendFile = new File(saneEconomy.getDataFolder(), backendFileName);
backend = new EconomyStorageBackendFlatfile(backendFile);
logger.info("Initialized flatfile backend with file " + backendFile.getAbsolutePath());
} else if (backendType.equalsIgnoreCase("json")) {
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;
}
@ -111,38 +105,40 @@ public class SaneEconomyConfiguration {
/**
* Convert one EconomyStorageBackend to another.
* Right now, this just consists of converting all player balances. Data in the old backend is kept.
* Why is this in here?
* @param oldBackend Old backend
* @param newBackend New backend
*/
private void convertBackends(EconomyStorageBackend oldBackend, EconomyStorageBackend newBackend) {
oldBackend.getAllBalances().forEach((uniqueId, balance) -> {
newBackend.setBalance(new EconomableGeneric(uniqueId), balance);
});
oldBackend.getAllBalances().forEach((uniqueId, balance) ->
newBackend.setBalance(new EconomableGeneric(uniqueId), balance)
);
newBackend.waitUntilFlushed();
}
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;
}
@ -162,7 +158,7 @@ public class SaneEconomyConfiguration {
boolean useSsl = config.getBoolean("use_ssl", false);
return new DatabaseCredentials(
databaseType, backendHost, backendPort, backendUser, backendPass, backendDb, tablePrefix, useSsl
);
databaseType, backendHost, backendPort, backendUser, backendPass, backendDb, tablePrefix, useSsl
);
}
}

View File

@ -11,21 +11,26 @@ 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);
}
}

View File

@ -15,8 +15,10 @@ import java.util.logging.Logger;
*/
public class MySQLConnection {
private static final Logger LOGGER = Logger.getLogger("MySQLConnection");
public static final int FIVE_SECONDS = 5000;
private final DatabaseCredentials dbCredentials;
private final SaneDatabase saneDatabase;
private boolean canLockTables = true;
public MySQLConnection(DatabaseCredentials dbCredentials) {
this.dbCredentials = dbCredentials;
@ -34,13 +36,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();
@ -48,38 +50,63 @@ public class MySQLConnection {
}
}
public void lockTable(Connection conn, String tableName) throws SQLException {
if (!this.canLockTables) {
return;
}
try {
conn.prepareStatement("LOCK TABLE " + this.getTable(tableName) + " WRITE").execute();
this.canLockTables = true;
} catch (SQLException e) {
if (this.canLockTables) {
LOGGER.warning("Your MySQL user does not have privileges to LOCK TABLES - this may cause issues if you are running this plugin with the same database on multiple servers.");
}
this.canLockTables = false;
}
}
public void unlockTables(Connection conn) throws SQLException {
if (!this.canLockTables) {
return;
}
conn.prepareStatement("UNLOCK TABLES").execute();
}
public void executeAsyncOperation(String tag, Consumer<Connection> 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<Connection> 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() {
long startTime = System.currentTimeMillis();
while (!this.saneDatabase.areAllTransactionsDone()) {
if ((System.currentTimeMillis() - startTime) > 5000) {
if ((System.currentTimeMillis() - startTime) > FIVE_SECONDS) {
LOGGER.warning("Took too long to flush all transactions - something has probably hung :(");
break;
}

View File

@ -11,6 +11,7 @@ import org.appledash.saneeconomy.economy.transaction.TransactionResult;
import org.appledash.saneeconomy.utils.PlayerUtils;
import org.bukkit.OfflinePlayer;
import java.math.BigDecimal;
import java.util.List;
/**
@ -40,7 +41,7 @@ public class EconomySaneEconomy implements Economy {
@Override
public String format(double v) {
return SaneEconomy.getInstance().getEconomyManager().getCurrency().formatAmount(v);
return SaneEconomy.getInstance().getEconomyManager().getCurrency().formatAmount(new BigDecimal(v));
}
@Override
@ -55,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
@ -65,120 +66,120 @@ 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));
return SaneEconomy.getInstance().getEconomyManager().getBalance(this.makeEconomable(target)).doubleValue();
}
@Override
public double getBalance(OfflinePlayer offlinePlayer) {
return SaneEconomy.getInstance().getEconomyManager().getBalance(Economable.wrap(offlinePlayer));
return SaneEconomy.getInstance().getEconomyManager().getBalance(Economable.wrap(offlinePlayer)).doubleValue();
}
@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), amount);
return SaneEconomy.getInstance().getEconomyManager().hasBalance(this.makeEconomable(target), new BigDecimal(amount));
}
@Override
public boolean has(OfflinePlayer offlinePlayer, double amount) {
return SaneEconomy.getInstance().getEconomyManager().hasBalance(Economable.wrap(offlinePlayer), amount);
return SaneEconomy.getInstance().getEconomyManager().hasBalance(Economable.wrap(offlinePlayer), new BigDecimal(amount));
}
@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, 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(
SaneEconomy.getInstance().getEconomyManager().getCurrency(), Economable.wrap(offlinePlayer), Economable.PLUGIN, amount, TransactionReason.PLUGIN_TAKE
));
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), 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(
SaneEconomy.getInstance().getEconomyManager().getCurrency(), Economable.PLUGIN, Economable.wrap(offlinePlayer), v, TransactionReason.PLUGIN_GIVE
));
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
@ -270,7 +271,7 @@ public class EconomySaneEconomy implements Economy {
return Economable.CONSOLE;
}
if (validatePlayer(input)) {
if (this.validatePlayer(input)) {
return Economable.wrap(PlayerUtils.getOfflinePlayer(input));
}
@ -281,7 +282,7 @@ public class EconomySaneEconomy implements Economy {
TransactionResult result = SaneEconomy.getInstance().getEconomyManager().transact(transaction);
if (result.getStatus() == TransactionResult.Status.SUCCESS) {
return new EconomyResponse(transaction.getAmount(), result.getToBalance(), EconomyResponse.ResponseType.SUCCESS, null);
return new EconomyResponse(transaction.getAmount().doubleValue(), result.getToBalance().doubleValue(), EconomyResponse.ResponseType.SUCCESS, null);
}
return new EconomyResponse(0, 0, EconomyResponse.ResponseType.FAILURE, result.getStatus().toString());

View File

@ -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) {

View File

@ -25,8 +25,10 @@ economy:
notify-admin-give: false # Whether to notify players when /ecoadmin give is used on them.
notify-admin-take: false # Whether to notify players when /ecoadmin take is used on them.
notify-admin-set: false # Whether to notify players when /ecoadmin set is used on them.
pay-offline-players: true # Whether to allow paying offline players or not.
multi-server-sync: false # Experimental balance syncing without player rejoins, across BungeeCord networks.
update-check: true # Whether to check for updates to the plugin and notify admins about them.
locale-override: false # Whether to force the server's locale to be en_US.
debug: false # Debug mode, leave this set to false.
metrics: true # Whether to send anonymous metrics about the plugin's usage back to the developers, useful for fixing crashes.

View File

@ -7,6 +7,9 @@
# The order of placeholders can be changed. Anything after the :, like the '02d' in {1:02d} is a Java String.format specifier. If you don't know what that is, I recommend leaving it as-is.
# IMPORTANT: If your translation has a colon ( : ) character inside of it, you must enclose the entire part after "translation: " in single quotes ( ' ).
# If this file doesn't work for some reason, check your console for errors with "SnakeYAML" included in them.
####################################################################################################
########## READ ABOVE IF YOU INTEND TO EDIT THIS FILE, BEFORE ASKING FOR HELP! #####################
####################################################################################################
messages:
- message: "You don't have permission to check the balance of {1}."
- message: "That player is not online."

View File

@ -2,6 +2,7 @@ name: SaneEconomy
author: AppleDash
main: org.appledash.saneeconomy.SaneEconomy
version: ${project.version}
# api-version: '1.14'
load: STARTUP
softdepend: [Vault]
commands:

View File

@ -4,6 +4,7 @@ import org.appledash.saneeconomy.economy.Currency;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigDecimal;
import java.text.DecimalFormat;
/**
@ -14,7 +15,7 @@ public class CurrencyTest {
@Test
public void testCurrencyFormat() {
Currency currency = new Currency("test dollar", "test dollars", new DecimalFormat("0.00"));
Assert.assertEquals(currency.formatAmount(1.0D), "1.00 test dollar");
Assert.assertEquals(currency.formatAmount(1337.0D), "1337.00 test dollars");
Assert.assertEquals(currency.formatAmount(new BigDecimal("1.0")), "1.00 test dollar");
Assert.assertEquals(currency.formatAmount(new BigDecimal("1337.0")), "1337.00 test dollars");
}
}

View File

@ -19,9 +19,9 @@ public class EconomableTest {
@Test
public void testWrapFaction() {
UUID uuid = UUID.randomUUID();
Economable economable = Economable.wrap(String.format("faction-%s", uuid.toString()));
Economable economable = Economable.wrap(String.format("faction-%s", uuid));
Assert.assertEquals(economable.getClass(), EconomableFaction.class);
Assert.assertEquals(economable.getUniqueIdentifier(), String.format("faction:%s", uuid.toString()));
Assert.assertEquals(economable.getUniqueIdentifier(), String.format("faction:%s", uuid));
}
@Test

View File

@ -10,12 +10,15 @@ import org.appledash.saneeconomy.economy.transaction.TransactionResult;
import org.appledash.saneeconomy.test.mock.MockEconomyStorageBackend;
import org.appledash.saneeconomy.test.mock.MockOfflinePlayer;
import org.appledash.saneeconomy.test.mock.MockSaneEconomy;
import org.appledash.saneeconomy.test.util.SaneEcoAssert;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
/**
@ -27,9 +30,9 @@ public class EconomyManagerTest {
@Before
public void setupEconomyManager() {
economyManager = new EconomyManager(new MockSaneEconomy(),
new Currency("test dollar", "test dollars", new DecimalFormat("0.00")),
new MockEconomyStorageBackend(), null);
this.economyManager = new EconomyManager(new MockSaneEconomy(),
new Currency("test dollar", "test dollars", new DecimalFormat("0.00")),
new MockEconomyStorageBackend(), null);
}
@Test
@ -38,67 +41,65 @@ 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(0.0D, economyManager.getBalance(playerOne), 0.0);
Assert.assertEquals(0.0D, economyManager.getBalance(playerTwo), 0.0);
Assert.assertFalse(this.economyManager.accountExists(playerOne));
Assert.assertFalse(this.economyManager.accountExists(playerTwo));
SaneEcoAssert.assertEquals(BigDecimal.ZERO, this.economyManager.getBalance(playerOne));
SaneEcoAssert.assertEquals(BigDecimal.ZERO, this.economyManager.getBalance(playerTwo));
economyManager.setBalance(playerOne, 100.0D);
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(100.0, economyManager.getBalance(playerOne), 0.0);
Assert.assertEquals(0.0, economyManager.getBalance(playerTwo), 0.0);
SaneEcoAssert.assertEquals(new BigDecimal("100.00"), this.economyManager.getBalance(playerOne));
SaneEcoAssert.assertEquals(BigDecimal.ZERO, this.economyManager.getBalance(playerTwo));
// One should be able to transfer to two
Assert.assertTrue(economyManager.transact(new Transaction(economyManager.getCurrency(), playerOne, playerTwo, 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", 50.0, economyManager.getBalance(playerOne), 0.0);
Assert.assertEquals("Player two should have 50 dollars", 50.0, economyManager.getBalance(playerTwo), 0.0);
SaneEcoAssert.assertEquals("Player one should have 50 dollars", new BigDecimal("50.00"), this.economyManager.getBalance(playerOne));
SaneEcoAssert.assertEquals("Player two should have 50 dollars", new BigDecimal("50.00"), this.economyManager.getBalance(playerTwo));
// Ensure that balance addition and subtraction works...
Assert.assertEquals(25.0, economyManager.transact(
new Transaction(economyManager.getCurrency(), playerOne, Economable.CONSOLE, 25.0, TransactionReason.TEST_TAKE)
).getFromBalance(), 0.0);
SaneEcoAssert.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(50.0, economyManager.transact(
new Transaction(economyManager.getCurrency(), Economable.CONSOLE, playerOne, 25.0, TransactionReason.TEST_GIVE)
).getToBalance(), 0.0);
SaneEcoAssert.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, Double.MAX_VALUE, TransactionReason.TEST_TAKE)
).getStatus());
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, 50.0));
Assert.assertFalse(economyManager.hasBalance(playerOne, 51.0));
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<Economable> economables = new ArrayList<>(10);
Set<String> names = new HashSet<String>();
Set<String> names = new HashSet<>();
for (int i = 0; i < 10; i++) {
Economable economable = Economable.wrap(new MockOfflinePlayer("Dude" + i));
names.add("Dude" + i);
economables.add(economable);
this.economyManager.setBalance(economable, random.nextInt(1000));
this.economyManager.setBalance(economable, new BigDecimal(random.nextInt(1000)));
}
this.economyManager.getBackend().reloadTopPlayerBalances();
List<Double> javaSortedBalances = economables.stream().map(this.economyManager::getBalance).sorted((left, right) -> -left.compareTo(right)).collect(Collectors.toList());
List<Double> ecoManTopBalances = ImmutableList.copyOf(this.economyManager.getTopBalances(10, 0).values());
List<BigDecimal> javaSortedBalances = economables.stream().map(this.economyManager::getBalance).sorted((left, right) -> -left.compareTo(right)).collect(Collectors.toList());
List<BigDecimal> 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)));
@ -117,4 +118,25 @@ public class EconomyManagerTest {
return true;
}
@Test
public void testHasRequiredBalance() {
for (int n = 0; n < 20; n++) { // in the absence of Junit 5's @RepeatedTest
BigDecimal bigDecimal = randomBigDecimal();
// We MUST modify the BigDecimal in some way otherwise the test will always succeed
// See https://github.com/AppleDash/SaneEconomy/issues/100
for (int m = 0; m < 20; m++) {
bigDecimal = bigDecimal.add(randomBigDecimal()).subtract(randomBigDecimal());
}
//
Assert.assertTrue("Account must have required balance despite loss of precision (repeat " + n + ")",
economyManager.hasBalance(bigDecimal, new BigDecimal(bigDecimal.doubleValue())));
}
}
private static BigDecimal randomBigDecimal() {
return new BigDecimal(ThreadLocalRandom.current().nextDouble());
}
}

View File

@ -1,10 +1,12 @@
package org.appledash.saneeconomy.test;
import org.appledash.saneeconomy.economy.Currency;
import org.appledash.saneeconomy.test.util.SaneEcoAssert;
import org.appledash.saneeconomy.utils.NumberUtils;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Locale;
@ -16,21 +18,21 @@ public class NumberUtilsTest {
@Test
public void testParsePositive() {
// Valid input
Assert.assertEquals(69.0, NumberUtils.parsePositiveDouble("69.0"), 0.0);
SaneEcoAssert.assertEquals(new BigDecimal("69.0"), NumberUtils.parsePositiveDouble("69.0"));
// Valid but not positive
Assert.assertEquals(-1.0, NumberUtils.parsePositiveDouble("-10.0"), 0.0);
SaneEcoAssert.assertEquals(BigDecimal.ONE.negate(), NumberUtils.parsePositiveDouble("-10.0"));
// Invalid
Assert.assertEquals(-1.0, NumberUtils.parsePositiveDouble("nan"), 0.0);
Assert.assertEquals(-1.0, NumberUtils.parsePositiveDouble("ponies"), 0.0);
SaneEcoAssert.assertEquals(BigDecimal.ONE.negate(), NumberUtils.parsePositiveDouble("nan"));
SaneEcoAssert.assertEquals(BigDecimal.ONE.negate(), NumberUtils.parsePositiveDouble("ponies"));
// Infinite
Assert.assertEquals(-1.0, NumberUtils.parsePositiveDouble("1E1000000000"), 0.0);
// TODO: Not needed with BigDecimal? Assert.assertEquals(BigDecimal.ONE.negate(), NumberUtils.parsePositiveDouble("1E1000000000"));
}
@Test
public void testFilter() {
Currency currency = new Currency(null, null, new DecimalFormat("0.00"));
Assert.assertEquals(NumberUtils.filterAmount(currency, 1337.420D), 1337.42, 0.0);
SaneEcoAssert.assertEquals(new BigDecimal("1337.42"), NumberUtils.filterAmount(currency, new BigDecimal("1337.420")));
}
@Test
@ -38,7 +40,7 @@ public class NumberUtilsTest {
Locale old = Locale.getDefault();
Locale.setDefault(Locale.FRANCE);
try {
testFilter();
this.testFilter();
} catch (Throwable e) {
Locale.setDefault(old);
throw e;
@ -46,4 +48,14 @@ public class NumberUtilsTest {
Locale.setDefault(old);
}
}
@Test
public void testBigDecimalEquals() {
BigDecimal one = new BigDecimal("100.0");
BigDecimal two = new BigDecimal("100.00");
BigDecimal three = new BigDecimal("100.1");
Assert.assertTrue("100.0 should equal 100.00", NumberUtils.equals(one, two));
Assert.assertFalse("100.0 should not equal 100.1", NumberUtils.equals(one, three));
}
}

View File

@ -3,14 +3,16 @@ package org.appledash.saneeconomy.test.mock;
import org.appledash.saneeconomy.economy.backend.type.EconomyStorageBackendCaching;
import org.appledash.saneeconomy.economy.economable.Economable;
import java.math.BigDecimal;
/**
* Created by AppleDash on 7/29/2016.
* Blackjack is still best pony.
*/
public class MockEconomyStorageBackend extends EconomyStorageBackendCaching {
@Override
public void setBalance(Economable player, double newBalance) {
balances.put(player.getUniqueIdentifier(), newBalance);
public void setBalance(Economable player, BigDecimal newBalance) {
this.balances.put(player.getUniqueIdentifier(), newBalance);
this.uuidToName.put(player.getUniqueIdentifier(), player.getName());
}

View File

@ -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

View File

@ -6,6 +6,7 @@ import org.appledash.saneeconomy.economy.logger.TransactionLogger;
import org.appledash.saneeconomy.vault.VaultHook;
import java.util.Optional;
import java.util.UUID;
/**
* Created by appledash on 9/18/16.
@ -26,4 +27,9 @@ public class MockSaneEconomy implements ISaneEconomy {
public VaultHook getVaultHook() {
return null;
}
@Override
public String getLastName(UUID uuid) {
return uuid.toString();
}
}

View File

@ -34,6 +34,7 @@ import java.util.logging.Logger;
* Created by appledash on 7/15/17.
* Blackjack is best pony.
*/
@SuppressWarnings("all")
public class MockServer implements Server {
public static MockServer instance;
@ -47,8 +48,8 @@ public class MockServer implements Server {
}
private Logger logger = Logger.getLogger("MockServer");
private Map<UUID, OfflinePlayer> offlinePlayers = new HashMap<>();
private final Logger logger = Logger.getLogger("MockServer");
private final Map<UUID, OfflinePlayer> offlinePlayers = new HashMap<>();
public void addOfflinePlayer(OfflinePlayer offlinePlayer) {
this.offlinePlayers.put(offlinePlayer.getUniqueId(), offlinePlayer);
@ -501,12 +502,12 @@ public class MockServer implements Server {
}
@Override
public CachedServerIcon loadServerIcon(File file) throws IllegalArgumentException, Exception {
public CachedServerIcon loadServerIcon(File file) {
return null;
}
@Override
public CachedServerIcon loadServerIcon(BufferedImage bufferedImage) throws IllegalArgumentException, Exception {
public CachedServerIcon loadServerIcon(BufferedImage bufferedImage) {
return null;
}

View File

@ -0,0 +1,19 @@
package org.appledash.saneeconomy.test.util;
import org.appledash.saneeconomy.utils.NumberUtils;
import org.junit.Assert;
import java.math.BigDecimal;
public final class SaneEcoAssert {
private SaneEcoAssert() {
}
public static void assertEquals(BigDecimal left, BigDecimal right) {
Assert.assertTrue(String.format("%s != %s", left.toPlainString(), right.toPlainString()), NumberUtils.equals(left, right));
}
public static void assertEquals(String message, BigDecimal left, BigDecimal right) {
Assert.assertTrue(message, NumberUtils.equals(left, right));
}
}

View File

@ -16,7 +16,7 @@
<dependency>
<groupId>org.appledash</groupId>
<artifactId>SaneEconomyCore</artifactId>
<version>0.14.0-SNAPSHOT</version>
<version>0.17.2-SNAPSHOT</version>
</dependency>
</dependencies>

View File

@ -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<String, Double> getKillAmounts() {
return killAmounts;
return this.killAmounts;
}
}

View File

@ -12,6 +12,7 @@ import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@ -21,8 +22,8 @@ import java.util.UUID;
* Blackjack is still best pony.
*/
public class EntityDamageListener implements Listener {
private SaneEconomyMobKills plugin;
private Map<Integer, Map<UUID, Double>> damageDealt = new HashMap<>();
private final SaneEconomyMobKills plugin;
private final Map<Integer, Map<UUID, Double>> damageDealt = new HashMap<>();
public EntityDamageListener(SaneEconomyMobKills plugin) {
this.plugin = plugin;
@ -41,16 +42,16 @@ public class EntityDamageListener implements Listener {
return;
}
if (!plugin.getKillAmounts().containsKey(getEntityType(damagee))) {
if (!this.plugin.getKillAmounts().containsKey(this.getEntityType(damagee))) {
return;
}
Map<UUID, Double> 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 +67,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<UUID, Double> damageDoneToThisEntity = damageDealt.get(entity.getEntityId());
double totalDmg = ((LivingEntity) entity).getMaxHealth();//sumValues(damageDoneToThisEntity);
Map<UUID, Double> damageDoneToThisEntity = this.damageDealt.get(entity.getEntityId());
double totalDmg = entity.getMaxHealth();//sumValues(damageDoneToThisEntity);
for (Map.Entry<UUID, Double> 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(BigDecimal.valueOf(thisAmount)), thisPercent, entity.getName());
}
plugin.getSaneEconomy().getEconomyManager().transact(new Transaction(
this.plugin.getSaneEconomy().getEconomyManager().getCurrency(), Economable.PLUGIN, Economable.wrap(offlinePlayer), thisAmount, TransactionReason.PLUGIN_GIVE
));
this.plugin.getSaneEconomy().getEconomyManager().transact(new Transaction(
this.plugin.getSaneEconomy().getEconomyManager().getCurrency(), Economable.PLUGIN, Economable.wrap(offlinePlayer), BigDecimal.valueOf(thisAmount), TransactionReason.PLUGIN_GIVE
));
}
damageDealt.remove(evt.getEntity().getEntityId());
this.damageDealt.remove(evt.getEntity().getEntityId());
}
private String getEntityType(Entity entity) {

View File

@ -17,7 +17,7 @@
<dependency>
<groupId>org.appledash</groupId>
<artifactId>SaneEconomyCore</artifactId>
<version>0.14.0-SNAPSHOT</version>
<version>0.17.2-SNAPSHOT</version>
</dependency>
</dependencies>

View File

@ -1,5 +1,6 @@
package org.appledash.saneeconomy.onlinetime;
import java.math.BigDecimal;
import java.util.Map;
/**
@ -8,39 +9,39 @@ import java.util.Map;
*/
public class Payout {
private final int secondsInterval;
private final double amount;
private final BigDecimal 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;
this.amount = amount;
this.amount = BigDecimal.valueOf(amount);
this.message = message;
this.reportInterval = reportInterval;
}
public int getSecondsInterval() {
return secondsInterval;
return this.secondsInterval;
}
public double getAmount() {
return amount;
public BigDecimal getAmount() {
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;
}
}

View File

@ -10,6 +10,7 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent;
import java.math.BigDecimal;
import java.util.*;
/**
@ -17,9 +18,9 @@ import java.util.*;
* Blackjack is best pony.
*/
public class SaneEconomyOnlineTime extends SanePlugin implements Listener {
private Map<UUID, Long> onlineSeconds = new HashMap<>();
private Map<UUID, Double> reportingAmounts = new HashMap<>();
private List<Payout> payouts = new ArrayList<>();
private final Map<UUID, Long> onlineSeconds = new HashMap<>();
private final Map<UUID, BigDecimal> reportingAmounts = new HashMap<>();
private final List<Payout> payouts = new ArrayList<>();
private SaneEconomy saneEconomy;
@Override
@ -40,14 +41,14 @@ 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;
}
if ((onlineSeconds % payout.getSecondsInterval()) == 0) {
if (this.reportingAmounts.containsKey(player.getUniqueId())) {
this.reportingAmounts.put(player.getUniqueId(), this.reportingAmounts.get(player.getUniqueId()) + payout.getAmount());
this.reportingAmounts.put(player.getUniqueId(), this.reportingAmounts.get(player.getUniqueId()).add(payout.getAmount()));
} else {
this.reportingAmounts.put(player.getUniqueId(), payout.getAmount());
}
@ -56,25 +57,20 @@ 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(), BigDecimal.ZERO)), payout.getReportInterval());
this.reportingAmounts.put(player.getUniqueId(), BigDecimal.ZERO);
}
}
}
},0, 20);
}, 0, 20);
this.getServer().getPluginManager().registerEvents(this, this);
}
@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());
}
}

View File

@ -16,7 +16,7 @@
<dependency>
<groupId>org.appledash</groupId>
<artifactId>SaneEconomyCore</artifactId>
<version>0.14.0-SNAPSHOT</version>
<version>0.17.2-SNAPSHOT</version>
</dependency>
</dependencies>

View File

@ -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;
}
}

View File

@ -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!");
});
}

View File

@ -16,6 +16,7 @@ import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import java.math.BigDecimal;
import java.util.Optional;
import java.util.logging.Logger;
@ -49,7 +50,7 @@ public class InteractListener implements Listener {
return;
}
Optional<SignShop> shopOptional = plugin.getSignShopManager().getSignShop(evt.getClickedBlock().getLocation());
Optional<SignShop> shopOptional = this.plugin.getSignShopManager().getSignShop(evt.getClickedBlock().getLocation());
if (!shopOptional.isPresent()) {
return;
@ -65,7 +66,7 @@ public class InteractListener implements Listener {
return;
}
doBuy(shop, evt.getPlayer());
this.doBuy(shop, evt.getPlayer());
}
// Sell
@ -76,12 +77,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 +104,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,9 +113,9 @@ 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);
BigDecimal price = shop.getSellPrice(quantity);
if (!player.getInventory().containsAtLeast(new ItemStack(shop.getItemStack()), quantity)) {
this.plugin.getMessenger().sendMessage(player, "You do not have {1} {2}!", quantity, shop.getItemStack().getType().name());
@ -123,15 +124,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()

View File

@ -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,21 +45,21 @@ 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;

View File

@ -7,6 +7,8 @@ import org.appledash.saneeconomy.economy.transaction.TransactionReason;
import org.appledash.saneeconomysignshop.util.ItemInfo;
import org.bukkit.entity.Player;
import java.math.BigDecimal;
/**
* Created by appledash on 1/1/17.
* Blackjack is still best pony.
@ -18,9 +20,9 @@ public class ShopTransaction {
private final Player player;
private final ItemInfo item;
private final int quantity;
private final double price;
private final BigDecimal price;
public ShopTransaction(Currency currency, TransactionDirection direction, Player player, ItemInfo item, int quantity, double price) {
public ShopTransaction(Currency currency, TransactionDirection direction, Player player, ItemInfo item, int quantity, BigDecimal price) {
this.currency = currency;
this.direction = direction;
this.player = player;
@ -30,30 +32,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;
public BigDecimal getPrice() {
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);
}
}

View File

@ -9,6 +9,7 @@ import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.UUID;
/**
@ -20,8 +21,8 @@ public class SignShop implements Serializable {
private final SerializableLocation location;
private final ItemInfo item;
private final int quantity;
private final double buyPrice;
private final double sellPrice;
private final BigDecimal buyPrice;
private final BigDecimal sellPrice;
public SignShop(UUID ownerUuid, Location location, ItemStack item, int quantity, double buyPrice, double sellPrice) {
if ((ownerUuid == null) || (location == null) || (item == null)) {
@ -36,8 +37,8 @@ public class SignShop implements Serializable {
this.location = new SerializableLocation(location);
this.item = new ItemInfo(item);
this.quantity = quantity;
this.buyPrice = buyPrice;
this.sellPrice = sellPrice;
this.buyPrice = BigDecimal.valueOf(buyPrice);
this.sellPrice = BigDecimal.valueOf(sellPrice);
}
/**
@ -45,7 +46,7 @@ public class SignShop implements Serializable {
* @return Location
*/
public Location getLocation() {
return location.getBukkitLocation();
return this.location.getBukkitLocation();
}
/**
@ -53,7 +54,7 @@ public class SignShop implements Serializable {
* @return Material representing item/block type
*/
public ItemStack getItemStack() {
return item.toItemStack();
return this.item.toItemStack();
}
/**
@ -61,23 +62,23 @@ public class SignShop implements Serializable {
* @return ItemInfo representing the type and quantity of item
*/
public ItemInfo getItem() {
return item;
return this.item;
}
/**
* Get the price that the player can buy this item from the server for
* @return Buy price for this.getQuantity() items
*/
public double getBuyPrice() {
return buyPrice;
public BigDecimal getBuyPrice() {
return this.buyPrice;
}
/**
* Get the price that the player can sell this item to the server for
* @return Buy price for this.getQuantity() items
*/
public double getSellPrice() {
return sellPrice;
public BigDecimal getSellPrice() {
return this.sellPrice;
}
/**
@ -86,8 +87,8 @@ public class SignShop implements Serializable {
* @param quantity Quantity of items to price
* @return Price to buy that number of items at this shop
*/
public double getBuyPrice(int quantity) {
return this.buyPrice * ((float)quantity / (float)this.quantity); // TODO: Is this okay?
public BigDecimal getBuyPrice(int quantity) {
return this.buyPrice.multiply(BigDecimal.valueOf((double) quantity / this.quantity)); // TODO: Is this okay?
}
/**
@ -96,8 +97,8 @@ public class SignShop implements Serializable {
* @param quantity Quantity of items to price
* @return Price to sell that number of items at this shop
*/
public double getSellPrice(int quantity) {
return this.sellPrice * ((float)quantity / (float)this.quantity); // TODO: Is this okay?
public BigDecimal getSellPrice(int quantity) {
return this.sellPrice.multiply(BigDecimal.valueOf((double) quantity / this.quantity)); // TODO: Is this okay?
}
/**
@ -105,7 +106,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.compareTo(BigDecimal.ZERO) >= 0;
}
/**
@ -113,7 +114,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.compareTo(BigDecimal.ZERO) >= 0;
}
/**
@ -121,7 +122,7 @@ public class SignShop implements Serializable {
* @return UUID
*/
public UUID getOwnerUuid() {
return ownerUuid;
return this.ownerUuid;
}
/**
@ -129,10 +130,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));
}
}

View File

@ -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<SignShop> getSignShop(Location location) {
return Optional.ofNullable(storage.getSignShops().get(location));
return Optional.ofNullable(this.storage.getSignShops().get(location));
}
}

View File

@ -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<SignShop> tempShops = gson.fromJson(new FileReader(storageFile), new TypeToken<List<SignShop>>(){}.getType());
tempShops.forEach((shop) -> cachedSignShops.put(shop.getLocation(), shop));
List<SignShop> tempShops = this.gson.fromJson(new FileReader(this.storageFile), new TypeToken<List<SignShop>>() {} .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<Location, SignShop> getSignShops() {
return ImmutableMap.copyOf(cachedSignShops);
return ImmutableMap.copyOf(this.cachedSignShops);
}
}

View File

@ -24,7 +24,7 @@ public class DefaultHashMap<K, V> extends HashMap<K, V> {
V value = super.get(key);
if (value == null) {
value = defaultSupplier.get((K)key);
value = this.defaultSupplier.get((K)key);
this.put((K) key, value);
}

View File

@ -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<String, Pair<Integer, Short>> 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.");
}

View File

@ -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);
}
}

View File

@ -17,10 +17,10 @@ public class ItemLimits {
}
public int getHourlyGain() {
return hourlyGain;
return this.hourlyGain;
}
public int getLimit() {
return limit;
return this.limit;
}
}

View File

@ -21,7 +21,7 @@ public class LimitManager {
// private final Map<ItemInfo, ItemLimits> buyItemLimits = new DefaultHashMap<ItemInfo, ItemLimits>(() -> ItemLimits.DEFAULT);
private final Map<ItemInfo, ItemLimits> sellItemLimits = new DefaultHashMap<>(() -> ItemLimits.DEFAULT);
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
private final Map<UUID, Map<ItemInfo, Integer>> sellPlayerLimits = new DefaultHashMap<>(() -> new DefaultHashMap<>((info) -> sellItemLimits.get(info).getLimit()));
private final Map<UUID, Map<ItemInfo, Integer>> sellPlayerLimits = new DefaultHashMap<>(() -> new DefaultHashMap<>((info) -> this.sellItemLimits.get(info).getLimit()));
// private final Map<TransactionDirection, Map<ItemInfo, ItemLimits>> 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,20 +55,20 @@ 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() {
// For every limit type
// For every player
// For every limit
// Increment limit by the limit for the specific direction and item.
// For every player
// For every limit
// Increment limit by the limit for the specific direction and item.
sellPlayerLimits.forEach((playerUuid, itemToLimit) -> {
this.sellPlayerLimits.forEach((playerUuid, itemToLimit) -> {
Map<ItemInfo, Integer> 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));
}
}

View File

@ -14,14 +14,14 @@ public class Pair<K, V> {
}
public K getLeft() {
return left;
return this.left;
}
public V getRight() {
return right;
return this.right;
}
public static <K, V> Pair<K, V> of(K k, V v) {
return new Pair<>(k, v);
}
}
}

View File

@ -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);
}
}

9
astyle.conf Normal file
View File

@ -0,0 +1,9 @@
--mode=java
--style=java # Bracket formatting
--indent=spaces=4
--indent-switches
--pad-oper
--pad-header
--add-brackets
--suffix=none # Do not backup original file
--lineend=linux

View File

@ -43,7 +43,7 @@
<dependency>
<groupId>org.appledash</groupId>
<artifactId>sanelib</artifactId>
<version>0.3.7-SNAPSHOT</version>
<version>0.4.1-SNAPSHOT</version>
</dependency>
</dependencies>