diff --git a/README.md b/README.md index 0ee5d71..9755670 100644 --- a/README.md +++ b/README.md @@ -13,10 +13,10 @@ EconomyLite is a lightweight, yet advanced economy plugin for your Sponge server - EconomyLite is multi-threaded for the best possible performance - Multiple Storage Options - Store your data however you like, locally or on a MySQL database +- Migration + - EconomyLite allows you to easily migrate your data from another economy plugin - Customizable - Much of EconomyLite can be changed to suit your needs -- Username Change Support - - Any player can change their name, and EconomyLite can handle it - Virtual Management - EconomyLite includes commands to manage virtual accounts - Loans diff --git a/build.gradle b/build.gradle index 3ab08da..0fbac0c 100644 --- a/build.gradle +++ b/build.gradle @@ -26,7 +26,7 @@ repositories { dependencies { compile "org.spongepowered:spongeapi:${project.apiVersion}" - compile 'com.github.flibiostudio:utils:5f41eac' + compile 'com.github.flibiostudio:utils:2115eae' } shadowJar { diff --git a/gradle.properties b/gradle.properties index 245fbcf..c104358 100644 --- a/gradle.properties +++ b/gradle.properties @@ -2,5 +2,5 @@ name=EconomyLite owner=Flibio inceptionYear=2015 currentYear=2018 -version=3.0.0 +version=2.14.0 apiVersion=7.1.0-SNAPSHOT \ No newline at end of file diff --git a/src/main/java/io/github/flibio/economylite/EconomyLite.java b/src/main/java/io/github/flibio/economylite/EconomyLite.java index 59d6aaf..36155c7 100644 --- a/src/main/java/io/github/flibio/economylite/EconomyLite.java +++ b/src/main/java/io/github/flibio/economylite/EconomyLite.java @@ -39,9 +39,11 @@ import io.github.flibio.economylite.modules.loan.LoanModule; import io.github.flibio.economylite.modules.sql.SqlModule; import io.github.flibio.utils.commands.CommandLoader; +import io.github.flibio.utils.config.ConfigManager; import io.github.flibio.utils.file.FileManager; import io.github.flibio.utils.message.MessageStorage; import ninja.leaping.configurate.ConfigurationNode; +import ninja.leaping.configurate.commented.CommentedConfigurationNode; import org.slf4j.Logger; import org.spongepowered.api.Game; import org.spongepowered.api.config.ConfigDir; @@ -60,6 +62,8 @@ import java.util.List; import java.util.Optional; +import javax.xml.stream.events.Comment; + @Plugin(id = PluginInfo.ID, name = PluginInfo.NAME, version = PluginInfo.VERSION, description = PluginInfo.DESCRIPTION) public class EconomyLite { @@ -75,7 +79,8 @@ public class EconomyLite { @Inject private PluginContainer container; - private static FileManager fileManager; + private static ConfigManager currencyManager; + private static ConfigManager configManager; private static MessageStorage messageStorage; private static EconomyLite instance; @@ -94,16 +99,12 @@ public void onServerInitialize(GamePreInitializationEvent event) { logger.info("EconomyLite " + PluginInfo.VERSION + " is initializing!"); instance = this; // File setup - if (new File(configDir.toString()).isAbsolute()) { - fileManager = FileManager.createInstance(this, configDir.toString()); - } else { - fileManager = FileManager.createInstance(this, "./" + configDir.toString()); - } + configManager = ConfigManager.create(configDir, "config.conf", logger); + currencyManager = ConfigManager.create(configDir, "currencies.conf", logger); initializeFiles(); initializeCurrencies(); // Load Message Storage - messageStorage = MessageStorage.createInstance(this, configDir.toString()); - initializeMessage(); + messageStorage = MessageStorage.create(configDir, "messages", logger); // Load modules List postInitModules = new ArrayList<>(); getModules().forEach(m -> { @@ -160,56 +161,46 @@ public void onServerInitialize(GamePreInitializationEvent event) { } private void initializeFiles() { - fileManager.setDefault("config.conf", "default-balance", Double.class, 0.0); - fileManager.setDefault("config.conf", "virt-default-balance", Double.class, 0.0); - fileManager.setDefault("config.conf", "debug-logging", Boolean.class, true); - fileManager.setDefault("config.conf", "notify-on-admin-commands", Boolean.class, false); - fileManager.setDefault("config.conf", "confirm-offline-payments", Boolean.class, false); - } - - public static boolean isEnabled(String path) { - if (fileManager.getValue("config.conf", path, Boolean.class).isPresent()) { - return fileManager.getValue("config.conf", path, Boolean.class).get(); - } else { - getInstance().getLogger().error("An error has occurred loading config value " + path + "! Defaulting to false."); - return false; - } + configManager.setDefault("Default balance of player accounts.", Double.class, 0.0, "default-balance", "player"); + configManager.setDefault("Default balance of virtual accounts.", Double.class, 0.0, "default-balance", "virtual"); + configManager.setDefault("Enables or disables debug logging.", Boolean.class, true, "debug-logging"); + configManager.setDefault("If enabled players will be notified when an admin changes their balance", Boolean.class, false, + "notify-on-admin-commands"); + configManager.setDefault("If enabled players will be asked to confirm payments to an offline player.", Boolean.class, true, + "confirm-offline-payments"); + configManager.save(); } private void initializeCurrencies() { // Initialize the default currency into file - fileManager.setDefault("currencies.conf", "current", String.class, "coin"); - fileManager.setDefault("currencies.conf", "coin.singular", String.class, "Coin"); - fileManager.setDefault("currencies.conf", "coin.plural", String.class, "Coins"); - fileManager.setDefault("currencies.conf", "coin.symbol", String.class, "C"); + currencyManager.setDefault(String.class, "current", "coin"); + currencyManager.setDefault(String.class, "Coin", "coin", "singular"); + currencyManager.setDefault(String.class, "Coins", "coin", "plural"); + currencyManager.setDefault(String.class, "C", "coin", "symbol"); Currency defaultCurrency = - new LiteCurrency(fileManager.getValue("currencies.conf", "coin.singular", String.class).get(), fileManager.getValue( - "currencies.conf", "coin.plural", String.class).get(), fileManager.getValue("currencies.conf", "coin.symbol", String.class) - .get(), true, 2); + new LiteCurrency(currencyManager.getValue("", String.class, "coin", "singular"), + currencyManager.getValue("", String.class, "coin", "plural"), currencyManager.getValue("", String.class, "coin", "symbol"), + true, 2); currencyEconService = new CurrencyService(defaultCurrency); // Load all of the currencies - Optional fOpt = fileManager.getFile("currencies.conf"); - if (fOpt.isPresent()) { - ConfigurationNode root = fOpt.get(); - for (Object raw : root.getChildrenMap().keySet()) { - if (raw instanceof String) { - String currencyId = (String) raw; - Optional sOpt = fileManager.getValue("currencies.conf", currencyId + ".singular", String.class); - Optional pOpt = fileManager.getValue("currencies.conf", currencyId + ".plural", String.class); - Optional syOpt = fileManager.getValue("currencies.conf", currencyId + ".symbol", String.class); - if (sOpt.isPresent() && pOpt.isPresent() && syOpt.isPresent() && !currencyId.equals("coin")) { - Currency currency = new LiteCurrency(sOpt.get(), pOpt.get(), syOpt.get(), false, 2); - currencyEconService.addCurrency(currency); - } + CommentedConfigurationNode root = currencyManager.getNode(); + for (Object raw : root.getChildrenMap().keySet()) { + if (raw instanceof String) { + String currencyId = (String) raw; + String singular = currencyManager.getValue("", String.class, currencyId, "singular"); + String plural = currencyManager.getValue("", String.class, currencyId, "plural"); + String symbol = currencyManager.getValue("", String.class, currencyId, "symbol"); + if (!singular.isEmpty() && !plural.isEmpty() && !symbol.isEmpty() && !currencyId.equals("coin")) { + Currency currency = new LiteCurrency(singular, plural, symbol, false, 2); + currencyEconService.addCurrency(currency); } } } // Attempt to load the current currency - Optional cOpt = fileManager.getValue("currencies.conf", "current", String.class); - if (cOpt.isPresent()) { - String currentCur = cOpt.get(); + String current = currencyManager.getValue("", String.class, "current"); + if (!current.isEmpty()) { currencyEconService.getCurrencies().forEach(c -> { - if (("economylite:" + currentCur).equalsIgnoreCase(c.getId())) { + if (("economylite:" + current).equalsIgnoreCase(c.getId())) { // This is the current currency currencyEconService.setCurrentCurrency(c); } @@ -217,15 +208,12 @@ private void initializeCurrencies() { } // If the current currency string failed to load set it to default if (currencyEconService.getCurrentCurrency().equals(defaultCurrency)) { - fileManager.setValue("currencies.conf", "current", String.class, "coin"); + currencyManager.forceValue("coin", "current"); + currencyManager.save(); } logger.info("Using currency: " + currencyEconService.getCurrentCurrency().getName()); } - private void initializeMessage() { - messageStorage.defaultMessages("messages"); - } - public Logger getLogger() { return logger; } @@ -234,12 +222,20 @@ public Game getGame() { return game; } + public Path getConfigDir() { + return configDir; + } + public PluginContainer getPluginContainer() { return container; } - public static FileManager getFileManager() { - return fileManager; + public static ConfigManager getCurrencyManager() { + return currencyManager; + } + + public static ConfigManager getConfigManager() { + return configManager; } public static MessageStorage getMessageStorage() { @@ -270,10 +266,6 @@ public static List getModules() { return ImmutableList.of(new SqlModule(), new LoanModule()); } - public String getConfigDir() { - return configDir.toString(); - } - public String getMainDir() { return mainDir.toString(); } diff --git a/src/main/java/io/github/flibio/economylite/api/PlayerEconService.java b/src/main/java/io/github/flibio/economylite/api/PlayerEconService.java index e3d64fb..c974174 100644 --- a/src/main/java/io/github/flibio/economylite/api/PlayerEconService.java +++ b/src/main/java/io/github/flibio/economylite/api/PlayerEconService.java @@ -19,7 +19,7 @@ public interface PlayerEconService { /** * Gets the balance of a player. - * + * * @param uuid The UUID of the player to get the balance of. * @param currency The currency to use. * @param cause What is getting the balance. @@ -29,7 +29,7 @@ public interface PlayerEconService { /** * Sets the balance of a player. - * + * * @param uuid The UUID of the player to set the balance of. * @param balance The new balance of the uuid. * @param currency The currency to use. @@ -40,7 +40,7 @@ public interface PlayerEconService { /** * Removes currency from a player's balance. - * + * * @param uuid The UUID of the player to remove currency from. * @param amount The amount of currency to remove. * @param currency The currency to use. @@ -53,7 +53,7 @@ default public boolean withdraw(UUID uuid, BigDecimal amount, Currency currency, /** * Adds currency to a player's balance. - * + * * @param uuid The UUID of the player to add currency to. * @param amount The amount of currency to add. * @param currency The currency to use. @@ -64,18 +64,9 @@ default public boolean deposit(UUID uuid, BigDecimal amount, Currency currency, return setBalance(uuid, getBalance(uuid, currency, cause).add(amount), currency, cause); } - /** - * Checks if a player exists in the system with any currency. - * - * @param uuid The UUID of the player to check for. - * @param cause What is checking if the account exists. - * @return If the player exists or not. - */ - public boolean accountExists(UUID uuid, Cause cause); - /** * Checks if a player exists in the system for the specified currency. - * + * * @param uuid The UUID of the player to check for. * @param currency The currency to check against. * @param cause What is checking if the account exists. @@ -85,7 +76,7 @@ default public boolean deposit(UUID uuid, BigDecimal amount, Currency currency, /** * Clears a currency from the database. - * + * * @param currency The currency to clear. * @param cause What is clearing the balances. */ @@ -93,7 +84,7 @@ default public boolean deposit(UUID uuid, BigDecimal amount, Currency currency, /** * Gets the top unique accounts registered in the EconomyLite system. - * + * * @param start The starting account to get. * @param end The ending account to get. * @param cause What is getting the accounts. @@ -103,7 +94,7 @@ default public boolean deposit(UUID uuid, BigDecimal amount, Currency currency, /** * Sets the balance of all players. - * + * * @param balance The new balance. * @param currency The currency to use. * @param cause What caused the balance change. diff --git a/src/main/java/io/github/flibio/economylite/api/VirtualEconService.java b/src/main/java/io/github/flibio/economylite/api/VirtualEconService.java index 9bcb08f..a3b4676 100644 --- a/src/main/java/io/github/flibio/economylite/api/VirtualEconService.java +++ b/src/main/java/io/github/flibio/economylite/api/VirtualEconService.java @@ -63,15 +63,6 @@ default public boolean deposit(String id, BigDecimal amount, Currency currency, return setBalance(id, getBalance(id, currency, cause).add(amount), currency, cause); } - /** - * Checks if an account exists in the system. - * - * @param id The name of the account to check for. - * @param cause What is checking if the account exists. - * @return If the account exists or not. - */ - public boolean accountExists(String id, Cause cause); - /** * Checks if an account exists in the system for the specified currency. * diff --git a/src/main/java/io/github/flibio/economylite/commands/MigrateCommand.java b/src/main/java/io/github/flibio/economylite/commands/MigrateCommand.java index dc6624c..5a1fb2d 100644 --- a/src/main/java/io/github/flibio/economylite/commands/MigrateCommand.java +++ b/src/main/java/io/github/flibio/economylite/commands/MigrateCommand.java @@ -22,11 +22,14 @@ import org.spongepowered.api.command.args.GenericArguments; import org.spongepowered.api.command.spec.CommandSpec; import org.spongepowered.api.command.spec.CommandSpec.Builder; +import org.spongepowered.api.service.economy.Currency; import org.spongepowered.api.text.Text; import java.io.File; import java.io.FileNotFoundException; import java.math.BigDecimal; +import java.util.HashMap; +import java.util.Map; import java.util.UUID; @AsyncCommand @@ -105,10 +108,17 @@ public void run(CommandSource src, CommandContext args) { PlayerServiceCommon sqlService = (PlayerServiceCommon) s; // Load the data service PlayerDataService dataService = new PlayerDataService(); + // Get Currency Data + Map cIds = new HashMap<>(); + EconomyLite.getCurrencyService().getCurrencies().forEach(c -> { + cIds.put(c.getId(), c); + }); // Insert new data dataService.getAccountsMigration().forEach(r -> { String[] d = r.split("%-%"); - sqlService.setRawData(d[0], d[1], d[2]); + if (cIds.get(d[2]) != null) { + sqlService.setRawData(d[0], d[1], cIds.get(d[2])); + } }); src.sendMessage(messageStorage.getMessage("command.migrate.completed")); } catch (Exception e) { diff --git a/src/main/java/io/github/flibio/economylite/commands/PayCommand.java b/src/main/java/io/github/flibio/economylite/commands/PayCommand.java index a0dfd33..2fab34f 100644 --- a/src/main/java/io/github/flibio/economylite/commands/PayCommand.java +++ b/src/main/java/io/github/flibio/economylite/commands/PayCommand.java @@ -10,6 +10,7 @@ import io.github.flibio.utils.commands.BaseCommandExecutor; import io.github.flibio.utils.commands.Command; import io.github.flibio.utils.message.MessageStorage; +import org.spongepowered.api.Sponge; import org.spongepowered.api.command.args.CommandContext; import org.spongepowered.api.command.args.GenericArguments; import org.spongepowered.api.command.spec.CommandSpec; @@ -49,7 +50,7 @@ public void run(Player src, CommandContext args) { src.sendMessage(messageStorage.getMessage("command.pay.invalid")); } else { User target = args.getOne("player").get(); - if (!EconomyLite.isEnabled("confirm-offline-payments") || target.isOnline()) { + if (!EconomyLite.getConfigManager().getValue(Boolean.class, false, "confirm-offline-payments") || target.isOnline()) { // Complete the payment pay(target, amount, src); } else { @@ -75,19 +76,20 @@ private void pay(User target, BigDecimal amount, Player src) { Optional tOpt = ecoService.getOrCreateAccount(target.getUniqueId()); if (uOpt.isPresent() && tOpt.isPresent()) { if (uOpt.get() - .transfer(tOpt.get(), ecoService.getDefaultCurrency(), amount, Cause.of(EventContext.empty(),(EconomyLite.getInstance()))) + .transfer(tOpt.get(), ecoService.getDefaultCurrency(), amount, Cause.of(EventContext.empty(), (EconomyLite.getInstance()))) .getResult().equals(ResultType.SUCCESS)) { Text label = ecoService.getDefaultCurrency().getPluralDisplayName(); if (amount.equals(BigDecimal.ONE)) { label = ecoService.getDefaultCurrency().getDisplayName(); } - src.sendMessage(messageStorage.getMessage("command.pay.success", "target", Text.of(targetName), "amountandlabel", - Text.of(String.format(Locale.ENGLISH, "%,.2f", amount) + " ").toBuilder().append(label).build())); - if (target instanceof Player) { - ((Player) target).sendMessage(messageStorage.getMessage("command.pay.target", "amountandlabel", - Text.of(String.format(Locale.ENGLISH, "%,.2f", amount) + " ").toBuilder().append(label).build(), "sender", - uOpt.get().getDisplayName())); - } + src.sendMessage(messageStorage.getMessage("command.pay.success", "target", targetName, "amountandlabel", + String.format(Locale.ENGLISH, "%,.2f", amount) + " " + label.toPlain())); + final Text curLabel = label; + Sponge.getServer().getPlayer(target.getUniqueId()).ifPresent(p -> { + p.sendMessage(messageStorage.getMessage("command.pay.target", "amountandlabel", + String.format(Locale.ENGLISH, "%,.2f", amount) + " " + curLabel.toPlain(), "sender", + uOpt.get().getDisplayName().toPlain())); + }); } else { src.sendMessage(messageStorage.getMessage("command.pay.failed", "target", targetName)); } diff --git a/src/main/java/io/github/flibio/economylite/commands/balance/BalTopCommand.java b/src/main/java/io/github/flibio/economylite/commands/balance/BalTopCommand.java index 15c82a3..37dcaca 100644 --- a/src/main/java/io/github/flibio/economylite/commands/balance/BalTopCommand.java +++ b/src/main/java/io/github/flibio/economylite/commands/balance/BalTopCommand.java @@ -82,9 +82,8 @@ public void run(CommandSource src, CommandContext args) { label = current.getDisplayName(); } src.sendMessage(messages.getMessage( - "command.baltop.data", - ImmutableMap.of("position", Text.of(count), "name", Text.of(e.getKey()), "balance", - Text.of(String.format(Locale.ENGLISH, "%,.2f", e.getValue())), "label", label))); + "command.baltop.data", "position", Integer.toString(count), "name", e.getKey(), "balance", + String.format(Locale.ENGLISH, "%,.2f", e.getValue()), "label", label.toPlain())); count++; }); Text toSend = Text.of(); @@ -103,8 +102,9 @@ public void run(CommandSource src, CommandContext args) { .onClick(TextActions.runCommand("/baltop " + (pageNumber + 1))) .onHover(TextActions.showText(Text.of(TextColors.GREEN, "NEXT"))).build()).build(); } - if (!toSend.toPlain().isEmpty()) + if (!toSend.toPlain().isEmpty()) { src.sendMessage(toSend); + } count = 0; } } diff --git a/src/main/java/io/github/flibio/economylite/commands/balance/BalanceCommand.java b/src/main/java/io/github/flibio/economylite/commands/balance/BalanceCommand.java index 03116b6..1d043e2 100644 --- a/src/main/java/io/github/flibio/economylite/commands/balance/BalanceCommand.java +++ b/src/main/java/io/github/flibio/economylite/commands/balance/BalanceCommand.java @@ -3,6 +3,12 @@ */ package io.github.flibio.economylite.commands.balance; +import io.github.flibio.economylite.EconomyLite; +import io.github.flibio.economylite.api.CurrencyEconService; +import io.github.flibio.utils.commands.AsyncCommand; +import io.github.flibio.utils.commands.BaseCommandExecutor; +import io.github.flibio.utils.commands.Command; +import io.github.flibio.utils.message.MessageStorage; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.args.CommandContext; import org.spongepowered.api.command.args.GenericArguments; @@ -13,13 +19,7 @@ import org.spongepowered.api.service.economy.Currency; import org.spongepowered.api.service.economy.account.UniqueAccount; import org.spongepowered.api.text.Text; -import com.google.common.collect.ImmutableMap; -import io.github.flibio.economylite.EconomyLite; -import io.github.flibio.economylite.api.CurrencyEconService; -import io.github.flibio.utils.commands.AsyncCommand; -import io.github.flibio.utils.commands.BaseCommandExecutor; -import io.github.flibio.utils.commands.Command; -import io.github.flibio.utils.message.MessageStorage; +import org.spongepowered.api.text.serializer.TextSerializers; import java.math.BigDecimal; import java.util.Locale; @@ -53,9 +53,9 @@ public void run(CommandSource src, CommandContext args) { if (bal.equals(BigDecimal.ONE)) { label = currency.getDisplayName(); } - src.sendMessage(messageStorage.getMessage("command.balanceother", - ImmutableMap.of("player", Text.of(targetName), "balance", Text.of(String.format(Locale.ENGLISH, "%,.2f", bal)), "label", - label))); + src.sendMessage(messageStorage + .getMessage("command.balanceother", "player", targetName, "balance", String.format(Locale.ENGLISH, "%,.2f", bal), "label", + TextSerializers.FORMATTING_CODE.serialize(label))); } else { src.sendMessage(messageStorage.getMessage("command.error")); } @@ -73,8 +73,8 @@ public void run(CommandSource src, CommandContext args) { if (bal.equals(BigDecimal.ONE)) { label = currency.getDisplayName(); } - src.sendMessage(messageStorage.getMessage("command.balance", "balance", Text.of(String.format(Locale.ENGLISH, "%,.2f", bal)), - "label", label)); + src.sendMessage(messageStorage.getMessage("command.balance", "balance", String.format(Locale.ENGLISH, "%,.2f", bal), + "label", TextSerializers.FORMATTING_CODE.serialize(label))); } else { src.sendMessage(messageStorage.getMessage("command.error")); } diff --git a/src/main/java/io/github/flibio/economylite/commands/currency/CurrencyCommand.java b/src/main/java/io/github/flibio/economylite/commands/currency/CurrencyCommand.java index 7c2ee86..43ebfe7 100644 --- a/src/main/java/io/github/flibio/economylite/commands/currency/CurrencyCommand.java +++ b/src/main/java/io/github/flibio/economylite/commands/currency/CurrencyCommand.java @@ -29,7 +29,7 @@ public Builder getCommandSpecBuilder() { @Override public void run(CommandSource src, CommandContext args) { src.sendMessage(messageStorage.getMessage("command.currency.current", "currency", EconomyLite.getEconomyService().getDefaultCurrency() - .getDisplayName())); + .getDisplayName().toPlain())); src.sendMessage(messageStorage.getMessage("command.usage", "command", "/currency", "subcommands", "set | create | delete")); } } diff --git a/src/main/java/io/github/flibio/economylite/commands/currency/CurrencyCreateCommand.java b/src/main/java/io/github/flibio/economylite/commands/currency/CurrencyCreateCommand.java index 6245597..3a2b24c 100644 --- a/src/main/java/io/github/flibio/economylite/commands/currency/CurrencyCreateCommand.java +++ b/src/main/java/io/github/flibio/economylite/commands/currency/CurrencyCreateCommand.java @@ -10,6 +10,7 @@ import io.github.flibio.utils.commands.BaseCommandExecutor; import io.github.flibio.utils.commands.Command; import io.github.flibio.utils.commands.ParentCommand; +import io.github.flibio.utils.config.ConfigManager; import io.github.flibio.utils.file.FileManager; import io.github.flibio.utils.message.MessageStorage; import org.spongepowered.api.command.CommandSource; @@ -27,7 +28,7 @@ public class CurrencyCreateCommand extends BaseCommandExecutor { private MessageStorage messageStorage = EconomyLite.getMessageStorage(); private CurrencyEconService currencyService = EconomyLite.getCurrencyService(); - private FileManager configManager = EconomyLite.getFileManager(); + private ConfigManager manager = EconomyLite.getCurrencyManager(); @Override public Builder getCommandSpecBuilder() { @@ -56,9 +57,10 @@ public void run(CommandSource src, CommandContext args) { Currency currency = new LiteCurrency(singular, plural, symbol, false, 2); currencyService.addCurrency(currency); String configId = currency.getId().replaceAll("economylite:", ""); - configManager.setValue("currencies.conf", configId + ".singular", String.class, currency.getDisplayName().toPlain()); - configManager.setValue("currencies.conf", configId + ".plural", String.class, currency.getPluralDisplayName().toPlain()); - configManager.setValue("currencies.conf", configId + ".symbol", String.class, currency.getSymbol().toPlain()); + manager.forceValue(currency.getDisplayName().toPlain(), configId, ".singular"); + manager.forceValue(currency.getPluralDisplayName().toPlain(), configId, ".plural"); + manager.forceValue(currency.getSymbol().toPlain(), configId, ".symbol"); + manager.save(); src.sendMessage(messageStorage.getMessage("command.currency.created", "currency", currency.getDisplayName().toPlain())); } } else { diff --git a/src/main/java/io/github/flibio/economylite/commands/currency/CurrencyDeleteCommand.java b/src/main/java/io/github/flibio/economylite/commands/currency/CurrencyDeleteCommand.java index 7e484e6..08c4d8a 100644 --- a/src/main/java/io/github/flibio/economylite/commands/currency/CurrencyDeleteCommand.java +++ b/src/main/java/io/github/flibio/economylite/commands/currency/CurrencyDeleteCommand.java @@ -51,7 +51,7 @@ public void run(CommandSource src, CommandContext args) { currencyService.setCurrentCurrency(currencyService.getDefaultCurrency()); } currencyService.deleteCurrency(c); - src.sendMessage(messageStorage.getMessage("command.currency.deleted", "currency", c.getDisplayName())); + src.sendMessage(messageStorage.getMessage("command.currency.deleted", "currency", c.getDisplayName().toPlain())); } } } @@ -63,7 +63,7 @@ public void run(CommandSource src, CommandContext args) { currencyService.getCurrencies().forEach(currency -> { if (!currency.equals(currencyService.getDefaultCurrency())) { src.sendMessage(Text.of(currency.getDisplayName()).toBuilder().onClick(TextActions.executeCallback(c -> { - src.sendMessage(messageStorage.getMessage("command.currency.deleteconfirm", "currency", currency.getDisplayName()) + src.sendMessage(messageStorage.getMessage("command.currency.deleteconfirm", "currency", currency.getDisplayName().toPlain()) .toBuilder().onClick( TextActions.executeCallback(c2 -> { if (currencyService.getCurrentCurrency().equals(currency)) { @@ -71,7 +71,7 @@ public void run(CommandSource src, CommandContext args) { } currencyService.deleteCurrency(currency); src.sendMessage(messageStorage.getMessage("command.currency.deleted", "currency", - currency.getDisplayName())); + currency.getDisplayName().toPlain())); })).build()); })).build()); } diff --git a/src/main/java/io/github/flibio/economylite/commands/currency/CurrencySetCommand.java b/src/main/java/io/github/flibio/economylite/commands/currency/CurrencySetCommand.java index ddbe3d0..f4de489 100644 --- a/src/main/java/io/github/flibio/economylite/commands/currency/CurrencySetCommand.java +++ b/src/main/java/io/github/flibio/economylite/commands/currency/CurrencySetCommand.java @@ -44,21 +44,23 @@ public void run(CommandSource src, CommandContext args) { if (c.getDisplayName().toPlain().equalsIgnoreCase(currencyName)) { currencyService.setCurrentCurrency(c); found = true; - src.sendMessage(messageStorage.getMessage("command.currency.changed", "currency", c.getDisplayName())); + src.sendMessage(messageStorage.getMessage("command.currency.changed", "currency", c.getDisplayName().toPlain())); } } if (!found) { src.sendMessage(messageStorage.getMessage("command.currency.invalid")); } } else { - src.sendMessage(messageStorage.getMessage("command.currency.current", "currency", currencyService.getCurrentCurrency().getDisplayName())); + src.sendMessage(messageStorage.getMessage("command.currency.current", "currency", currencyService.getCurrentCurrency().getDisplayName() + .toPlain())); src.sendMessage(messageStorage.getMessage("command.currency.selectnew")); currencyService.getCurrencies().forEach(currency -> { src.sendMessage(Text.of(currency.getDisplayName()).toBuilder().onClick(TextActions.executeCallback(c -> { - src.sendMessage(messageStorage.getMessage("command.currency.confirm", "currency", currency.getDisplayName()).toBuilder() + src.sendMessage(messageStorage.getMessage("command.currency.confirm", "currency", currency.getDisplayName().toPlain()).toBuilder() .onClick(TextActions.executeCallback(c2 -> { currencyService.setCurrentCurrency(currency); - src.sendMessage(messageStorage.getMessage("command.currency.changed", "currency", currency.getDisplayName())); + src.sendMessage( + messageStorage.getMessage("command.currency.changed", "currency", currency.getDisplayName().toPlain())); })).build()); })).build()); }); diff --git a/src/main/java/io/github/flibio/economylite/commands/virtual/PayVirtualCommand.java b/src/main/java/io/github/flibio/economylite/commands/virtual/PayVirtualCommand.java index d6c5ddd..85510d1 100644 --- a/src/main/java/io/github/flibio/economylite/commands/virtual/PayVirtualCommand.java +++ b/src/main/java/io/github/flibio/economylite/commands/virtual/PayVirtualCommand.java @@ -53,11 +53,11 @@ public void run(Player src, CommandContext args) { if (aOpt.isPresent() && uOpt.isPresent()) { Account receiver = aOpt.get(); UniqueAccount payer = uOpt.get(); - if (payer.transfer(receiver, ecoService.getDefaultCurrency(), amount, Cause.of(EventContext.empty(),(EconomyLite.getInstance()))) + if (payer.transfer(receiver, ecoService.getDefaultCurrency(), amount, Cause.of(EventContext.empty(), (EconomyLite.getInstance()))) .getResult().equals(ResultType.SUCCESS)) { - src.sendMessage(messageStorage.getMessage("command.pay.success", "target", receiver.getDisplayName())); + src.sendMessage(messageStorage.getMessage("command.pay.success", "target", receiver.getDisplayName().toPlain())); } else { - src.sendMessage(messageStorage.getMessage("command.pay.failed", "target", receiver.getDisplayName())); + src.sendMessage(messageStorage.getMessage("command.pay.failed", "target", receiver.getDisplayName().toPlain())); } } } diff --git a/src/main/java/io/github/flibio/economylite/commands/virtual/VirtualBalanceCommand.java b/src/main/java/io/github/flibio/economylite/commands/virtual/VirtualBalanceCommand.java index 1eb6664..501bc67 100644 --- a/src/main/java/io/github/flibio/economylite/commands/virtual/VirtualBalanceCommand.java +++ b/src/main/java/io/github/flibio/economylite/commands/virtual/VirtualBalanceCommand.java @@ -50,9 +50,8 @@ public void run(CommandSource src, CommandContext args) { if (bal.equals(BigDecimal.ONE)) { label = currency.getDisplayName(); } - src.sendMessage(messageStorage.getMessage("command.balanceother", - ImmutableMap.of("player", aOpt.get().getDisplayName(), "balance", Text.of(String.format(Locale.ENGLISH, "%,.2f", bal)), - "label", label))); + src.sendMessage(messageStorage.getMessage("command.balanceother", "player", aOpt.get().getDisplayName().toPlain(), "balance", + String.format(Locale.ENGLISH, "%,.2f", bal), "label", label.toPlain())); } else { src.sendMessage(messageStorage.getMessage("command.error")); } diff --git a/src/main/java/io/github/flibio/economylite/commands/virtual/VirtualPayCommand.java b/src/main/java/io/github/flibio/economylite/commands/virtual/VirtualPayCommand.java index b8151b3..a2aaec4 100644 --- a/src/main/java/io/github/flibio/economylite/commands/virtual/VirtualPayCommand.java +++ b/src/main/java/io/github/flibio/economylite/commands/virtual/VirtualPayCommand.java @@ -58,7 +58,7 @@ public void run(CommandSource src, CommandContext args) { if (aOpt.isPresent() && uOpt.isPresent()) { Account payer = aOpt.get(); UniqueAccount receiver = uOpt.get(); - if (payer.transfer(receiver, ecoService.getDefaultCurrency(), amount, Cause.of(EventContext.empty(),EconomyLite.getInstance + if (payer.transfer(receiver, ecoService.getDefaultCurrency(), amount, Cause.of(EventContext.empty(), EconomyLite.getInstance ())) .getResult().equals(ResultType.SUCCESS)) { src.sendMessage(messageStorage.getMessage("command.pay.success", "target", target.getName())); @@ -68,8 +68,8 @@ public void run(CommandSource src, CommandContext args) { label = ecoService.getDefaultCurrency().getDisplayName(); } ((Player) target).sendMessage(messageStorage.getMessage("command.pay.target", "amountandlabel", - Text.of(String.format(Locale.ENGLISH, "%,.2f", amount) + " ").toBuilder().append(label).build(), "sender", - payer.getDisplayName())); + String.format(Locale.ENGLISH, "%,.2f", amount) + " " + label.toPlain(), "sender", + payer.getDisplayName().toPlain())); } } else { src.sendMessage(messageStorage.getMessage("command.pay.failed", "target", target.getName())); diff --git a/src/main/java/io/github/flibio/economylite/commands/virtual/VirtualSetCommand.java b/src/main/java/io/github/flibio/economylite/commands/virtual/VirtualSetCommand.java index f24ec38..1b77431 100644 --- a/src/main/java/io/github/flibio/economylite/commands/virtual/VirtualSetCommand.java +++ b/src/main/java/io/github/flibio/economylite/commands/virtual/VirtualSetCommand.java @@ -47,10 +47,10 @@ public void run(CommandSource src, CommandContext args) { if (aOpt.isPresent()) { Account targetAccount = aOpt.get(); if (targetAccount.setBalance(EconomyLite.getCurrencyService().getCurrentCurrency(), newBal, - Cause.of(EventContext.empty(),(EconomyLite.getInstance()))).getResult().equals(ResultType.SUCCESS)) { - src.sendMessage(messageStorage.getMessage("command.econ.setsuccess", "name", targetAccount.getDisplayName())); + Cause.of(EventContext.empty(), (EconomyLite.getInstance()))).getResult().equals(ResultType.SUCCESS)) { + src.sendMessage(messageStorage.getMessage("command.econ.setsuccess", "name", targetAccount.getDisplayName().toPlain())); } else { - src.sendMessage(messageStorage.getMessage("command.econ.setfail", "name", targetAccount.getDisplayName())); + src.sendMessage(messageStorage.getMessage("command.econ.setfail", "name", targetAccount.getDisplayName().toPlain())); } } else { src.sendMessage(messageStorage.getMessage("command.error")); diff --git a/src/main/java/io/github/flibio/economylite/impl/CurrencyService.java b/src/main/java/io/github/flibio/economylite/impl/CurrencyService.java index b82f32a..0e178e3 100644 --- a/src/main/java/io/github/flibio/economylite/impl/CurrencyService.java +++ b/src/main/java/io/github/flibio/economylite/impl/CurrencyService.java @@ -42,7 +42,8 @@ public Currency getDefaultCurrency() { @Override public void setCurrentCurrency(Currency currency) { this.currentCurrency = currency; - EconomyLite.getFileManager().setValue("currencies.conf", "current", String.class, currency.getId().replaceAll("economylite:", "")); + EconomyLite.getCurrencyManager().forceValue(currency.getId().replaceAll("economylite:", ""), "current"); + EconomyLite.getCurrencyManager().save(); } @Override @@ -56,7 +57,8 @@ public void deleteCurrency(Currency currency) { EconomyLite.getPlayerService().clearCurrency(currency, CauseFactory.create("Currency deletion")); EconomyLite.getVirtualService().clearCurrency(currency, CauseFactory.create("Currency deletion")); currencies.remove(currency); - EconomyLite.getFileManager().deleteValue("currencies.conf", currency.getId().replaceAll("economylite:", "")); + EconomyLite.getCurrencyManager().forceValue(null, currency.getId().replaceAll("economylite:", "")); + EconomyLite.getCurrencyManager().save(); } } } diff --git a/src/main/java/io/github/flibio/economylite/impl/PlayerDataService.java b/src/main/java/io/github/flibio/economylite/impl/PlayerDataService.java index 3c04afe..2d76abe 100644 --- a/src/main/java/io/github/flibio/economylite/impl/PlayerDataService.java +++ b/src/main/java/io/github/flibio/economylite/impl/PlayerDataService.java @@ -11,7 +11,8 @@ public class PlayerDataService extends PlayerServiceCommon { public PlayerDataService() { - super(LocalSqlManager.createInstance(EconomyLite.getInstance(), "data", correctPath(EconomyLite.getInstance().getConfigDir())).get(), true); + super(LocalSqlManager.createInstance(EconomyLite.getInstance(), "data", correctPath(EconomyLite.getInstance().getConfigDir().toString())) + .get(), true); } private static String correctPath(String path) { diff --git a/src/main/java/io/github/flibio/economylite/impl/PlayerServiceCommon.java b/src/main/java/io/github/flibio/economylite/impl/PlayerServiceCommon.java index 4df7b0d..fc0c9aa 100644 --- a/src/main/java/io/github/flibio/economylite/impl/PlayerServiceCommon.java +++ b/src/main/java/io/github/flibio/economylite/impl/PlayerServiceCommon.java @@ -7,12 +7,14 @@ import io.github.flibio.economylite.EconomyLite; import io.github.flibio.economylite.api.PlayerEconService; +import io.github.flibio.utils.sql.CacheManager; import io.github.flibio.utils.sql.SqlManager; import org.slf4j.Logger; import org.spongepowered.api.event.cause.Cause; import org.spongepowered.api.service.economy.Currency; import org.spongepowered.api.service.economy.EconomyService; import org.spongepowered.api.service.economy.account.UniqueAccount; +import org.spongepowered.api.service.economy.account.VirtualAccount; import java.math.BigDecimal; import java.sql.ResultSet; @@ -24,14 +26,24 @@ public class PlayerServiceCommon implements PlayerEconService { private SqlManager manager; - private boolean log = true; + private boolean log; private Logger logger = EconomyLite.getInstance().getLogger(); + private CacheManager balCache; + private CacheManager exCache; + private CacheManager> topCache; + public PlayerServiceCommon(SqlManager manager, boolean h2) { this.manager = manager; - this.log = EconomyLite.isEnabled("debug-logging"); - if (manager.initialTestConnection()) + this.log = EconomyLite.getConfigManager().getValue(Boolean.class, false, "debug-logging"); + if (manager.initialTestConnection()) { manager.executeUpdate("CREATE TABLE IF NOT EXISTS economyliteplayers(uuid VARCHAR(36), balance DECIMAL(11,2), currency VARCHAR(1024))"); + manager.executeUpdate("ALTER TABLE economyliteplayers ADD UNIQUE (uuid)"); + } + // Create caches + balCache = CacheManager.create(logger, 64, 360); + exCache = CacheManager.create(logger, 128, 360); + topCache = CacheManager.create(logger, 16, 30); } public boolean isWorking() { @@ -39,58 +51,76 @@ public boolean isWorking() { } public BigDecimal getBalance(UUID uuid, Currency currency, Cause cause) { + BigDecimal result = balCache.getIfPresent(formId(uuid, currency)); + if (result != null) { + debug("playercommon: {C} Balance of '" + uuid.toString() + "' - " + cause.toString() + " = " + result.toPlainString()); + return result; + } Optional bOpt = manager.queryType("balance", BigDecimal.class, "SELECT balance FROM economyliteplayers WHERE uuid = ? AND currency = ?", uuid.toString(), currency.getId()); - BigDecimal result = (bOpt.isPresent()) ? bOpt.get() : BigDecimal.ZERO; + result = (bOpt.isPresent()) ? bOpt.get() : BigDecimal.ZERO; + balCache.update(formId(uuid, currency), result); + exCache.update(formId(uuid, currency), true); debug("playercommon: Balance of '" + uuid.toString() + "' - " + cause.toString() + " = " + result.toPlainString()); return result; } public boolean setBalance(UUID uuid, BigDecimal balance, Currency currency, Cause cause) { + boolean result; if (accountExists(uuid, currency, cause)) { - boolean result = manager.executeUpdate("UPDATE economyliteplayers SET balance = ? WHERE uuid = ? AND currency = ?", balance.toString(), + result = manager.executeUpdate("UPDATE economyliteplayers SET balance = ? WHERE uuid = ? AND currency = ?", balance.toString(), uuid.toString(), currency.getId()); debug("playercommon: +Account Exists+ Setting balance of '" + uuid.toString() + "' to '" + balance.toPlainString() + "' with '" + currency.getId() + "' - " + cause.toString() + " = " + result); - return result; } else { - boolean result = manager.executeUpdate("INSERT INTO economyliteplayers (`uuid`, `balance`, `currency`) VALUES (?, ?, ?)", + result = manager.executeUpdate("INSERT INTO economyliteplayers (`uuid`, `balance`, `currency`) VALUES (?, ?, ?)", uuid.toString(), balance.toString(), currency.getId()); debug("playercommon: +Account Does Not Exist+ Setting balance of '" + uuid.toString() + "' to '" + balance.toPlainString() + "' with '" + currency.getId() + "' - " + cause.toString() + " = " + result); - return result; } - } - - public boolean accountExists(UUID uuid, Cause cause) { - boolean result = manager.queryExists("SELECT uuid FROM economyliteplayers WHERE uuid = ?", uuid.toString()); - debug("playercommon: '" + uuid.toString() + "' exists - " + cause.toString() + " = " + result); + if (result) { + balCache.update(formId(uuid, currency), balance); + exCache.update(formId(uuid, currency), true); + } return result; } public boolean accountExists(UUID uuid, Currency currency, Cause cause) { - boolean result = - manager.queryExists("SELECT uuid FROM economyliteplayers WHERE uuid = ? AND currency = ?", uuid.toString(), currency.getId()); - debug("playercommon: Checking if '" + uuid.toString() + "' exists with '" + currency.getId() + "' - " + cause.toString() + " = " - + result); + Boolean result = exCache.getIfPresent(formId(uuid, currency)); + if (result != null) { + debug("playercommon: {C} Checking if '" + uuid.toString() + "' exists with '" + currency.getId() + "' - " + cause.toString() + " = " + + result); + return result; + } + result = manager.queryExists("SELECT uuid FROM economyliteplayers WHERE uuid = ? AND currency = ?", uuid.toString(), currency.getId()); + debug("playercommon: Checking if '" + uuid.toString() + "' exists with '" + currency.getId() + "' - " + cause.toString() + " = " + result); + exCache.update(formId(uuid, currency), result); return result; } public void clearCurrency(Currency currency, Cause cause) { boolean result = manager.executeUpdate("DELETE FROM economyliteplayers WHERE currency = ?", currency.getId()); debug("playercommon: Clearing currency '" + currency.getId() + "' - " + cause.toString() + " = " + result); + balCache.clear(); + exCache.clear(); + topCache.clear(); } public List getTopAccounts(int start, int end, Cause cause) { debug("playercommon: Getting top accounts - " + cause.toString()); + String mid = start + "-" + end + ":" + EconomyLite.getEconomyService().getDefaultCurrency().getId(); + List accounts = topCache.getIfPresent(mid); + if (accounts != null) { + return accounts; + } int offset = start - 1; int limit = end - offset; - ArrayList accounts = new ArrayList<>(); + accounts = new ArrayList<>(); List uuids = manager.queryTypeList("uuid", String.class, "SELECT uuid FROM economyliteplayers WHERE currency = ? ORDER BY balance DESC LIMIT ?, ?", - EconomyLite.getEconomyService().getDefaultCurrency().getId(), String.valueOf(offset), String.valueOf(limit)); + EconomyLite.getEconomyService().getDefaultCurrency().getId(), offset, limit); EconomyService ecoService = EconomyLite.getEconomyService(); for (String uuid : uuids) { Optional uOpt = ecoService.getOrCreateAccount(UUID.fromString(uuid)); @@ -98,6 +128,7 @@ public List getTopAccounts(int start, int end, Cause cause) { accounts.add(uOpt.get()); } } + topCache.update(mid, accounts); return accounts; } @@ -105,6 +136,8 @@ public boolean setBalanceAll(BigDecimal balance, Currency currency, Cause cause) boolean result = manager.executeUpdate("UPDATE economyliteplayers SET balance = ? WHERE currency = ?", balance.toString(), currency.getId()); debug("playercommon: +Account Exists+ Setting balance of ALL to '" + balance.toPlainString() + "' with '" + currency.getId() + "' - " + cause.toString() + " = " + result); + topCache.clear(); + balCache.clear(); return result; } @@ -126,11 +159,11 @@ public List getAccountsMigration() { return accounts; } - public void setRawData(String uuid, String bal, String currency) { - if (accountExists(UUID.fromString(uuid), CauseFactory.stringCause("Migration"))) { - manager.executeUpdate("UPDATE economyliteplayers SET balance = ? WHERE uuid = ? AND currency = ?", bal, uuid, currency); + public void setRawData(String uuid, String bal, Currency currency) { + if (accountExists(UUID.fromString(uuid), currency, CauseFactory.stringCause("Migration"))) { + manager.executeUpdate("UPDATE economyliteplayers SET balance = ? WHERE uuid = ? AND currency = ?", bal, uuid, currency.getId()); } else { - manager.executeUpdate("INSERT INTO economyliteplayers (`uuid`, `balance`, `currency`) VALUES (?, ?, ?)", uuid, bal, currency); + manager.executeUpdate("INSERT INTO economyliteplayers (`uuid`, `balance`, `currency`) VALUES (?, ?, ?)", uuid, bal, currency.getId()); } } @@ -139,4 +172,8 @@ private void debug(String message) { logger.debug(message); } } + + private String formId(UUID id, Currency currency) { + return id.toString() + ":" + currency.getId(); + } } diff --git a/src/main/java/io/github/flibio/economylite/impl/VirtualDataService.java b/src/main/java/io/github/flibio/economylite/impl/VirtualDataService.java index 6a1ee11..20b9174 100644 --- a/src/main/java/io/github/flibio/economylite/impl/VirtualDataService.java +++ b/src/main/java/io/github/flibio/economylite/impl/VirtualDataService.java @@ -11,7 +11,8 @@ public class VirtualDataService extends VirtualServiceCommon { public VirtualDataService() { - super(LocalSqlManager.createInstance(EconomyLite.getInstance(), "data", correctPath(EconomyLite.getInstance().getConfigDir())).get(), true); + super(LocalSqlManager.createInstance(EconomyLite.getInstance(), "data", correctPath(EconomyLite.getInstance().getConfigDir().toString())) + .get(), true); } private static String correctPath(String path) { diff --git a/src/main/java/io/github/flibio/economylite/impl/VirtualServiceCommon.java b/src/main/java/io/github/flibio/economylite/impl/VirtualServiceCommon.java index 85fb479..fb743cd 100644 --- a/src/main/java/io/github/flibio/economylite/impl/VirtualServiceCommon.java +++ b/src/main/java/io/github/flibio/economylite/impl/VirtualServiceCommon.java @@ -3,8 +3,11 @@ */ package io.github.flibio.economylite.impl; +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; import io.github.flibio.economylite.EconomyLite; import io.github.flibio.economylite.api.VirtualEconService; +import io.github.flibio.utils.sql.CacheManager; import io.github.flibio.utils.sql.SqlManager; import org.slf4j.Logger; import org.spongepowered.api.event.cause.Cause; @@ -17,16 +20,21 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; +import java.util.concurrent.TimeUnit; public class VirtualServiceCommon implements VirtualEconService { private SqlManager manager; - private boolean log = true; + private boolean log; private Logger logger = EconomyLite.getInstance().getLogger(); + private CacheManager balCache; + private CacheManager exCache; + private CacheManager> topCache; + public VirtualServiceCommon(SqlManager manager, boolean h2) { this.manager = manager; - this.log = EconomyLite.isEnabled("debug-logging"); + this.log = EconomyLite.getConfigManager().getValue(Boolean.class, false, "debug-logging"); if (manager.initialTestConnection()) { manager.executeUpdate("CREATE TABLE IF NOT EXISTS economylitevirts(id VARCHAR(36), balance DECIMAL(11,2), currency VARCHAR(1024))"); if (h2) { @@ -34,7 +42,12 @@ public VirtualServiceCommon(SqlManager manager, boolean h2) { } else { manager.executeUpdate("ALTER TABLE `economylitevirts` CHANGE `id` `id` VARCHAR(1024)"); } + manager.executeUpdate("ALTER TABLE economylitevirts ADD UNIQUE (id)"); } + // Create caches + balCache = CacheManager.create(logger, 64, 360); + exCache = CacheManager.create(logger, 128, 360); + topCache = CacheManager.create(logger, 16, 30); } public boolean isWorking() { @@ -42,57 +55,74 @@ public boolean isWorking() { } public BigDecimal getBalance(String id, Currency currency, Cause cause) { + BigDecimal result = balCache.getIfPresent(formId(id, currency)); + if (result != null) { + debug("virtcommon: {C} Balance of '" + id + "' - " + cause.toString() + " = " + result.toPlainString()); + return result; + } Optional bOpt = manager.queryType("balance", BigDecimal.class, "SELECT balance FROM economylitevirts WHERE id = ? AND currency = ?", id, currency.getId()); - BigDecimal result = (bOpt.isPresent()) ? bOpt.get() : BigDecimal.ZERO; + result = (bOpt.isPresent()) ? bOpt.get() : BigDecimal.ZERO; + balCache.update(formId(id, currency), result); + exCache.update(formId(id, currency), true); debug("virtcommon: Balance of '" + id + "' - " + cause.toString() + " = " + result.toPlainString()); return result; } public boolean setBalance(String id, BigDecimal balance, Currency currency, Cause cause) { + boolean result; if (accountExists(id, currency, cause)) { - boolean result = manager.executeUpdate("UPDATE economylitevirts SET balance = ? WHERE id = ? AND currency = ?", balance.toString(), id, + result = manager.executeUpdate("UPDATE economylitevirts SET balance = ? WHERE id = ? AND currency = ?", balance.toString(), id, currency.getId()); debug("virtcommon: +Account Exists+ Setting balance of '" + id + "' to '" + balance.toPlainString() + "' with '" + currency.getId() + "' - " + cause.toString() + " = " + result); - return result; } else { - boolean result = - manager.executeUpdate("INSERT INTO economylitevirts (`id`, `balance`, `currency`) VALUES (?, ?, ?)", id, balance.toString(), - currency.getId()); + result = manager.executeUpdate("INSERT INTO economylitevirts (`id`, `balance`, `currency`) VALUES (?, ?, ?)", id, balance.toString(), + currency.getId()); debug("virtcommon: +Account Does Not Exist+ Setting balance of '" + id + "' to '" + balance.toPlainString() + "' with '" + currency.getId() + "' - " + cause.toString() + " = " + result); - return result; } - } - - public boolean accountExists(String id, Cause cause) { - boolean result = manager.queryExists("SELECT id FROM economylitevirts WHERE id = ?", id); - debug("virtcommon: '" + id + "' exists - " + cause.toString() + " = " + result); + if (result) { + balCache.update(formId(id, currency), balance); + exCache.update(formId(id, currency), true); + } return result; } public boolean accountExists(String id, Currency currency, Cause cause) { - boolean result = manager.queryExists("SELECT id FROM economylitevirts WHERE id = ? AND currency = ?", id, currency.getId()); - debug("virtcommon: Checking if '" + id + "' exists with '" + currency.getId() + "' - " + cause.toString() + " = " - + result); + Boolean result = exCache.getIfPresent(formId(id, currency)); + if (result != null) { + debug("virtcommon: {C} Checking if '" + id + "' exists with '" + currency.getId() + "' - " + cause.toString() + " = " + result); + return result; + } + result = manager.queryExists("SELECT id FROM economylitevirts WHERE id = ? AND currency = ?", id, currency.getId()); + debug("virtcommon: Checking if '" + id + "' exists with '" + currency.getId() + "' - " + cause.toString() + " = " + result); + exCache.update(formId(id, currency), result); return result; } public void clearCurrency(Currency currency, Cause cause) { boolean result = manager.executeUpdate("DELETE FROM economylitevirts WHERE currency = ?", currency.getId()); debug("virtcommon: Clearing currency '" + currency.getId() + "' - " + cause.toString() + " = " + result); + balCache.clear(); + exCache.clear(); + topCache.clear(); } public List getTopAccounts(int start, int end, Cause cause) { debug("virtcommon: Getting top accounts - " + cause.toString()); + String mid = start + "-" + end + ":" + EconomyLite.getEconomyService().getDefaultCurrency().getId(); + List accounts = topCache.getIfPresent(mid); + if (accounts != null) { + return accounts; + } int offset = start - 1; int limit = end - offset; - ArrayList accounts = new ArrayList<>(); + accounts = new ArrayList<>(); List ids = manager.queryTypeList("id", String.class, "SELECT id FROM economylitevirts WHERE currency = ? ORDER BY balance DESC LIMIT ?, ?", - EconomyLite.getEconomyService().getDefaultCurrency().getId(), String.valueOf(offset), String.valueOf(limit)); + EconomyLite.getEconomyService().getDefaultCurrency().getId(), offset, limit); EconomyService ecoService = EconomyLite.getEconomyService(); for (String id : ids) { Optional vOpt = ecoService.getOrCreateAccount(id); @@ -100,6 +130,7 @@ public List getTopAccounts(int start, int end, Cause cause) { accounts.add((VirtualAccount) vOpt.get()); } } + topCache.update(mid, accounts); return accounts; } @@ -108,4 +139,8 @@ private void debug(String message) { logger.debug(message); } } + + private String formId(String id, Currency currency) { + return id + ":" + currency.getId(); + } } diff --git a/src/main/java/io/github/flibio/economylite/impl/economy/LiteEconomyService.java b/src/main/java/io/github/flibio/economylite/impl/economy/LiteEconomyService.java index 1f797f5..097e6fb 100644 --- a/src/main/java/io/github/flibio/economylite/impl/economy/LiteEconomyService.java +++ b/src/main/java/io/github/flibio/economylite/impl/economy/LiteEconomyService.java @@ -78,12 +78,12 @@ public Currency getDefaultCurrency() { @Override public boolean hasAccount(UUID uuid) { - return playerService.accountExists(uuid, CauseFactory.create("Checking account existance")); + return playerService.accountExists(uuid, getDefaultCurrency(), CauseFactory.create("Checking account existance")); } @Override public boolean hasAccount(String identifier) { - return virtualService.accountExists(identifier, CauseFactory.create("Checking account existance")); + return virtualService.accountExists(identifier, getDefaultCurrency(), CauseFactory.create("Checking account existance")); } } diff --git a/src/main/java/io/github/flibio/economylite/impl/economy/account/LiteUniqueAccount.java b/src/main/java/io/github/flibio/economylite/impl/economy/account/LiteUniqueAccount.java index 103a38c..59713a5 100644 --- a/src/main/java/io/github/flibio/economylite/impl/economy/account/LiteUniqueAccount.java +++ b/src/main/java/io/github/flibio/economylite/impl/economy/account/LiteUniqueAccount.java @@ -61,7 +61,7 @@ public Text getDisplayName() { @Override public BigDecimal getDefaultBalance(Currency currency) { - Optional bOpt = EconomyLite.getFileManager().getValue("config.conf", "default-balance", Double.class); + Optional bOpt = EconomyLite.getConfigManager().getValue(Double.class, "default-balance", "player"); if (bOpt.isPresent()) { return BigDecimal.valueOf(bOpt.get()); } else { diff --git a/src/main/java/io/github/flibio/economylite/impl/economy/account/LiteVirtualAccount.java b/src/main/java/io/github/flibio/economylite/impl/economy/account/LiteVirtualAccount.java index d4b16f3..7289ba4 100644 --- a/src/main/java/io/github/flibio/economylite/impl/economy/account/LiteVirtualAccount.java +++ b/src/main/java/io/github/flibio/economylite/impl/economy/account/LiteVirtualAccount.java @@ -48,7 +48,7 @@ public Text getDisplayName() { @Override public BigDecimal getDefaultBalance(Currency currency) { - Optional bOpt = EconomyLite.getFileManager().getValue("config.conf", "virt-default-balance", Double.class); + Optional bOpt = EconomyLite.getConfigManager().getValue(Double.class, "default-balance", "virtual"); if (bOpt.isPresent()) { return BigDecimal.valueOf(bOpt.get()); } else { diff --git a/src/main/java/io/github/flibio/economylite/modules/loan/LoanListener.java b/src/main/java/io/github/flibio/economylite/modules/loan/LoanListener.java index 58deaf9..44344ec 100644 --- a/src/main/java/io/github/flibio/economylite/modules/loan/LoanListener.java +++ b/src/main/java/io/github/flibio/economylite/modules/loan/LoanListener.java @@ -3,6 +3,7 @@ */ package io.github.flibio.economylite.modules.loan; +import org.spongepowered.api.text.serializer.TextSerializers; import org.spongepowered.api.util.Tristate; import org.spongepowered.api.service.permission.SubjectData; @@ -45,8 +46,9 @@ public void onBalanceChange(EconomyTransactionEvent event) { Optional uOpt = event.getCause().first(UUID.class); Optional sOpt = event.getCause().first(String.class); if (sOpt.isPresent()) { - if (sOpt.get().equalsIgnoreCase("economylite:loan")) + if (sOpt.get().equalsIgnoreCase("economylite:loan")) { return; + } } if (uOpt.isPresent()) { UUID uuid = uOpt.get(); @@ -64,28 +66,29 @@ public void onBalanceChange(EconomyTransactionEvent event) { BigDecimal mis = event.getTransactionResult().getAmount().subtract(bal); double misDouble = mis.doubleValue(); // Notify player of interest rate - player.sendMessage(messages.getMessage("module.loan.interest", "rate", Text.of(intRate))); + player.sendMessage(messages.getMessage("module.loan.interest", "rate", Double.toString(intRate))); // Check how much loan they can take out double maxLoan = (maxLoanBal - loanBalance) / intRate; - if (maxLoan <= 0) + if (maxLoan <= 0) { return; + } if (maxLoan < misDouble) { // Offer the player a smaller loan player.sendMessage(messages.getMessage("module.loan.partial")); player.sendMessage(messages.getMessage("module.loan.ask", "amount", - Text.of(String.format(Locale.ENGLISH, "%,.2f", maxLoan)), "label", getPrefix(maxLoan, cur))); + String.format(Locale.ENGLISH, "%,.2f", maxLoan), "label", getPrefix(maxLoan, cur))); double total = maxLoan * intRate; player.sendMessage(messages.getMessage("module.loan.payment", "amount", - Text.of(String.format(Locale.ENGLISH, "%,.2f", total)), "label", getPrefix(total, cur))); + String.format(Locale.ENGLISH, "%,.2f", total), "label", getPrefix(total, cur))); module.tableLoans.remove(uuid); module.tableLoans.put(uuid, maxLoan); } else { // Ask the player if they want a full loan - player.sendMessage(messages.getMessage("module.loan.ask", "amount", Text.of(String.format(Locale.ENGLISH, "%,.2f", mis)), + player.sendMessage(messages.getMessage("module.loan.ask", "amount", String.format(Locale.ENGLISH, "%,.2f", mis), "label", getPrefix(mis.doubleValue(), cur))); BigDecimal total = mis.multiply(BigDecimal.valueOf(intRate)); player.sendMessage(messages.getMessage("module.loan.payment", "amount", - Text.of(String.format(Locale.ENGLISH, "%,.2f", total)), "label", getPrefix(total.doubleValue(), cur))); + String.format(Locale.ENGLISH, "%,.2f", total), "label", getPrefix(total.doubleValue(), cur))); player.sendMessage(LoanTextUtils.yesOrNo("/loan accept", "/loan deny")); module.tableLoans.remove(uuid); module.tableLoans.put(uuid, mis.doubleValue()); @@ -116,11 +119,11 @@ public void onLoanChange(LoanBalanceChangeEvent event) { } } - private Text getPrefix(double amnt, Currency cur) { + private String getPrefix(double amnt, Currency cur) { Text label = cur.getPluralDisplayName(); if (amnt == 1.0) { label = cur.getDisplayName(); } - return label; + return TextSerializers.FORMATTING_CODE.serialize(label); } } diff --git a/src/main/java/io/github/flibio/economylite/modules/loan/LoanManager.java b/src/main/java/io/github/flibio/economylite/modules/loan/LoanManager.java index 2332bfd..6e8bd70 100644 --- a/src/main/java/io/github/flibio/economylite/modules/loan/LoanManager.java +++ b/src/main/java/io/github/flibio/economylite/modules/loan/LoanManager.java @@ -6,6 +6,7 @@ import io.github.flibio.economylite.CauseFactory; import io.github.flibio.economylite.EconomyLite; import io.github.flibio.economylite.modules.loan.event.LoanBalanceChangeEvent; +import io.github.flibio.utils.config.ConfigManager; import io.github.flibio.utils.file.FileManager; import org.spongepowered.api.Sponge; import org.spongepowered.api.service.economy.Currency; @@ -19,49 +20,53 @@ public class LoanManager { - private FileManager manager = EconomyLite.getFileManager(); + private ConfigManager manager; private EconomyService eco = EconomyLite.getEconomyService(); private LoanModule module; public LoanManager(LoanModule module) { this.module = module; // Initialize the file - manager.getFile("player-loans.data"); + manager = ConfigManager.create(EconomyLite.getInstance().getConfigDir(), "player-loans.data", EconomyLite.getInstance().getLogger()); } /** * Gets the loan balance of a player. - * + * * @param uuid The player to get the balance of. * @return The player's balance, if no error has occurred. */ public Optional getLoanBalance(UUID uuid) { Currency cur = eco.getDefaultCurrency(); - manager.setDefault("player-loans.data", uuid.toString() + "." + cur.getId() + ".balance", Double.class, 0.0); - return manager.getValue("player-loans.data", uuid.toString() + "." + cur.getId() + ".balance", Double.class); + manager.setDefault(Double.class, 0.0, uuid.toString(), cur.getId(), "balance"); + manager.save(); + return manager.getValue(Double.class, uuid.toString(), cur.getId(), "balance"); } /** * Sets the balance of a player. - * + * * @param uuid The player to set the balance of. * @param amount The balance that will be set. * @return If the balance was successfully set. */ public boolean setLoanBalance(UUID uuid, double amount) { // Make sure balance is within parameters - if (amount < 0 || amount > module.getMaxLoan()) + if (amount < 0 || amount > module.getMaxLoan()) { return false; + } // Fire loan balance change event Sponge.getEventManager().post(new LoanBalanceChangeEvent(amount, uuid)); Currency cur = eco.getDefaultCurrency(); - return manager.setValue("player-loans.data", uuid.toString() + "." + cur.getId() + ".balance", Double.class, amount); + manager.forceValue(amount, uuid.toString(), cur.getId(), "balance"); + manager.save(); + return true; } /** * Adds currency to a player's loan balance. Automatically charges interest * and adds to the player's account. - * + * * @param uuid The player. * @param amount The amount to add. * @return If the amount was added successfully. @@ -72,8 +77,9 @@ public boolean addLoanBalance(UUID uuid, double amount) { Optional uOpt = eco.getOrCreateAccount(uuid); if (bOpt.isPresent() && uOpt.isPresent()) { double bal = bOpt.get(); - if (amount < 0 || bal + (amount * module.getInterestRate()) > module.getMaxLoan()) + if (amount < 0 || bal + (amount * module.getInterestRate()) > module.getMaxLoan()) { return false; + } return (setLoanBalance(uuid, (amount * module.getInterestRate()) + bal) && uOpt.get() .deposit(cur, BigDecimal.valueOf(amount), CauseFactory.stringCause("loan")).getResult().equals(ResultType.SUCCESS)); } @@ -83,7 +89,7 @@ public boolean addLoanBalance(UUID uuid, double amount) { /** * Removes loan balance from a player. Automatically removes funds from the * player's account. - * + * * @param uuid The player. * @param amount The amount to remove. * @return If the amount was removed successfully. @@ -94,8 +100,9 @@ public boolean removeLoanBalance(UUID uuid, double amount) { Optional uOpt = eco.getOrCreateAccount(uuid); if (bOpt.isPresent() && uOpt.isPresent()) { double bal = bOpt.get(); - if (bal - amount < 0 || amount < 0) + if (bal - amount < 0 || amount < 0) { return false; + } return (uOpt.get().withdraw(cur, BigDecimal.valueOf(amount), CauseFactory.stringCause("loan")).getResult() .equals(ResultType.SUCCESS) && setLoanBalance(uuid, bal - amount)); } diff --git a/src/main/java/io/github/flibio/economylite/modules/loan/LoanModule.java b/src/main/java/io/github/flibio/economylite/modules/loan/LoanModule.java index cf51668..adc66ef 100644 --- a/src/main/java/io/github/flibio/economylite/modules/loan/LoanModule.java +++ b/src/main/java/io/github/flibio/economylite/modules/loan/LoanModule.java @@ -13,9 +13,11 @@ import io.github.flibio.economylite.modules.loan.command.LoanPayCommand; import io.github.flibio.economylite.modules.loan.command.LoanTakeCommand; import io.github.flibio.utils.commands.CommandLoader; +import io.github.flibio.utils.config.ConfigManager; import io.github.flibio.utils.file.FileManager; import io.github.flibio.utils.message.MessageStorage; import ninja.leaping.configurate.ConfigurationNode; +import ninja.leaping.configurate.commented.CommentedConfigurationNode; import org.slf4j.Logger; import org.spongepowered.api.Sponge; import org.spongepowered.api.text.serializer.TextSerializers; @@ -28,7 +30,7 @@ public class LoanModule implements Module { private MessageStorage messages = EconomyLite.getMessageStorage(); - private FileManager configManager = EconomyLite.getFileManager(); + private ConfigManager configManager = EconomyLite.getConfigManager(); private LoanManager loanManager; private double interestRate = 1.0; private double maxLoan = 1000.0; @@ -37,8 +39,8 @@ public class LoanModule implements Module { @Override public boolean initialize(Logger logger, Object plugin) { - Optional iOpt = configManager.getValue("config.conf", "modules.loan.interest-rate", Double.class); - Optional mOpt = configManager.getValue("config.conf", "modules.loan.max-loan-balance", Double.class); + Optional iOpt = configManager.getValue(Double.class, "modules", "loan", "interest-rate"); + Optional mOpt = configManager.getValue(Double.class, "modules", "loan", "max-loan-balance"); if (iOpt.isPresent() && mOpt.isPresent()) { interestRate = iOpt.get(); maxLoan = mOpt.get(); @@ -72,23 +74,20 @@ public void postInitialization(Logger logger, Object plugin) { new LoanTakeCommand(this), new LoanAcceptCommand(this), new LoanDenyCommand(this) - ); + ); } @Override public void initializeConfig() { - configManager.setDefault("config.conf", "modules.loan.enabled", Boolean.class, false); - configManager.setDefault("config.conf", "modules.loan.interest-rate", Double.class, 1.0); - configManager.setDefault("config.conf", "modules.loan.max-loan-balance", Double.class, 1000.0); - - Optional cOpt = configManager.getFile("config.conf"); - if (cOpt.isPresent()) { - ConfigurationNode con = cOpt.get(); - Map defaultPerms = ImmutableMap.of("reward.permission", true); - if (con.getNode("modules").getNode("loan").getNode("debtor-perms").isVirtual()) { - con.getNode("modules").getNode("loan").getNode("debtor-perms").setValue(defaultPerms); - configManager.saveFile("config.conf", con); - } + configManager.setDefault(Boolean.class, false, "modules", "loan", "enabled"); + configManager.setDefault(Double.class, 1.0, "modules", "loan", "interest-rate"); + configManager.setDefault(Double.class, 1000.0, "modules", "loan", "max-loan-balance"); + + CommentedConfigurationNode con = configManager.getNode(); + Map defaultPerms = ImmutableMap.of("reward.permission", true); + if (con.getNode("modules").getNode("loan").getNode("debtor-perms").isVirtual()) { + con.getNode("modules").getNode("loan").getNode("debtor-perms").setValue(defaultPerms); + configManager.overwriteNode(con); } } @@ -99,8 +98,7 @@ public String getName() { @Override public boolean isEnabled() { - Optional eOpt = configManager.getValue("config.conf", "modules.loan.enabled", Boolean.class); - return (eOpt.isPresent()) ? eOpt.get() : false; + return configManager.getValue(Boolean.class, false, "modules", "loan", "enabled"); } public LoanManager getLoanManager() { @@ -116,17 +114,14 @@ public double getInterestRate() { } public Map getPermissions() { - Optional cOpt = configManager.getFile("config.conf"); Map perms = new HashMap<>(); - if (cOpt.isPresent()) { - ConfigurationNode con = cOpt.get(); + CommentedConfigurationNode con = configManager.getNode(); - Map map = con.getNode("modules").getNode("loan").getNode("debtor-perms").getChildrenMap(); + Map map = con.getNode("modules").getNode("loan").getNode("debtor-perms").getChildrenMap(); - map.keySet().forEach(perm -> { - perms.put(perm.toString(), map.get(perm).getBoolean()); - }); - } + map.keySet().forEach(perm -> { + perms.put(perm.toString(), map.get(perm).getBoolean()); + }); return perms; } } diff --git a/src/main/java/io/github/flibio/economylite/modules/loan/command/LoanBalanceCommand.java b/src/main/java/io/github/flibio/economylite/modules/loan/command/LoanBalanceCommand.java index cf8d258..90164eb 100644 --- a/src/main/java/io/github/flibio/economylite/modules/loan/command/LoanBalanceCommand.java +++ b/src/main/java/io/github/flibio/economylite/modules/loan/command/LoanBalanceCommand.java @@ -16,6 +16,7 @@ import org.spongepowered.api.command.spec.CommandSpec; import org.spongepowered.api.command.spec.CommandSpec.Builder; import org.spongepowered.api.entity.living.player.Player; +import org.spongepowered.api.text.serializer.TextSerializers; import java.util.Locale; import java.util.Optional; @@ -43,18 +44,18 @@ public void run(Player src, CommandContext args) { Optional bOpt = module.getLoanManager().getLoanBalance(src.getUniqueId()); if (bOpt.isPresent()) { Currency cur = EconomyLite.getEconomyService().getDefaultCurrency(); - src.sendMessage(messages.getMessage("module.loan.balance", "balance", Text.of(String.format(Locale.ENGLISH, "%,.2f", bOpt.get())), + src.sendMessage(messages.getMessage("module.loan.balance", "balance", String.format(Locale.ENGLISH, "%,.2f", bOpt.get()), "label", getPrefix(bOpt.get(), cur))); } else { src.sendMessage(messages.getMessage("command.error")); } } - private Text getPrefix(double amnt, Currency cur) { + private String getPrefix(double amnt, Currency cur) { Text label = cur.getPluralDisplayName(); if (amnt == 1.0) { label = cur.getDisplayName(); } - return label; + return TextSerializers.FORMATTING_CODE.serialize(label); } } diff --git a/src/main/java/io/github/flibio/economylite/modules/loan/command/LoanPayCommand.java b/src/main/java/io/github/flibio/economylite/modules/loan/command/LoanPayCommand.java index fb58938..b988a3c 100644 --- a/src/main/java/io/github/flibio/economylite/modules/loan/command/LoanPayCommand.java +++ b/src/main/java/io/github/flibio/economylite/modules/loan/command/LoanPayCommand.java @@ -18,6 +18,7 @@ import org.spongepowered.api.command.spec.CommandSpec.Builder; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.text.Text; +import org.spongepowered.api.text.serializer.TextSerializers; import java.util.Locale; import java.util.Optional; @@ -55,7 +56,7 @@ public void run(Player src, CommandContext args) { // Pay only what is needed if (module.getLoanManager().removeLoanBalance(uuid, loanBal)) { // Successfully payed loan - src.sendMessage(messages.getMessage("module.loan.payed", "amount", Text.of(String.format(Locale.ENGLISH, "%,.2f", loanBal)), + src.sendMessage(messages.getMessage("module.loan.payed", "amount", String.format(Locale.ENGLISH, "%,.2f", loanBal), "label", getPrefix(loanBal, cur))); } else { // Failed to pay @@ -65,7 +66,7 @@ public void run(Player src, CommandContext args) { // Pay entire request if (module.getLoanManager().removeLoanBalance(uuid, payment)) { // Successfully payed loan - src.sendMessage(messages.getMessage("module.loan.payed", "amount", Text.of(String.format(Locale.ENGLISH, "%,.2f", payment)), + src.sendMessage(messages.getMessage("module.loan.payed", "amount", String.format(Locale.ENGLISH, "%,.2f", payment), "label", getPrefix(payment, cur))); } else { // Failed to pay @@ -78,11 +79,11 @@ public void run(Player src, CommandContext args) { } } - private Text getPrefix(double amnt, Currency cur) { + private String getPrefix(double amnt, Currency cur) { Text label = cur.getPluralDisplayName(); if (amnt == 1.0) { label = cur.getDisplayName(); } - return label; + return TextSerializers.FORMATTING_CODE.serialize(label); } } diff --git a/src/main/java/io/github/flibio/economylite/modules/loan/command/LoanTakeCommand.java b/src/main/java/io/github/flibio/economylite/modules/loan/command/LoanTakeCommand.java index 8ea6183..1b627c4 100644 --- a/src/main/java/io/github/flibio/economylite/modules/loan/command/LoanTakeCommand.java +++ b/src/main/java/io/github/flibio/economylite/modules/loan/command/LoanTakeCommand.java @@ -18,6 +18,7 @@ import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.service.economy.Currency; import org.spongepowered.api.text.Text; +import org.spongepowered.api.text.serializer.TextSerializers; import java.util.Locale; import java.util.Optional; @@ -53,7 +54,7 @@ public void run(Player src, CommandContext args) { if (dOpt.isPresent()) { double loanBalance = dOpt.get(); // Notify player of interest rate - src.sendMessage(messages.getMessage("module.loan.interest", "rate", Text.of(module.getInterestRate()))); + src.sendMessage(messages.getMessage("module.loan.interest", "rate", Double.toString(module.getInterestRate()))); // Check how much loan they can take out double maxLoan = (module.getMaxLoan() - loanBalance) / module.getInterestRate(); if (maxLoan <= 0) { @@ -63,21 +64,20 @@ public void run(Player src, CommandContext args) { if (maxLoan < loanAmount) { // Offer the player a smaller loan src.sendMessage(messages.getMessage("module.loan.partial")); - src.sendMessage(messages.getMessage("module.loan.ask", "amount", - Text.of(String.format(Locale.ENGLISH, "%,.2f", maxLoan)), "label", getPrefix(maxLoan, cur))); + src.sendMessage(messages.getMessage("module.loan.ask", "amount", String.format(Locale.ENGLISH, "%,.2f", maxLoan), "label", + getPrefix(maxLoan, cur))); double total = maxLoan * module.getInterestRate(); - src.sendMessage(messages.getMessage("module.loan.payment", "amount", - Text.of(String.format(Locale.ENGLISH, "%,.2f", total)), "label", getPrefix(total, cur))); + src.sendMessage(messages.getMessage("module.loan.payment", "amount", String.format(Locale.ENGLISH, "%,.2f", total), "label", + getPrefix(total, cur))); module.tableLoans.remove(uuid); module.tableLoans.put(uuid, maxLoan); } else { // Ask the player if they want a full loan - src.sendMessage(messages.getMessage("module.loan.ask", "amount", Text.of(String.format(Locale.ENGLISH, "%,.2f", loanAmount)), + src.sendMessage(messages.getMessage("module.loan.ask", "amount", String.format(Locale.ENGLISH, "%,.2f", loanAmount), "label", getPrefix(loanAmount, cur))); double total = loanAmount * module.getInterestRate(); - src.sendMessage(messages.getMessage("module.loan.payment", "amount", - Text.of(String.format(Locale.ENGLISH, "%,.2f", total)), "label", getPrefix(total, cur))); - + src.sendMessage(messages.getMessage("module.loan.payment", "amount", String.format(Locale.ENGLISH, "%,.2f", total), "label", + getPrefix(total, cur))); src.sendMessage(LoanTextUtils.yesOrNo("/loan accept", "/loan deny")); module.tableLoans.remove(uuid); module.tableLoans.put(uuid, loanAmount); @@ -90,12 +90,12 @@ public void run(Player src, CommandContext args) { } } - private Text getPrefix(double amnt, Currency cur) { + private String getPrefix(double amnt, Currency cur) { Text label = cur.getPluralDisplayName(); if (amnt == 1.0) { label = cur.getDisplayName(); } - return label; + return TextSerializers.FORMATTING_CODE.serialize(label); } } diff --git a/src/main/java/io/github/flibio/economylite/modules/sql/SqlModule.java b/src/main/java/io/github/flibio/economylite/modules/sql/SqlModule.java index e7f1cf8..fc80d74 100644 --- a/src/main/java/io/github/flibio/economylite/modules/sql/SqlModule.java +++ b/src/main/java/io/github/flibio/economylite/modules/sql/SqlModule.java @@ -5,14 +5,14 @@ import io.github.flibio.economylite.EconomyLite; import io.github.flibio.economylite.modules.Module; -import io.github.flibio.utils.file.FileManager; +import io.github.flibio.utils.config.ConfigManager; import org.slf4j.Logger; import java.util.Optional; public class SqlModule implements Module { - private FileManager configManager = EconomyLite.getFileManager(); + private ConfigManager configManager = EconomyLite.getConfigManager(); @Override public boolean initialize(Logger logger, Object plugin) { @@ -34,12 +34,12 @@ public boolean initialize(Logger logger, Object plugin) { @Override public void initializeConfig() { - configManager.setDefault("config.conf", "modules.mysql.enabled", Boolean.class, false); - configManager.setDefault("config.conf", "modules.mysql.hostname", String.class, "hostname"); - configManager.setDefault("config.conf", "modules.mysql.port", String.class, "3306"); - configManager.setDefault("config.conf", "modules.mysql.database", String.class, "database"); - configManager.setDefault("config.conf", "modules.mysql.username", String.class, "username"); - configManager.setDefault("config.conf", "modules.mysql.password", String.class, "password"); + configManager.setDefault(Boolean.class, false, "modules", "mysql", "enabled"); + configManager.setDefault(String.class, "hostname", "modules", "mysql", "hostname"); + configManager.setDefault(String.class, "3306", "modules", "mysql", "port"); + configManager.setDefault(String.class, "database", "modules", "mysql", "database"); + configManager.setDefault(String.class, "username", "modules", "mysql", "username"); + configManager.setDefault(String.class, "password", "modules", "mysql", "password"); } @Override @@ -49,13 +49,11 @@ public String getName() { @Override public boolean isEnabled() { - Optional eOpt = configManager.getValue("config.conf", "modules.mysql.enabled", Boolean.class); - return (eOpt.isPresent()) ? eOpt.get() : false; + return configManager.getValue(Boolean.class, false, "modules", "mysql", "enabled"); } private String getDetail(String name) { - Optional vOpt = configManager.getValue("config.conf", "modules.mysql." + name, String.class); - return (vOpt.isPresent()) ? vOpt.get() : ""; + return configManager.getValue("", String.class, "modules", "mysql", name); } }