From dfd67154ff3cc6a4feff943b2cb8957a92dd6b07 Mon Sep 17 00:00:00 2001 From: "Daniel V." Date: Fri, 27 Sep 2024 23:25:50 -0400 Subject: [PATCH] Reformat code to align with code style. --- .changelog/0.1.2.0.md | 85 +- .changelog/0.1.2.1.md | 9 +- .changelog/0.1.2.2.md | 34 +- .changelog/0.1.2.3.md | 1 + .changelog/0.1.2.4.md | 4 +- .changelog/0.1.2.5.md | 3 +- .changelog/0.1.2.6.md | 82 +- .changelog/0.1.2.7.md | 1 + .changelog/0.1.2.8.md | 12 +- .changelog/0.1.2.9.md | 6 +- .changelog/0.1.3.0.md | 35 +- .changelog/0.1.3.1.md | 9 +- .changelog/0.1.3.2.md | 27 +- .github/ISSUE_TEMPLATE/report-a-bug.yml | 2 +- .github/ISSUE_TEMPLATE/request-a-feature.yml | 2 +- .github/workflows/codesee-arch-diagram.yml | 2 +- .github/workflows/maven.yml | 32 +- Bug Report.md | 18 +- Bukkit/pom.xml | 9 +- Bukkit/src/net/tnemc/bukkit/BukkitConfig.java | 7 +- Bukkit/src/net/tnemc/bukkit/BukkitCore.java | 10 + Bukkit/src/net/tnemc/bukkit/BukkitPlugin.java | 15 +- .../tnemc/bukkit/ModifiedBukkitLogger.java | 5 + .../bukkit/ModifiedBukkitPluginCore.java | 2 + Bukkit/src/net/tnemc/bukkit/TNE.java | 4 + .../tnemc/bukkit/command/AdminCommand.java | 69 +- .../tnemc/bukkit/command/ModuleCommand.java | 22 +- .../tnemc/bukkit/command/MoneyCommand.java | 60 +- .../tnemc/bukkit/command/ShortCommands.java | 21 +- .../bukkit/command/TransactionCommand.java | 20 +- .../bukkit/depend/faction/FactionAccount.java | 2 + .../bukkit/depend/faction/FactionCheck.java | 7 +- .../bukkit/depend/faction/FactionHandler.java | 1 + .../bukkit/depend/towny/NationAccount.java | 2 + .../bukkit/depend/towny/NationCheck.java | 8 +- .../bukkit/depend/towny/TownAccount.java | 3 + .../tnemc/bukkit/depend/towny/TownCheck.java | 7 +- .../bukkit/depend/towny/TownyHandler.java | 1 + .../tnemc/bukkit/hook/economy/TNEVault.java | 177 ++-- .../bukkit/hook/economy/TNEVaultUnlocked.java | 95 +- .../tnemc/bukkit/hook/economy/VaultHook.java | 4 +- .../hook/economy/VaultUnlockedHook.java | 4 +- .../net/tnemc/bukkit/hook/misc/PAPIHook.java | 12 +- .../mcmmo/PlayerFishingTreasureListener.java | 3 +- .../player/PlayerInteractListener.java | 3 +- .../listeners/player/PlayerJoinListener.java | 3 +- .../listeners/player/PlayerQuitListener.java | 1 + .../server/MessageChannelListener.java | 2 + .../server/PluginEnableListener.java | 1 + .../listeners/world/WorldLoadListener.java | 1 + BukkitEarly/pom.xml | 9 +- .../src/paper/PaperServerProvider.java | 1 + BukkitEarly/src/paper/TNE.java | 3 + Bungee/pom.xml | 5 +- Bungee/src/net/tnemc/bungee/BungeeCore.java | 4 + Bungee/src/net/tnemc/bungee/BungeeProxy.java | 3 + .../src/net/tnemc/bungee/ProxyProvider.java | 9 +- .../tnemc/bungee/event/MessageListener.java | 1 + .../tnemc/bungee/message/MessageHandler.java | 6 + .../tnemc/bungee/message/MessageManager.java | 6 + .../bungee/message/backlog/ConfigEntry.java | 6 + .../bungee/message/backlog/MessageData.java | 3 + .../message/handlers/AccountHandler.java | 3 +- .../handlers/BalanceMessageHandler.java | 5 +- .../handlers/ConfigMessageHandler.java | 3 + .../handlers/MessageMessageHandler.java | 5 +- .../handlers/SyncAllMessageHandler.java | 2 + Core/pom.xml | 8 +- Core/resources/config.yml | 10 +- Core/resources/messages.yml | 2 +- Core/resources/structure.sql | 344 ++++++-- Core/src/net/tnemc/core/EconomyManager.java | 27 +- Core/src/net/tnemc/core/TNECore.java | 59 +- .../net/tnemc/core/TNEStorageProvider.java | 18 +- Core/src/net/tnemc/core/account/Account.java | 78 +- .../net/tnemc/core/account/AccountStatus.java | 11 +- .../tnemc/core/account/AccountTypeCheck.java | 4 +- .../net/tnemc/core/account/GeyserAccount.java | 2 + .../tnemc/core/account/NonPlayerAccount.java | 5 +- .../net/tnemc/core/account/PlayerAccount.java | 17 +- .../net/tnemc/core/account/SharedAccount.java | 40 +- .../account/holdings/CurrencyHoldings.java | 8 +- .../core/account/holdings/HoldingsEntry.java | 21 +- .../account/holdings/HoldingsHandler.java | 30 +- .../core/account/holdings/RegionHoldings.java | 30 +- .../tnemc/core/account/holdings/Wallet.java | 72 +- .../holdings/handlers/EnderChestHandler.java | 21 +- .../holdings/handlers/ExperienceHandler.java | 15 +- .../handlers/ExperienceLevelHandler.java | 25 +- .../holdings/handlers/InventoryHandler.java | 22 +- .../holdings/handlers/VirtualHandler.java | 14 +- .../holdings/modify/HoldingsModifier.java | 76 +- .../holdings/modify/HoldingsOperation.java | 7 + .../net/tnemc/core/account/shared/Member.java | 33 +- .../account/shared/MemberPermissions.java | 26 +- .../tnemc/core/account/shared/Permission.java | 7 +- .../account/status/AccountLockedStatus.java | 5 + .../account/status/AccountNormalStatus.java | 5 + .../status/AccountRestrictedStatus.java | 5 + .../net/tnemc/core/actions/ActionSource.java | 15 +- .../tnemc/core/actions/EconomyResponse.java | 7 +- .../actions/response/AccountResponse.java | 18 +- .../core/actions/response/CustomResponse.java | 11 +- .../actions/response/GeneralResponse.java | 12 +- .../actions/response/HoldingsResponse.java | 18 + .../core/actions/source/PlayerSource.java | 9 +- .../core/actions/source/PluginSource.java | 9 +- Core/src/net/tnemc/core/api/TNEAPI.java | 101 ++- .../api/callback/TNECallbackProvider.java | 1 + .../tnemc/core/api/callback/TNECallbacks.java | 2 + .../api/callback/account/AccountCallback.java | 1 + .../account/AccountCreateCallback.java | 3 + .../account/AccountDeleteCallback.java | 1 + .../callback/account/AccountLoadCallback.java | 3 + .../callback/account/AccountSaveCallback.java | 2 + .../account/AccountTypesCallback.java | 3 +- .../currency/CurrencyDropCallback.java | 6 + .../currency/CurrencyLoadCallback.java | 4 + .../currency/DenominationLoadCallback.java | 6 + .../transaction/PostTransactionCallback.java | 5 +- .../transaction/PreTransactionCallback.java | 8 +- .../core/api/response/AccountAPIResponse.java | 6 +- .../tnemc/core/channel/BalanceHandler.java | 2 + .../net/tnemc/core/channel/ConfigHandler.java | 2 + .../net/tnemc/core/channel/CreateHandler.java | 2 + .../tnemc/core/channel/MessageHandler.java | 2 + .../net/tnemc/core/channel/SyncHandler.java | 2 + .../net/tnemc/core/command/AdminCommand.java | 7 + .../net/tnemc/core/command/BaseCommand.java | 4 + .../net/tnemc/core/command/ModuleCommand.java | 2 + .../net/tnemc/core/command/MoneyCommand.java | 92 +- .../core/command/TransactionCommand.java | 24 +- .../command/parameters/PercentBigDecimal.java | 1 + .../parameters/resolver/AccountResolver.java | 1 + .../resolver/BigDecimalResolver.java | 1 + .../parameters/resolver/CurrencyResolver.java | 1 + .../parameters/resolver/DebugResolver.java | 1 + .../resolver/PercentDecimalResolver.java | 1 + .../parameters/resolver/StatusResolver.java | 1 + .../suggestion/AccountSuggestion.java | 1 + .../suggestion/CurrencySuggestion.java | 1 + .../suggestion/DebugSuggestion.java | 1 + .../suggestion/RegionSuggestion.java | 1 + .../suggestion/StatusSuggestion.java | 1 + .../src/net/tnemc/core/config/DataConfig.java | 6 +- .../src/net/tnemc/core/config/MainConfig.java | 7 +- .../net/tnemc/core/config/MessageConfig.java | 15 +- .../src/net/tnemc/core/currency/Currency.java | 64 +- .../tnemc/core/currency/CurrencyLoader.java | 19 +- .../tnemc/core/currency/CurrencyRegion.java | 4 + .../tnemc/core/currency/CurrencySaver.java | 15 +- .../net/tnemc/core/currency/CurrencyType.java | 31 +- .../net/tnemc/core/currency/Denomination.java | 11 +- Core/src/net/tnemc/core/currency/Note.java | 28 +- .../calculations/CalculationData.java | 15 +- .../calculations/ItemCalculations.java | 11 +- .../calculations/MonetaryCalculation.java | 30 +- .../currency/format/CurrencyFormatter.java | 4 + .../core/currency/format/FormatRule.java | 13 +- .../currency/format/impl/DecimalRule.java | 3 + .../currency/format/impl/MajorAmountRule.java | 4 +- .../currency/format/impl/MajorNameRule.java | 6 +- .../core/currency/format/impl/MajorRule.java | 9 +- .../currency/format/impl/MaterialRule.java | 4 + .../currency/format/impl/MinorAmountRule.java | 3 + .../currency/format/impl/MinorNameRule.java | 6 +- .../core/currency/format/impl/MinorRule.java | 9 +- .../currency/format/impl/ShortenJRule.java | 3 + .../currency/format/impl/ShortenRule.java | 4 +- .../core/currency/format/impl/SymbolRule.java | 2 + .../core/currency/item/ItemCurrency.java | 10 +- .../core/currency/item/ItemDenomination.java | 22 +- .../loader/DefaultCurrencyLoader.java | 22 +- .../currency/saver/DefaultCurrencySaver.java | 7 +- .../currency/type/ExperienceLevelType.java | 5 + .../core/currency/type/ExperienceType.java | 5 + .../tnemc/core/currency/type/ItemType.java | 13 +- .../tnemc/core/currency/type/MixedType.java | 11 +- .../tnemc/core/currency/type/VirtualType.java | 6 +- .../entity/EntityDropItemHandler.java | 2 +- .../player/PlayerCloseEChestHandler.java | 7 +- .../player/PlayerInteractHandler.java | 11 +- .../handlers/player/PlayerJoinHandler.java | 19 +- .../handlers/player/PlayerLeaveHandler.java | 3 + .../handlers/region/RegionLoadHandler.java | 1 + .../core/handlers/server/ChannelHandler.java | 1 + .../net/tnemc/core/hook/tnk/CampAccount.java | 3 + .../net/tnemc/core/hook/tnk/CampCheck.java | 8 +- .../tnemc/core/hook/tnk/KingdomAccount.java | 3 + .../net/tnemc/core/hook/tnk/KingdomCheck.java | 8 +- .../net/tnemc/core/hook/tnk/PactAccount.java | 3 + .../net/tnemc/core/hook/tnk/PactCheck.java | 8 +- .../net/tnemc/core/hook/tnk/TNKHandler.java | 1 + .../tnemc/core/hook/tnk/VillageAccount.java | 3 + .../net/tnemc/core/hook/tnk/VillageCheck.java | 7 +- .../net/tnemc/core/io/maps/MultiTreeMap.java | 7 + .../receipt/ReceiptTimeComparator.java | 1 + .../receipt/ReceiptVoidComparator.java | 1 + .../io/message/BaseTranslationProvider.java | 4 +- .../io/serialization/impl/SerialAccount.java | 20 +- .../io/serialization/impl/SerialCurrency.java | 7 +- .../impl/SerialDenomination.java | 27 +- .../io/serialization/impl/SerialHoldings.java | 10 +- .../io/serialization/impl/SerialMember.java | 12 +- .../io/serialization/impl/SerialNote.java | 2 + .../io/serialization/impl/SerialTaxEntry.java | 2 + .../datables/sql/standard/SQLAccount.java | 102 +-- .../datables/sql/standard/SQLHoldings.java | 34 +- .../datables/sql/standard/SQLReceipt.java | 108 +-- .../io/storage/datables/yaml/YAMLAccount.java | 14 +- .../storage/datables/yaml/YAMLHoldings.java | 18 +- .../io/storage/datables/yaml/YAMLReceipt.java | 28 +- .../core/io/storage/dialect/TNEDialect.java | 93 +- .../io/storage/dialect/impl/MariaDialect.java | 218 +++-- .../dialect/impl/MariaOutdatedDialect.java | 218 +++-- .../io/storage/dialect/impl/MySQLDialect.java | 183 ++-- .../core/io/yaml/YamlStorageManager.java | 4 + .../tnemc/core/manager/AccountManager.java | 57 +- .../tnemc/core/manager/CurrencyManager.java | 69 +- .../tnemc/core/manager/ReceiptManager.java | 86 +- .../net/tnemc/core/manager/TopManager.java | 10 + .../core/manager/TransactionManager.java | 30 +- Core/src/net/tnemc/core/manager/Updater.java | 5 + .../tnemc/core/manager/top/TopCurrency.java | 6 +- .../net/tnemc/core/manager/top/TopPage.java | 4 + Core/src/net/tnemc/core/menu/BaltopMenu.java | 23 +- Core/src/net/tnemc/core/menu/MyBalMenu.java | 93 +- Core/src/net/tnemc/core/menu/MyEcoMenu.java | 816 +++++++++--------- .../net/tnemc/core/menu/TransactionMenu.java | 23 +- .../constraints/TNEStringConstraints.java | 2 + .../menu/handlers/AmountSelectionHandler.java | 3 + .../menu/handlers/StringSelectionHandler.java | 3 + .../icons/actions/PageSwitchWithClose.java | 2 + .../core/menu/icons/myeco/CurrencyIcon.java | 6 +- .../menu/icons/myeco/DenominationIcon.java | 5 +- .../menu/icons/myeco/SaveCurrencyIcon.java | 7 +- .../menu/icons/shared/PreviousMenuIcon.java | 1 + .../menu/icons/shared/PreviousPageIcon.java | 1 + .../menu/icons/shared/SwitchMenuIcon.java | 2 + .../menu/icons/shared/SwitchPageIcon.java | 4 + .../page/mybal/MyBalAmountSelectionPage.java | 28 +- .../menu/page/myeco/FormatSelectionPage.java | 121 +-- .../page/shared/AccountSelectionPage.java | 49 +- .../menu/page/shared/AmountSelectionPage.java | 199 ++--- .../page/shared/CurrencySelectionPage.java | 43 +- .../page/shared/EnchantmentSelectionPage.java | 79 +- .../menu/page/shared/FlagSelectionPage.java | 79 +- .../shared/MaterialSelectionPageCallback.java | 49 +- .../menu/page/shared/TransactionInfoPage.java | 163 ++-- .../tnemc/core/menu/page/top/BalTopPage.java | 31 +- .../net/tnemc/core/region/RegionGroup.java | 5 + .../src/net/tnemc/core/region/RegionMode.java | 2 + .../net/tnemc/core/region/RegionProvider.java | 20 +- .../net/tnemc/core/region/mode/BiomeMode.java | 6 +- .../net/tnemc/core/region/mode/WorldMode.java | 6 +- .../net/tnemc/core/transaction/Receipt.java | 30 +- .../tnemc/core/transaction/Transaction.java | 80 +- .../core/transaction/TransactionCheck.java | 23 +- .../transaction/TransactionCheckGroup.java | 8 +- .../transaction/TransactionParticipant.java | 10 +- .../transaction/TransactionProcessor.java | 12 +- .../core/transaction/TransactionResult.java | 13 +- .../core/transaction/TransactionType.java | 9 +- .../check/MaximumBalanceCheck.java | 13 +- .../check/MinimumBalanceCheck.java | 13 +- .../transaction/check/MinimumDenomCheck.java | 12 +- .../check/NegativeBalanceCheck.java | 13 +- .../transaction/check/PreCallbackCheck.java | 11 +- .../core/transaction/check/RegionCheck.java | 11 +- .../check/RestrictedCurrencyCheck.java | 15 +- .../core/transaction/check/StatusCheck.java | 11 +- .../core/transaction/check/TrackingCheck.java | 13 +- .../core/transaction/history/AwayHistory.java | 7 +- .../transaction/history/SortedHistory.java | 6 +- .../processor/BaseTransactionProcessor.java | 4 + .../core/transaction/receipt/ReceiptBox.java | 25 +- .../core/transaction/tax/type/FlatType.java | 6 +- .../transaction/tax/type/PercentileType.java | 6 +- .../core/transaction/type/ConversionType.java | 8 +- .../core/transaction/type/DepositType.java | 86 +- .../tnemc/core/transaction/type/PayType.java | 8 +- .../core/transaction/type/WithdrawType.java | 86 +- Core/src/net/tnemc/core/utils/Extractor.java | 24 +- Core/src/net/tnemc/core/utils/Identifier.java | 2 + Core/src/net/tnemc/core/utils/MISCUtils.java | 18 +- Core/src/net/tnemc/core/utils/Monetary.java | 5 + .../exceptions/InvalidAccountException.java | 6 +- .../exceptions/InvalidStatusException.java | 6 +- .../InvalidTransactionException.java | 8 +- .../NoValidCurrenciesException.java | 6 +- Core/walkthrough.md | 22 +- Folia/pom.xml | 8 +- Folia/src/net/tnemc/folia/FoliaCore.java | 2 + Folia/src/net/tnemc/folia/TNE.java | 3 + .../folia/impl/FoliaInventoryProvider.java | 2 + .../tnemc/folia/impl/FoliaPlayerProvider.java | 18 +- .../tnemc/folia/impl/FoliaServerProvider.java | 82 +- .../folia/impl/scheduler/FoliaChore.java | 2 + .../folia/impl/scheduler/FoliaScheduler.java | 20 +- PaperCore/pom.xml | 9 +- PaperCore/src/net/tnemc/paper/PaperCore.java | 10 + .../tnemc/paper/PaperDebugCalculations.java | 24 +- .../src/net/tnemc/paper/PaperPlugin.java | 16 +- PaperCore/src/net/tnemc/paper/TNE.java | 3 + .../net/tnemc/paper/command/AdminCommand.java | 69 +- .../tnemc/paper/command/ModuleCommand.java | 22 +- .../net/tnemc/paper/command/MoneyCommand.java | 59 +- .../tnemc/paper/command/ShortCommands.java | 21 +- .../paper/command/TransactionCommand.java | 20 +- .../tnemc/paper/hook/economy/TNEVault.java | 177 ++-- .../paper/hook/economy/TNEVaultUnlocked.java | 95 +- .../tnemc/paper/hook/economy/VaultHook.java | 4 +- .../paper/hook/economy/VaultUnlockedHook.java | 4 +- .../net/tnemc/paper/hook/misc/PAPIHook.java | 12 +- .../listener/PlayerInteractListener.java | 3 +- README.md | 51 +- Sponge8/pom.xml | 9 +- Sponge8/src/net/tnemc/sponge/SpongeCore.java | 13 + .../tnemc/sponge/command/AdminCommand.java | 43 +- .../tnemc/sponge/command/ModuleCommand.java | 10 +- .../tnemc/sponge/command/MoneyCommand.java | 56 +- .../tnemc/sponge/command/ShortCommands.java | 21 +- .../sponge/command/TransactionCommand.java | 16 +- .../net/tnemc/sponge/impl/SpongeCurrency.java | 7 + .../sponge/impl/SpongeDeletionResult.java | 2 + .../net/tnemc/sponge/impl/SpongeEconomy.java | 10 + .../net/tnemc/sponge/impl/SpongeReceipt.java | 7 + .../sponge/impl/SpongeTransactionEvent.java | 3 + .../sponge/impl/SpongeTransferReceipt.java | 2 + .../sponge/impl/SpongeUniqueAccount.java | 2 + .../sponge/impl/SpongeVirtualAccount.java | 81 +- .../player/PlayerCloseInventoryListener.java | 4 +- .../listeners/player/PlayerJoinListener.java | 4 +- .../listeners/player/PlayerLeaveListener.java | 2 + Velocity/pom.xml | 5 +- .../src/net/tnemc/velocity/VelocityCore.java | 7 +- .../src/net/tnemc/velocity/VelocityProxy.java | 2 + .../event/ServerPostConnectListener.java | 1 + .../velocity/message/MessageListener.java | 1 + changelog.md | 10 +- license.md | 515 ++++++++--- pom.xml | 4 +- resource.md | 152 ++-- 343 files changed, 5625 insertions(+), 2970 deletions(-) diff --git a/.changelog/0.1.2.0.md b/.changelog/0.1.2.0.md index 979dc41d..f9ffb4e8 100644 --- a/.changelog/0.1.2.0.md +++ b/.changelog/0.1.2.0.md @@ -2,10 +2,14 @@ ## Summary -With TNE Beta 1.2, TNE is going back to its roots. This means providing you, the server owner, with the economy -experience that you deserve, and the features and ease-of-use that you expect. The TNE experience has been slacking, and -for that I apologize, but it's time to kick TNE back into shape and get your economy solution back to Platinum Standard. -With this release I have implemented the majority of the ease-of-use features that you, the owners and users, have +With TNE Beta 1.2, TNE is going back to its roots. This means providing you, the server owner, with +the economy +experience that you deserve, and the features and ease-of-use that you expect. The TNE experience +has been slacking, and +for that I apologize, but it's time to kick TNE back into shape and get your economy solution back +to Platinum Standard. +With this release I have implemented the majority of the ease-of-use features that you, the owners +and users, have requested. Start experiencing the ultimate economy experience! ## Features @@ -14,57 +18,64 @@ With Beta 1.2 comes some feature additions. - Added support for Geyser players. - Added support for MiniMessage - - The good news for TNE users is this was already the general format being used for message configurations, but now it - has additional functionality. https://docs.adventure.kyori.net/minimessage/format.html + - The good news for TNE users is this was already the general format being used for message + configurations, but now it + has additional functionality. https://docs.adventure.kyori.net/minimessage/format.html - Menus Galore! - - Added a currency editor menu - - Added a MyBAL menu - - Users may do everything from convert their currency, to make notes, to pay other players from this menu! - - Added a MySERVER menu, to help admins modify TNE settings + - Added a currency editor menu + - Added a MyBAL menu + - Users may do everything from convert their currency, to make notes, to pay other players + from this menu! + - Added a MySERVER menu, to help admins modify TNE settings - Currency System changes - - Added a new "Mixed" currency type. - - This allows your users to have a virtual currency, but also be able to withdraw it into items - - We now support offline payment using ender chests for item currencies! - - Currencies are no longer case-sensitive(not sure why they were in the first place.) - - Completely revamped the currency conversion system. - - Say goodbye to tiers, say hello to denominations! - - Denominations don't require a major/minor notation. This means you can make any form - of denomination from 0.05 to 1.05 to 50! + - Added a new "Mixed" currency type. + - This allows your users to have a virtual currency, but also be able to withdraw it into + items + - We now support offline payment using ender chests for item currencies! + - Currencies are no longer case-sensitive(not sure why they were in the first place.) + - Completely revamped the currency conversion system. + - Say goodbye to tiers, say hello to denominations! + - Denominations don't require a major/minor notation. This means you can make any form + of denomination from 0.05 to 1.05 to 50! - Added GroupRealms configuration setting to config.yml - - Setting this to true would make world, world_nether and world_the_end share balances automatically. + - Setting this to true would make world, world_nether and world_the_end share balances + automatically. ## Internal -In Beta 1.2 a lot of the TNE internals have been rewritten from the ground up. This will help facilitate future updates +In Beta 1.2 a lot of the TNE internals have been rewritten from the ground up. This will help +facilitate future updates and help with making TNE even more efficient. Specific Internal Changes: + - Rewrote TNE entirely from scratch - - This rewrite was done to allow for easily added support to other platforms such as - Sponge and Minestom + - This rewrite was done to allow for easily added support to other platforms such as + Sponge and Minestom - Transaction System changes - - The transaction system now has support for taxation built-in. This will allow - modules/third-party plugins to utilize it. + - The transaction system now has support for taxation built-in. This will allow + modules/third-party plugins to utilize it. - Command System has been switched to Lamp - TNE now uses "Regions" instead of "Worlds." - - This is for future changes as the term "worlds" is too restrictive, in my opinion. + - This is for future changes as the term "worlds" is too restrictive, in my opinion. - Made all data-storable objects able to be serialized into JSON - - This was done for the RESTAPI for TNE that is currently in progress. - - This will allow for third-party applications to interact with TNE such as web-based - and mobile device applications. + - This was done for the RESTAPI for TNE that is currently in progress. + - This will allow for third-party applications to interact with TNE such as web-based + and mobile device applications. - Account Types - - TNE Accounts have now been separated into different types. - - Towny Types - - Town - - Nation - - Faction Type - - NonPlayer - - Shared Accounts - - Allows the ability to add members to an account. + - TNE Accounts have now been separated into different types. + - Towny Types + - Town + - Nation + - Faction Type + - NonPlayer + - Shared Accounts + - Allows the ability to add members to an account. ## Removed -Some TNE features have been removed in this release in order to help keep TNE innovating and evolving. +Some TNE features have been removed in this release in order to help keep TNE innovating and +evolving. - Removed commands.yml - Removed the UUID configuration from config.yml. Use online mode or a proxy. diff --git a/.changelog/0.1.2.1.md b/.changelog/0.1.2.1.md index b19b803d..eeca6728 100644 --- a/.changelog/0.1.2.1.md +++ b/.changelog/0.1.2.1.md @@ -2,11 +2,14 @@ - Fixed issue where percent tax wasn't applied to payer for /pay(courtesy of pauloantoniassi) - Fixed issue where velocity wasn't correctly handling syncing(reported by batatinha) -- Fixed issue where item currencies wouldn't send sync message to bungee/velocity if the player was offline +- Fixed issue where item currencies wouldn't send sync message to bungee/velocity if the player was + offline - Added /balance, /bal, /balo and /balanceother shorthands - Clarified parameters for /money balance in messages.yml. -- Added feature to create account on other servers if doesn't exist when getting sync calls through Bungee/Velocity.(requested by DonJone) +- Added feature to create account on other servers if doesn't exist when getting sync calls through + Bungee/Velocity.(requested by DonJone) - Added xConomy Converter for conversion module(requested by AdrianIsEpic24) - Internal changes - - Exposed some variables of the SQLConnector for modules to use SQL connections easier with different credentials. + - Exposed some variables of the SQLConnector for modules to use SQL connections easier with + different credentials. - Fixed critical dupe glitch(reported by Wextra) \ No newline at end of file diff --git a/.changelog/0.1.2.2.md b/.changelog/0.1.2.2.md index 95811bbf..e8b08cf7 100644 --- a/.changelog/0.1.2.2.md +++ b/.changelog/0.1.2.2.md @@ -1,22 +1,26 @@ # 0.1.2.2 - Added Core.Commands.LimitCurrency config to config.yml - - This allows server owners to limit currency interactions using commands such as /money pay, /money give based on permission nodes when set to true. + - This allows server owners to limit currency interactions using commands such as /money pay, + /money give based on permission nodes when set to true. - Added permission nodes to block actions for players for specific currencies. - - tne.money.balance.insert currency identifier here - controls usage of /money balance - - tne.money.convert.to.insert currency identifier here - controls usage of /money convert's to parameter - - tne.money.convert.from.insert currency identifier here - controls usage of /money convert's from parameter - - tne.money.deposit.insert currency identifier here - controls usage of /money deposit - - tne.money.give.insert currency identifier here - controls usage of /money give - - tne.money.note.insert currency identifier here - controls usage of /money note - - tne.money.other.insert currency identifier here - controls usage of /money other - - tne.money.pay.insert currency identifier here - controls usage of /money pay - - tne.money.request.insert currency identifier here - controls usage of /money request - - tne.money.set.insert currency identifier here - controls usage of /money set - - tne.money.setall.insert currency identifier here - controls usage of /money setall - - tne.money.take.insert currency identifier here - controls usage of /money take - - tne.money.top.insert currency identifier here - controls usage of /money top - - tne.money.withdraw.insert currency identifier here - controls usage of /money withdraw + - tne.money.balance.insert currency identifier here - controls usage of /money balance + - tne.money.convert.to.insert currency identifier here - controls usage of /money convert's to + parameter + - tne.money.convert.from.insert currency identifier here - controls usage of /money convert's + from parameter + - tne.money.deposit.insert currency identifier here - controls usage of /money deposit + - tne.money.give.insert currency identifier here - controls usage of /money give + - tne.money.note.insert currency identifier here - controls usage of /money note + - tne.money.other.insert currency identifier here - controls usage of /money other + - tne.money.pay.insert currency identifier here - controls usage of /money pay + - tne.money.request.insert currency identifier here - controls usage of /money request + - tne.money.set.insert currency identifier here - controls usage of /money set + - tne.money.setall.insert currency identifier here - controls usage of /money setall + - tne.money.take.insert currency identifier here - controls usage of /money take + - tne.money.top.insert currency identifier here - controls usage of /money top + - tne.money.withdraw.insert currency identifier here - controls usage of /money withdraw ## Internal Changes + - Added a BaseProcessor variable to prevent initializing useless objects over and over. \ No newline at end of file diff --git a/.changelog/0.1.2.3.md b/.changelog/0.1.2.3.md index e0924e39..5a13b463 100644 --- a/.changelog/0.1.2.3.md +++ b/.changelog/0.1.2.3.md @@ -1,3 +1,4 @@ # 0.1.2.3 + - Added support for shulker box balances. - Removed debug messages that were in the console from 0.1.2.2 \ No newline at end of file diff --git a/.changelog/0.1.2.4.md b/.changelog/0.1.2.4.md index 3347b71f..c0ef385e 100644 --- a/.changelog/0.1.2.4.md +++ b/.changelog/0.1.2.4.md @@ -1,6 +1,8 @@ # 0.1.2.4 + - Fixed issue where using item currencies with QuickShop-Hikari caused an error. -- Moved essentials converter back to using the YAML files instead of the Essentials API since they reset balances to other economy plugins' +- Moved essentials converter back to using the YAML files instead of the Essentials API since they + reset balances to other economy plugins' - Added maria-outdated as a DB option for those who are using outdated maria/mysql databases. - Fixed issue with Redis not working. - Fixed issue with offline servers not saving balances. \ No newline at end of file diff --git a/.changelog/0.1.2.5.md b/.changelog/0.1.2.5.md index df940a55..8a7772ee 100644 --- a/.changelog/0.1.2.5.md +++ b/.changelog/0.1.2.5.md @@ -1,5 +1,6 @@ # 0.1.2.5 + - Added config option for Geyser player prefixes - Added more debug logging for player account creation. - Added more data saving. - - Balances will now save more frequently. After every transaction. \ No newline at end of file + - Balances will now save more frequently. After every transaction. \ No newline at end of file diff --git a/.changelog/0.1.2.6.md b/.changelog/0.1.2.6.md index 3a3e3519..aa8a198e 100644 --- a/.changelog/0.1.2.6.md +++ b/.changelog/0.1.2.6.md @@ -1,58 +1,72 @@ # 0.1.2.6 ## Additions + - Added replacements for /money for each balance type. - - $inventory - - $ender - - $virtual + - $inventory + - $ender + - $virtual - Added placeholders for each balance type: - - %tne_balance:inventory% - - %tne_balance:ender% - - %tne_balance:virtual% + - %tne_balance:inventory% + - %tne_balance:ender% + - %tne_balance:virtual% - Added support for placeholders in messages.yml translations - Added parsing support for custom decimals in command parameters. - Added extensive messaging for currency loading - - This should show the end-user when they have misconfigured a currency. - - This will also show a message when the folder associated isn't found. + - This should show the end-user when they have misconfigured a currency. + - This will also show a message when the folder associated isn't found. - Updated TNML to 1.5.0.0 in order to start work on the menu system for TNE. ## Internals -- Added more serialization classes for various TNE objects. These will provide an interface for converting TNE objects to JSON strings and back to the object from JSON -- This will allow for some cool additions in the future for official modules, as well as, allowing for third-party plugins to take advantage for their own use. - - Current supported types: - - Currency - - Denomination - - Note - - TaxEntry - - Account - - Member - - HoldingsEntry + +- Added more serialization classes for various TNE objects. These will provide an interface for + converting TNE objects to JSON strings and back to the object from JSON +- This will allow for some cool additions in the future for official modules, as well as, allowing + for third-party plugins to take advantage for their own use. + - Current supported types: + - Currency + - Denomination + - Note + - TaxEntry + - Account + - Member + - HoldingsEntry - Updated to the latest version of TNML. - - The latest version of TNML gives stability and will allow for menus to be added into TNE now. -- Code is now shared between the Bukkit Core and the Bukkit-fork based cores such as Folia and Paper. - - This removed 67 files of duplicate code + - The latest version of TNML gives stability and will allow for menus to be added into TNE now. +- Code is now shared between the Bukkit Core and the Bukkit-fork based cores such as Folia and + Paper. + - This removed 67 files of duplicate code ## API -- Added shorthand methods for ease-of-use for developers that don't need to utilize the transaction system. - - setHoldings - - getHoldings - - addHoldings - - removeHoldings - - hasHoldings + +- Added shorthand methods for ease-of-use for developers that don't need to utilize the transaction + system. + - setHoldings + - getHoldings + - addHoldings + - removeHoldings + - hasHoldings - Added methods for adding objects to the stand TNE ones - - addBalanceFormatRule - Adds a rule for the currency formatter, which may be used in the Format configuration - - addCurrency - Adds a new currency to use with TNE - - addCurrencyType - Adds a new currency type which may be used by the end user. This may also be used to override current ones such as virtual, item, etc - - addAccountStatus - Adds a new account status. This may be used to extend the current statuses for something such as a bank status. - - addAccountType - Adds a new SharedAccountType. This allows adding custom account types for things such as Factions, Lands, etc. + - addBalanceFormatRule - Adds a rule for the currency formatter, which may be used in the Format + configuration + - addCurrency - Adds a new currency to use with TNE + - addCurrencyType - Adds a new currency type which may be used by the end user. This may also be + used to override current ones such as virtual, item, etc + - addAccountStatus - Adds a new account status. This may be used to extend the current statuses + for something such as a bank status. + - addAccountType - Adds a new SharedAccountType. This allows adding custom account types for + things such as Factions, Lands, etc. ## Fixes -- Fixed issue where empty entries in the enchantments/flags fields for currency notes would cause issues. + +- Fixed issue where empty entries in the enchantments/flags fields for currency notes would cause + issues. - Fixed issue where Essentials would send an OfflinePlayer with a null name - Removed module download functionality from Sponge as requested by Sponge staff - Fixed issue where /money wasn't displaying for multi-currency correctly. - Fixed issue where using /tne reset wouldn't clear the cache. -- Fixed issue where currency configs were creating extra file if currency identifier didn't match file name. +- Fixed issue where currency configs were creating extra file if currency identifier didn't match + file name. - Fixed issue where account name wasn't being updated if user renamed themself - Fixed issue where Folia Build wasn't working properly - Fixed issue where MobDrop config wasn't working properly \ No newline at end of file diff --git a/.changelog/0.1.2.7.md b/.changelog/0.1.2.7.md index d5e6fb2b..67be7bd0 100644 --- a/.changelog/0.1.2.7.md +++ b/.changelog/0.1.2.7.md @@ -1,3 +1,4 @@ # 0.1.2.6 + - Fixed issue where console commands didn't work properly when the server account was disabled. - Fixed issue where Vault plugin wasn't loading properly. \ No newline at end of file diff --git a/.changelog/0.1.2.8.md b/.changelog/0.1.2.8.md index 65e76ff7..6784d547 100644 --- a/.changelog/0.1.2.8.md +++ b/.changelog/0.1.2.8.md @@ -1,16 +1,20 @@ # 0.1.2.8 ## Major Changes + - Reduce TNE-specific internals and started using TNPC. - - This plugin library separates TNE into economy stuff and a plugin base to use for my other plugins. + - This plugin library separates TNE into economy stuff and a plugin base to use for my other + plugins. ## Minor Changes + - Added toppos placeholders - - %tne_toppos_% - - %tne_toppos__position_% -- Made currency search by name case-insensitive + - %tne_toppos_% + - %tne_toppos__position_% +- Made currency search by name case-insensitive ## Fixes + - Fixed issue where invalid flag/attribute for item configurations caused error. - Fixed incompatibility with factions - Fixed incompatibility with EconomyShopGUI diff --git a/.changelog/0.1.2.9.md b/.changelog/0.1.2.9.md index 471c6143..5b862c3e 100644 --- a/.changelog/0.1.2.9.md +++ b/.changelog/0.1.2.9.md @@ -3,13 +3,17 @@ ## Major Changes ## Minor Changes + - Made messages in HoldingsResponse.java translatable from messages.yml -- Changed payment result for payment that would send account negative use insufficient versus less than minimum message. +- Changed payment result for payment that would send account negative use insufficient versus less + than minimum message. - Added permission node to restrict transactions for accounts for specific currencies. ## Internals + - Added negative balance support to internals for possible future release. ## Fixes + - Empty line in messages.yml, don't send - Fixed issue with calculating change in item currencies \ No newline at end of file diff --git a/.changelog/0.1.3.0.md b/.changelog/0.1.3.0.md index 8ee7af97..b896412f 100644 --- a/.changelog/0.1.3.0.md +++ b/.changelog/0.1.3.0.md @@ -1,36 +1,45 @@ # 0.1.3.0 ## Major Changes + - Added support for VaultUnlocked - Added support for 1.21 - Currency Editor/Creator - - Allows server owners/admins to modify, and create currencies and denominations. - - In the future this will allow for any configuration to be modified through the menu + - Allows server owners/admins to modify, and create currencies and denominations. + - In the future this will allow for any configuration to be modified through the menu - MyBal Menu - - Allows for players to check balances and perform actions + - Allows for players to check balances and perform actions - Switched to BoostedYAML for configurations - - This will allow for auto-updating configs when a change is implemented in future versions. + - This will allow for auto-updating configs when a change is implemented in future versions. - Transaction logging reimplemented - - This allows logging previous transactions and keeping track of what exactly happened when. + - This allows logging previous transactions and keeping track of what exactly happened when. - Added support for mini messages in currency item display names and lore lines. ## Minor Changes + - Remove sysout statements that were left in for debugging. -- Added config option to currencies for filling ender chest before dropping items on ground if inventory is full. -- Added messages to messages.yml for currency dropping on ground/going into ender chest if main inventory is full. -- Added a new config node, DisabledRegions, which allows server owners to disable economy commands in specific regions. +- Added config option to currencies for filling ender chest before dropping items on ground if + inventory is full. +- Added messages to messages.yml for currency dropping on ground/going into ender chest if main + inventory is full. +- Added a new config node, DisabledRegions, which allows server owners to disable economy commands + in specific regions. - Added /money givenote aka /givenote, which lets administrators create money notes for players. - Added the ability to add an alternative name for worlds in world messages. - - This is in Messages.yml under Messages.Worlds.* and the format is world name: "replacement" -- Added ImportItems option support to currency YAML files in order to enable importing items from player balances for new item currencies + - This is in Messages.yml under Messages.Worlds.* and the format is world name: "replacement" +- Added ImportItems option support to currency YAML files in order to enable importing items from + player balances for new item currencies ## Internals + - Added CurrencyDropCallback for developers to listen and disable currency item drops. - Fixed issue with TNIL and SemVer throw an error because the type was left on Strict vs loose - Removed Treasury Support due to lack of progress/VaultUnlocked support addition. -- Switched materials to Namespaced keys, this provides more support for modded items in hybrid servers. +- Switched materials to Namespaced keys, this provides more support for modded items in hybrid + servers. ## Fixes + - Fixed UpdateChecker. - Fixed issue with restricted transaction check causing issue for opped players. - Fixed issues with Bungee/Velocity from incorrect jar version on spigot page. @@ -39,11 +48,13 @@ ## Notes -- Going forward(post 0.1.3.0 full release), the target version for TNE will be 1.19+, supporting legacy servers will be limited to bug fixes. +- Going forward(post 0.1.3.0 full release), the target version for TNE will be 1.19+, supporting + legacy servers will be limited to bug fixes. ## TODO ## In-Progress + - Initial Setup Process - Skull support for note/currency diff --git a/.changelog/0.1.3.1.md b/.changelog/0.1.3.1.md index aa54e1ba..1ac53aeb 100644 --- a/.changelog/0.1.3.1.md +++ b/.changelog/0.1.3.1.md @@ -1,15 +1,20 @@ # 0.1.3.1 ## Supporting TNE -I have decided to launch a GitHub Sponsors page for those who are able to provide support for TNE development! You may find it here: https://github.com/sponsors/creatorfromhell -This GitHub Sponsors page will be used to help fund development and maintenance costs. As I start to create modules for TNE, I'll add access to them for Sponsors! +I have decided to launch a GitHub Sponsors page for those who are able to provide support for TNE +development! You may find it here: https://github.com/sponsors/creatorfromhell + +This GitHub Sponsors page will be used to help fund development and maintenance costs. As I start to +create modules for TNE, I'll add access to them for Sponsors! ## Major Changes ## Minor Changes + - Added /transactions as shortcut for /transaction history ## Fixes + - Fixed issues with the myBal menu - Fixed issues some users were having with vault/paper connections on Paper with PaperCore \ No newline at end of file diff --git a/.changelog/0.1.3.2.md b/.changelog/0.1.3.2.md index cf703544..4ed836d1 100644 --- a/.changelog/0.1.3.2.md +++ b/.changelog/0.1.3.2.md @@ -1,41 +1,52 @@ # 0.1.3.2 ## Major Changes + - Added secret addition that some servers may find useful. ## Minor Changes -- Added new currency type, experience-level, which uses experience levels instead of experience itself. + +- Added new currency type, experience-level, which uses experience levels instead of experience + itself. - Added message that is sent when currencies are saved from menu. - Added message that is sent when MyECO is closed, but currencies weren't saved. -- Added configuration to currencies that will determine if the currency is shown in balance commands. +- Added configuration to currencies that will determine if the currency is shown in balance + commands. - Added new permissions to shared accounts; TRANSFER_OWNERSHIP and DELETE -- Added ability for messages from some money commands to be sent to players on different servers through bungee/redis/velocity +- Added ability for messages from some money commands to be sent to players on different servers + through bungee/redis/velocity - Added $pos placeholder for TopEntry message. - Added configuration to enabled/disable GUI alternatives to the chat-based commands. -- Added and JPrefixes for japanese number formatting. Requested by okarradon from discord. +- Added and JPrefixes for japanese number formatting. Requested by okarradon from + discord. ## Internals + - Various improvements to the module system - - Added the ability to require a specific TNE version - - Made it so commands are actually loaded properly - - Made it so callbacks are actually loaded/registered properly + - Added the ability to require a specific TNE version + - Made it so commands are actually loaded properly + - Made it so callbacks are actually loaded/registered properly ## Fixes + - Fixed issue with Folia build that got messed up when implementing Components - Removed luck perms context class completely since it was unused. - Fixed issue with bundles not removing item currencies properly -- Fixed issue with PotionData on 1.21 servers since spigot changed an API method from NotNull to Nullable... +- Fixed issue with PotionData on 1.21 servers since spigot changed an API method from NotNull to + Nullable... - Fixed issue with Banners on 1.21 servers, same as above. - Fixed issue with callbacks not being called. - Fixed issue with towny/factions accounts not being added. - Fixed incorrect message being sent for Insufficient funds. ## Notes + - Bad API Design from Spigot/Paper: "changing an API method from NotNull to Nullable..." ## TODO ## In-Progress + - Initial Setup Process - Skull support for note/currency diff --git a/.github/ISSUE_TEMPLATE/report-a-bug.yml b/.github/ISSUE_TEMPLATE/report-a-bug.yml index 145fec32..ce719cfc 100644 --- a/.github/ISSUE_TEMPLATE/report-a-bug.yml +++ b/.github/ISSUE_TEMPLATE/report-a-bug.yml @@ -1,7 +1,7 @@ name: Bug Report description: File a bug report for TNE to help us improve your experience title: "[BUG]: " -labels: ["bug"] +labels: [ "bug" ] assignees: - creatorfromhell diff --git a/.github/ISSUE_TEMPLATE/request-a-feature.yml b/.github/ISSUE_TEMPLATE/request-a-feature.yml index 46a0d6d2..fb551e59 100644 --- a/.github/ISSUE_TEMPLATE/request-a-feature.yml +++ b/.github/ISSUE_TEMPLATE/request-a-feature.yml @@ -1,7 +1,7 @@ name: Feature Request description: Suggest a feature to be added in order to help TNE improve. title: "[FEAT]: " -labels: ["feature"] +labels: [ "feature" ] assignees: - creatorfromhell diff --git a/.github/workflows/codesee-arch-diagram.yml b/.github/workflows/codesee-arch-diagram.yml index 806d41d1..ac331b2a 100644 --- a/.github/workflows/codesee-arch-diagram.yml +++ b/.github/workflows/codesee-arch-diagram.yml @@ -5,7 +5,7 @@ on: branches: - main pull_request_target: - types: [opened, synchronize, reopened] + types: [ opened, synchronize, reopened ] name: CodeSee diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 256e6ea1..b6d90e9c 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -20,21 +20,21 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - name: Set up JDK 17 - uses: actions/setup-java@v3 - with: - java-version: '17' - distribution: 'temurin' - cache: maven - - name: Build with Maven - run: mvn -B package --file pom.xml - - uses: actions/upload-artifact@v3 - with: - name: tne-snapshots - path: | + - uses: actions/checkout@v4 + - name: Set up JDK 17 + uses: actions/setup-java@v3 + with: + java-version: '17' + distribution: 'temurin' + cache: maven + - name: Build with Maven + run: mvn -B package --file pom.xml + - uses: actions/upload-artifact@v3 + with: + name: tne-snapshots + path: | **/target/*.jar - # Optional: Uploads the full dependency graph to GitHub to improve the quality of Dependabot alerts this repository can receive - - name: Update dependency graph - uses: advanced-security/maven-dependency-submission-action@571e99aab1055c2e71a1e2309b9691de18d6b7d6 + # Optional: Uploads the full dependency graph to GitHub to improve the quality of Dependabot alerts this repository can receive + - name: Update dependency graph + uses: advanced-security/maven-dependency-submission-action@571e99aab1055c2e71a1e2309b9691de18d6b7d6 diff --git a/Bug Report.md b/Bug Report.md index 695e7007..1a0c908b 100644 --- a/Bug Report.md +++ b/Bug Report.md @@ -1,23 +1,37 @@ Report Format ===================== -Please Note: If, for any reason, you elect not to use the following format for your issue, it will be closed without +Please Note: If, for any reason, you elect not to use the following format for your issue, it will +be closed without notice. - ## Feature Request Format + #### What feature are you suggesting be added? + #### Expected use-case for said feature? + #### Why should this feature be added to TNE? ## Bug Report Format + #### What is the issue/bug you're experiencing? + #### How can the issue be reproduced?(i.e. the steps to make the issue occur again) + #### TNE version?(exact version number), and whether or not you've made modification to it. + #### TNE build?(/tne build), and whether or not you've made modification to it. + #### Modules Loaded?(exact version number), and whether or not you've made modification to it. + #### Spigot/Bukkit version? + #### Is your server run in online mode? + #### The exact command you ran w/ arguments? + #### config.yml?(use http://paste.ubuntu.com, and remove your SQL details) + #### Your latest server log file?(use http://paste.ubuntu.com) + #### If this is to do with messages/world/player configurations, please include the YAML file for such.(use http://paste.ubuntu.com) diff --git a/Bukkit/pom.xml b/Bukkit/pom.xml index f334894f..725a9461 100644 --- a/Bukkit/pom.xml +++ b/Bukkit/pom.xml @@ -1,4 +1,6 @@ - + 4.0.0 BukkitCore jar @@ -40,7 +42,6 @@ - clean package target @@ -108,7 +109,9 @@ - ${project.build.directory}/dependency-reduced-pom.xml + + ${project.build.directory}/dependency-reduced-pom.xml + net.tnemc:* diff --git a/Bukkit/src/net/tnemc/bukkit/BukkitConfig.java b/Bukkit/src/net/tnemc/bukkit/BukkitConfig.java index fbe264f5..8ce0258d 100644 --- a/Bukkit/src/net/tnemc/bukkit/BukkitConfig.java +++ b/Bukkit/src/net/tnemc/bukkit/BukkitConfig.java @@ -35,15 +35,18 @@ public class BukkitConfig extends Config { private static BukkitConfig instance; + public BukkitConfig() { + super("bukkit.yml", "bukkit.yml", Collections.singletonList("Bukkit"), - LoaderSettings.builder().setAutoUpdate(true).build(), - UpdaterSettings.builder().setAutoSave(true).setVersioning(new BasicVersioning("Bukkit.config-version")).build()); + LoaderSettings.builder().setAutoUpdate(true).build(), + UpdaterSettings.builder().setAutoSave(true).setVersioning(new BasicVersioning("Bukkit.config-version")).build()); instance = this; } public static YamlDocument yaml() { + return instance.getYaml(); } } \ No newline at end of file diff --git a/Bukkit/src/net/tnemc/bukkit/BukkitCore.java b/Bukkit/src/net/tnemc/bukkit/BukkitCore.java index 7345e1be..c516c4e6 100644 --- a/Bukkit/src/net/tnemc/bukkit/BukkitCore.java +++ b/Bukkit/src/net/tnemc/bukkit/BukkitCore.java @@ -49,26 +49,31 @@ public class BukkitCore extends TNECore { private BukkitConfig bukkitConfig; public BukkitCore(JavaPlugin plugin) { + this.plugin = plugin; } @Override public void registerMenuHandler() { + this.menuHandler = new BukkitMenuHandler(plugin, true); } @Override public void registerCommandHandler() { + command = BukkitCommandHandler.create(plugin); } @Override public String commandHelpWriter(ExecutableCommand executableCommand, CommandActor commandActor) { + return ""; } @Override public void registerConfigs() { + super.registerConfigs(); this.bukkitConfig = new BukkitConfig(); @@ -79,6 +84,7 @@ public void registerConfigs() { @Override public void registerCommands() { + super.registerCommands(); //Register our commands @@ -91,6 +97,7 @@ public void registerCommands() { @Override public void registerCallbacks(CallbackManager callbackManager) { + super.registerCallbacks(callbackManager); callbackManager.addConsumer(TNECallbacks.ACCOUNT_TYPES.toString(), (callback->{ @@ -111,14 +118,17 @@ public void registerCallbacks(CallbackManager callbackManager) { @Override public BukkitItemCalculations itemCalculations() { + return new BukkitItemCalculations(); } public static BukkitCore instance() { + return (BukkitCore)TNECore.instance(); } public JavaPlugin getPlugin() { + return plugin; } } \ No newline at end of file diff --git a/Bukkit/src/net/tnemc/bukkit/BukkitPlugin.java b/Bukkit/src/net/tnemc/bukkit/BukkitPlugin.java index f44c947a..bcecbc35 100644 --- a/Bukkit/src/net/tnemc/bukkit/BukkitPlugin.java +++ b/Bukkit/src/net/tnemc/bukkit/BukkitPlugin.java @@ -54,8 +54,8 @@ public class BukkitPlugin { private boolean papiHooked = false; /** - * Called when the plugin is loaded by the Bukkit plugin manager. - * This method should be used to initialize any necessary resources or data. + * Called when the plugin is loaded by the Bukkit plugin manager. This method should be used to + * initialize any necessary resources or data. */ public void load(final JavaPlugin plugin, ServerConnector server) { @@ -82,8 +82,8 @@ public void load(final JavaPlugin plugin, ServerConnector server) { } /** - * Called by the Bukkit plugin manager when the plugin is enabled. - * This method should be used to enable the functionality provided by this class. + * Called by the Bukkit plugin manager when the plugin is enabled. This method should be used to + * enable the functionality provided by this class. */ public void enable(final JavaPlugin plugin) { @@ -119,18 +119,21 @@ public void enable(final JavaPlugin plugin) { } /** - * Called by the Bukkit plugin manager when the plugin is disabled. - * This method should be used to disable the functionality provided by this class. + * Called by the Bukkit plugin manager when the plugin is disabled. This method should be used to + * disable the functionality provided by this class. */ public void disable(final JavaPlugin plugin) { + this.pluginCore.onDisable(); } public boolean isPapiHooked() { + return papiHooked; } public void setPapiHooked(boolean papiHooked) { + this.papiHooked = papiHooked; } } \ No newline at end of file diff --git a/Bukkit/src/net/tnemc/bukkit/ModifiedBukkitLogger.java b/Bukkit/src/net/tnemc/bukkit/ModifiedBukkitLogger.java index dfa1aa12..323deb49 100644 --- a/Bukkit/src/net/tnemc/bukkit/ModifiedBukkitLogger.java +++ b/Bukkit/src/net/tnemc/bukkit/ModifiedBukkitLogger.java @@ -40,6 +40,7 @@ public record ModifiedBukkitLogger(Logger logger) implements LogProvider { */ @Override public void inform(String message, DebugLevel level) { + if(level.compare(PluginCore.instance().getLevel())) { logger.info(message); } @@ -53,6 +54,7 @@ public void inform(String message, DebugLevel level) { */ @Override public void debug(String message, DebugLevel level) { + if(level.compare(PluginCore.instance().getLevel())) { logger.warning("[DEBUG]: " + message); } @@ -66,6 +68,7 @@ public void debug(String message, DebugLevel level) { */ @Override public void warning(String message, DebugLevel level) { + if(level.compare(PluginCore.instance().getLevel())) { logger.warning(message); } @@ -79,6 +82,7 @@ public void warning(String message, DebugLevel level) { */ @Override public void error(String message, DebugLevel level) { + if(level.compare(PluginCore.instance().getLevel())) { logger.warning(message); } @@ -93,6 +97,7 @@ public void error(String message, DebugLevel level) { */ @Override public void error(String message, Exception exception, DebugLevel level) { + if(level.compare(PluginCore.instance().getLevel())) { logger.warning("====== Exception Occurred ======"); exception.printStackTrace(); diff --git a/Bukkit/src/net/tnemc/bukkit/ModifiedBukkitPluginCore.java b/Bukkit/src/net/tnemc/bukkit/ModifiedBukkitPluginCore.java index 3a7744d4..01a76ade 100644 --- a/Bukkit/src/net/tnemc/bukkit/ModifiedBukkitPluginCore.java +++ b/Bukkit/src/net/tnemc/bukkit/ModifiedBukkitPluginCore.java @@ -32,7 +32,9 @@ * @since 0.1.2.0 */ public class ModifiedBukkitPluginCore extends BukkitPluginCore { + public ModifiedBukkitPluginCore(JavaPlugin plugin, PluginEngine engine, ServerConnector connector, TranslationProvider provider, CallbackProvider callbackProvider) { + super(plugin, engine, connector, provider, callbackProvider); this.logger = new ModifiedBukkitLogger(plugin.getLogger()); diff --git a/Bukkit/src/net/tnemc/bukkit/TNE.java b/Bukkit/src/net/tnemc/bukkit/TNE.java index 3d7f7671..7e3ad210 100644 --- a/Bukkit/src/net/tnemc/bukkit/TNE.java +++ b/Bukkit/src/net/tnemc/bukkit/TNE.java @@ -33,20 +33,24 @@ public class TNE extends JavaPlugin { @Override public void onLoad() { + this.bukkit.load(this, new BukkitServerProvider()); } @Override public void onEnable() { + this.bukkit.enable(this); } @Override public void onDisable() { + this.bukkit.disable(this); } public BukkitPlugin getBukkit() { + return bukkit; } } \ No newline at end of file diff --git a/Bukkit/src/net/tnemc/bukkit/command/AdminCommand.java b/Bukkit/src/net/tnemc/bukkit/command/AdminCommand.java index 7755ea75..7a648ff8 100644 --- a/Bukkit/src/net/tnemc/bukkit/command/AdminCommand.java +++ b/Bukkit/src/net/tnemc/bukkit/command/AdminCommand.java @@ -59,133 +59,149 @@ * @author creatorfromhell * @since 0.1.2.0 */ -@Command({"tne", "myeco", "ecomenu", "ecomin", "ecoadmin", "ecomanage", "theneweconomy"}) +@Command({ "tne", "myeco", "ecomenu", "ecomin", "ecoadmin", "ecomanage", "theneweconomy" }) @Description("Admin.Main.Description") public class AdminCommand { - @DefaultFor({"tne", "myeco", "ecomin", "ecoadmin", "ecomanage", "theneweconomy"}) - @Subcommand({"ecomenu", "menu", "myeco"}) + @DefaultFor({ "tne", "myeco", "ecomin", "ecoadmin", "ecomanage", "theneweconomy" }) + @Subcommand({ "ecomenu", "menu", "myeco" }) @Usage("Admin.MyEco.Arguments") @Description("Admin.MyEco.Description") @CommandPermission("tne.admin.menu") public void onMyEco(BukkitCommandActor sender) { + net.tnemc.core.command.AdminCommand.onMyEco(new BukkitCMDSource(sender)); } - @Subcommand({"help", "?"}) + @Subcommand({ "help", "?" }) @Usage("Help.Arguments") @Description("Help.Description") public void help(BukkitCommandActor actor, CommandHelp helpEntries, @Default("1") int page) { + BaseCommand.help(new BukkitCMDSource(actor), helpEntries, page); } - @Subcommand({"backup", "archive"}) + @Subcommand({ "backup", "archive" }) @Usage("Admin.Backup.Arguments") @Description("Admin.Backup.Description") @CommandPermission("tne.admin.backup") public void backup(BukkitCommandActor sender) { + net.tnemc.core.command.AdminCommand.onBackup(new BukkitCMDSource(sender)); } - @Subcommand({"create", "add", "new", "make", "+"}) + @Subcommand({ "create", "add", "new", "make", "+" }) @Usage("Admin.Create.Arguments") @Description("Admin.Create.Description") @CommandPermission("tne.admin.create") public void create(BukkitCommandActor sender, String name) { + net.tnemc.core.command.AdminCommand.onCreate(new BukkitCMDSource(sender), name); } - @Subcommand({"debug"}) + @Subcommand({ "debug" }) @Usage("Admin.Debug.Arguments") @Description("Admin.Debug.Description") @CommandPermission("tne.admin.debug") public void debug(BukkitCommandActor sender, DebugLevel level) { + net.tnemc.core.command.AdminCommand.onDebug(new BukkitCMDSource(sender), level); } - @Subcommand({"delete", "destroy", "del", "remove", "-"}) + @Subcommand({ "delete", "destroy", "del", "remove", "-" }) @Usage("Admin.Delete.Arguments") @Description("Admin.Delete.Description") @CommandPermission("tne.admin.delete") public void delete(BukkitCommandActor sender, String name) { + net.tnemc.core.command.AdminCommand.onDelete(new BukkitCMDSource(sender), name); } - @Subcommand({"extract"}) + @Subcommand({ "extract" }) @Usage("Admin.Extract.Arguments") @Description("Admin.Extract.Description") @CommandPermission("tne.admin.extract") public void extract(BukkitCommandActor sender) { + net.tnemc.core.command.AdminCommand.onExtract(new BukkitCMDSource(sender)); } - @Subcommand({"purge"}) + @Subcommand({ "purge" }) @Usage("Admin.Purge.Arguments") @Description("Admin.Purge.Description") @CommandPermission("tne.admin.purge") public void purge(BukkitCommandActor sender) { + net.tnemc.core.command.AdminCommand.onPurge(new BukkitCMDSource(sender)); } - @Subcommand({"reload"}) + @Subcommand({ "reload" }) @Usage("Admin.Reload.Arguments") @Description("Admin.Reload.Description") @CommandPermission("tne.admin.reload") public void reload(BukkitCommandActor sender, @Default("all") String type) { + net.tnemc.core.command.AdminCommand.onReload(new BukkitCMDSource(sender), type); } - @Subcommand({"reset", "nuke"}) + @Subcommand({ "reset", "nuke" }) @Usage("Admin.Reset.Arguments") @Description("Admin.Reset.Description") @CommandPermission("tne.admin.reset") public void reset(BukkitCommandActor sender) { + net.tnemc.core.command.AdminCommand.onReset(new BukkitCMDSource(sender)); } - @Subcommand({"restore"}) + @Subcommand({ "restore" }) @Usage("Admin.Restore.Arguments") @Description("Admin.Restore.Description") @CommandPermission("tne.admin.restore") public void restore(BukkitCommandActor sender, @Default("0") int extraction) { + net.tnemc.core.command.AdminCommand.onRestore(new BukkitCMDSource(sender), extraction); } - @Subcommand({"old"}) + @Subcommand({ "old" }) @Usage("Admin.Restore.Arguments") @Description("Admin.Restore.Description") @CommandPermission("tne.admin.old") public void old(BukkitCommandActor sender, @Default("0") int extraction) { + PluginCore.server().scheduler().createDelayedTask(()->restoreOld(extraction), new ChoreTime(0), ChoreExecution.SECONDARY); new BukkitCMDSource(sender).message(new MessageData("Messages.Admin.Restoration")); } - @Subcommand({"save"}) + @Subcommand({ "save" }) @Usage("Admin.Save.Arguments") @Description("Admin.Save.Description") @CommandPermission("tne.admin.save") public void save(BukkitCommandActor sender) { + net.tnemc.core.command.AdminCommand.onSave(new BukkitCMDSource(sender)); } - @Subcommand({"status"}) + @Subcommand({ "status" }) @Usage("Admin.Status.Arguments") @Description("Admin.Status.Description") @CommandPermission("tne.admin.status") public void status(BukkitCommandActor sender, Account account, @Default("normal") AccountStatus status) { + net.tnemc.core.command.AdminCommand.onStatus(new BukkitCMDSource(sender), account, status); } - @Subcommand({"version", "ver", "build"}) + @Subcommand({ "version", "ver", "build" }) @Usage("Admin.Version.Arguments") @Description("Admin.Version.Description") @CommandPermission("tne.admin.version") public void version(BukkitCommandActor sender) { + net.tnemc.core.command.AdminCommand.onVersion(new BukkitCMDSource(sender)); } public static boolean restoreOld(@Nullable final Integer extraction) { + final File file = new File(PluginCore.directory(), "extracted.yml"); if(!file.exists()) { @@ -240,15 +256,15 @@ public static boolean restoreOld(@Nullable final Integer extraction) { final String currency = (String)currencyNameObj; if(!recode) { - final String finalCurrency = (currency.equalsIgnoreCase("default")) ? TNECore.eco().currency().getDefaultCurrency().getIdentifier() : currency; + final String finalCurrency = (currency.equalsIgnoreCase("default"))? TNECore.eco().currency().getDefaultCurrency().getIdentifier() : currency; final Optional cur = TNECore.eco().currency().findCurrency(finalCurrency); - final Currency currencyObj = cur.orElseGet(() -> TNECore.eco().currency().getDefaultCurrency(TNECore.eco().region().resolve(region))); + final Currency currencyObj = cur.orElseGet(()->TNECore.eco().currency().getDefaultCurrency(TNECore.eco().region().resolve(region))); final BigDecimal amount = new BigDecimal(extracted.getString("Accounts." + name + ".Balances." + region + "." + currency)); response.getAccount().get().setHoldings(new HoldingsEntry(TNECore.eco().region().resolve(region), currencyObj.getUid(), - amount, EconomyManager.NORMAL), TNECore.eco().getFor(currencyObj.type()).get(0).identifier()); + amount, EconomyManager.NORMAL), TNECore.eco().getFor(currencyObj.type()).get(0).identifier()); } else { final Set types = extracted.getSection("Accounts." + name + ".Balances." + region + "." + currency).getKeys(); @@ -256,23 +272,23 @@ public static boolean restoreOld(@Nullable final Integer extraction) { final String type = (String)typeObj; final BigDecimal amount = new BigDecimal(extracted.getString("Accounts." + name - + ".Balances." + region - + "." + currency + "." - + type)); + + ".Balances." + region + + "." + currency + "." + + type)); response.getAccount().get().setHoldings(new HoldingsEntry(region, UUID.fromString(currency), - amount, Identifier.fromID(type))); + amount, Identifier.fromID(type))); } } number++; try { final boolean message = (number % frequency == 0); - if (message) { + if(message) { final int progress = (number * 100) / accounts.size(); PluginCore.log().inform("Restoration Progress: " + progress, DebugLevel.OFF); } - } catch(Exception ignore) {} + } catch(Exception ignore) { } } } } @@ -283,6 +299,7 @@ public static boolean restoreOld(@Nullable final Integer extraction) { } protected static UUID get(final String name) { + for(OfflinePlayer player : Bukkit.getServer().getOfflinePlayers()) { if(player.getName() == null) continue; if(player.getName().equalsIgnoreCase(name)) { diff --git a/Bukkit/src/net/tnemc/bukkit/command/ModuleCommand.java b/Bukkit/src/net/tnemc/bukkit/command/ModuleCommand.java index 9546eaaa..bd17c0bd 100644 --- a/Bukkit/src/net/tnemc/bukkit/command/ModuleCommand.java +++ b/Bukkit/src/net/tnemc/bukkit/command/ModuleCommand.java @@ -37,54 +37,60 @@ * @author creatorfromhell * @since 0.1.2.0 */ -@Command({"module", "mod"}) +@Command({ "module", "mod" }) public class ModuleCommand { - @Subcommand({"help", "?"}) + @Subcommand({ "help", "?" }) @Usage("Help.Arguments") @Description("Help.Description") public void help(BukkitCommandActor actor, CommandHelp helpEntries, @Default("1") int page) { + BaseCommand.help(new BukkitCMDSource(actor), helpEntries, page); } - @Subcommand({"avail", "available"}) + @Subcommand({ "avail", "available" }) @Usage("Module.Available.Arguments") @Description("Module.Available.Description") @CommandPermission("tne.module.available") public void onAvailable(BukkitCommandActor sender, @Default(TNECore.coreURL) String url) { + net.tnemc.core.command.ModuleCommand.onAvailable(new BukkitCMDSource(sender), url); } - @Subcommand({"download", "dl"}) + @Subcommand({ "download", "dl" }) @Usage("Module.Download.Arguments") @Description("Module.Download.Description") @CommandPermission("tne.module.download") public void onDownload(BukkitCommandActor sender, String moduleName, @Default(TNECore.coreURL) String url) { + net.tnemc.core.command.ModuleCommand.onDownload(new BukkitCMDSource(sender), moduleName, url); } - @Subcommand({"info", "i"}) + @Subcommand({ "info", "i" }) @Usage("Module.Info.Arguments") @Description("Module.Info.Description") @CommandPermission("tne.module.info") public void onInfo(BukkitCommandActor sender, String moduleName) { + net.tnemc.core.command.ModuleCommand.onInfo(new BukkitCMDSource(sender), moduleName); } - @Subcommand({"list", "l"}) + @Subcommand({ "list", "l" }) @Usage("Module.List.Arguments") - @DefaultFor({"module", "mod"}) + @DefaultFor({ "module", "mod" }) @Description("Module.List.Description") @CommandPermission("tne.list.available") public void onList(BukkitCommandActor sender) { + net.tnemc.core.command.ModuleCommand.onList(new BukkitCMDSource(sender)); } - @Subcommand({"load"}) + @Subcommand({ "load" }) @Usage("Module.Load.Arguments") @Description("Module.Load.Description") @CommandPermission("tne.module.load") public void onLoad(BukkitCommandActor sender, String moduleName) { + net.tnemc.core.command.ModuleCommand.onLoad(new BukkitCMDSource(sender), moduleName); } } \ No newline at end of file diff --git a/Bukkit/src/net/tnemc/bukkit/command/MoneyCommand.java b/Bukkit/src/net/tnemc/bukkit/command/MoneyCommand.java index bcaa8fda..ec131565 100644 --- a/Bukkit/src/net/tnemc/bukkit/command/MoneyCommand.java +++ b/Bukkit/src/net/tnemc/bukkit/command/MoneyCommand.java @@ -17,6 +17,7 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . */ + import net.tnemc.core.account.Account; import net.tnemc.core.command.BaseCommand; import net.tnemc.core.command.parameters.PercentBigDecimal; @@ -41,144 +42,161 @@ * @author creatorfromhell * @since 0.1.2.0 */ -@Command({"money", "eco", "balo", "balance", "bal", "balanceother", "mybal"}) +@Command({ "money", "eco", "balo", "balance", "bal", "balanceother", "mybal" }) public class MoneyCommand { - @DefaultFor({"mybal"}) - @Subcommand({"balmenu", "menu", "mybal"}) + @DefaultFor({ "mybal" }) + @Subcommand({ "balmenu", "menu", "mybal" }) @Usage("Money.MyBal.Arguments") @Description("Money.MyBal.Description") @CommandPermission("tne.money.mybal") public void onMyBal(BukkitCommandActor sender) { + net.tnemc.core.command.MoneyCommand.onMyBal(new BukkitCMDSource(sender)); } - @Subcommand({"help", "?"}) + @Subcommand({ "help", "?" }) @Usage("Help.Arguments") @Description("Help.Description") public void help(BukkitCommandActor actor, CommandHelp helpEntries, @Default("1") int page) { + BaseCommand.help(new BukkitCMDSource(actor), helpEntries, page); } - @DefaultFor({"bal", "money", "eco", "balance"}) - @Subcommand({"balance", "bal", "val"}) + @DefaultFor({ "bal", "money", "eco", "balance" }) + @Subcommand({ "balance", "bal", "val" }) @Usage("Money.Balance.Arguments") @Description("Money.Balance.Description") @CommandPermission("tne.money.balance") public void onBalance(BukkitCommandActor sender, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onBalance(new BukkitCMDSource(sender), currency, region); } - @Subcommand({"convert"}) + @Subcommand({ "convert" }) @Usage("Money.Convert.Arguments") @Description("Money.Convert.Description") @CommandPermission("tne.money.convert") public void onConvert(BukkitCommandActor sender, @Named("amount") PercentBigDecimal amount, @Named("currency") Currency currency, @Named("currency") Currency from) { + net.tnemc.core.command.MoneyCommand.onConvert(new BukkitCMDSource(sender), amount, currency, from); } - @Subcommand({"deposit"}) + @Subcommand({ "deposit" }) @Usage("Money.Deposit.Arguments") @Description("Money.Deposit.Description") @CommandPermission("tne.money.deposit") public void onDeposit(BukkitCommandActor sender, @Named("amount") PercentBigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onDeposit(new BukkitCMDSource(sender), amount, currency, region); } - @Subcommand({"give", "+", "add"}) + @Subcommand({ "give", "+", "add" }) @Usage("Money.Give.Arguments") @Description("Money.Give.Description") @CommandPermission("tne.money.give") public void onGive(BukkitCommandActor sender, Account player, @Named("amount") PercentBigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onGive(new BukkitCMDSource(sender), player, amount, region, currency); } - @Subcommand({"givenote", "+note", "addnote"}) + @Subcommand({ "givenote", "+note", "addnote" }) @Usage("Money.GiveNote.Arguments") @Description("Money.GiveNote.Description") @CommandPermission("tne.money.givenote") public void onGiveNote(BukkitCommandActor sender, Account player, @Named("amount") BigDecimal amount, @Default("") @Named("currency") Currency currency) { + net.tnemc.core.command.MoneyCommand.onGiveNote(new BukkitCMDSource(sender), player, amount, currency); } - @Subcommand({"note", "n"}) + @Subcommand({ "note", "n" }) @Usage("Money.Note.Arguments") @Description("Money.Note.Description") @CommandPermission("tne.money.note") public void onNote(BukkitCommandActor sender, @Named("amount") PercentBigDecimal amount, @Default("") @Named("currency") Currency currency) { + net.tnemc.core.command.MoneyCommand.onNote(new BukkitCMDSource(sender), amount, currency); } - @Subcommand({"other", "check", "balo"}) - @DefaultFor({"balo", "balanceother"}) + @Subcommand({ "other", "check", "balo" }) + @DefaultFor({ "balo", "balanceother" }) @Usage("Money.Other.Arguments") @Description("Money.Other.Description") @CommandPermission("tne.money.other") public void onOther(BukkitCommandActor sender, Account player, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onOther(new BukkitCMDSource(sender), player, region, currency); } - @Subcommand({"pay", "send", "transfer"}) + @Subcommand({ "pay", "send", "transfer" }) @Usage("Money.Pay.Arguments") @Description("Money.Pay.Description") @CommandPermission("tne.money.pay") public void onPay(BukkitCommandActor sender, Account player, @Named("amount") PercentBigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("") String from) { + net.tnemc.core.command.MoneyCommand.onPay(new BukkitCMDSource(sender), player, amount, currency, from); } - @Subcommand({"request"}) + @Subcommand({ "request" }) @Usage("Money.Request.Arguments") @Description("Money.Request.Description") @CommandPermission("tne.money.Request") public void onRequest(BukkitCommandActor sender, Account player, @Named("amount") BigDecimal amount, @Default("") @Named("currency") Currency currency) { + net.tnemc.core.command.MoneyCommand.onRequest(new BukkitCMDSource(sender), player, amount, currency); } - @Subcommand({"set", "eq", "="}) + @Subcommand({ "set", "eq", "=" }) @Usage("Money.Set.Arguments") @Description("Money.Set.Description") @CommandPermission("tne.money.set") public void onSet(BukkitCommandActor sender, Account player, @Named("amount") BigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onSet(new BukkitCMDSource(sender), player, amount, region, currency); } - @Subcommand({"setall"}) + @Subcommand({ "setall" }) @Usage("Money.SetAll.Arguments") @Description("Money.SetAll.Description") @CommandPermission("tne.money.setall") public void onSetAll(BukkitCommandActor sender, @Named("amount") BigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onSetAll(new BukkitCMDSource(sender), amount, region, currency); } - @Subcommand({"switch", "swap"}) + @Subcommand({ "switch", "swap" }) @Usage("Money.Switch.Arguments") @Description("Money.Switch.Description") @CommandPermission("tne.money.switch") public void onSwitch(BukkitCommandActor sender, @Named("switched") Account account) { + net.tnemc.core.command.MoneyCommand.onSwitch(new BukkitCMDSource(sender), account); } - @Subcommand({"take", "minus", "remove", "-"}) + @Subcommand({ "take", "minus", "remove", "-" }) @Usage("Money.Take.Arguments") @Description("Money.Take.Description") @CommandPermission("tne.money.take") public void onTake(BukkitCommandActor sender, Account player, @Named("amount") PercentBigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onTake(new BukkitCMDSource(sender), player, amount, region, currency); } - @Subcommand({"top", "baltop"}) + @Subcommand({ "top", "baltop" }) @Usage("Money.Top.Arguments") @Description("Money.Top.Description") @CommandPermission("tne.money.top") public void onTop(BukkitCommandActor sender, @Default("1") Integer page, @Default("") @Named("currency") Currency currency, @Default("false") Boolean refresh) { + net.tnemc.core.command.MoneyCommand.onTop(new BukkitCMDSource(sender), page, currency, refresh); } - @Subcommand({"withdraw"}) + @Subcommand({ "withdraw" }) @Usage("Money.Withdraw.Arguments") @Description("Money.Withdraw.Description") @CommandPermission("tne.money.withdraw") public void onWithdraw(BukkitCommandActor sender, @Named("amount") PercentBigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onWithdraw(new BukkitCMDSource(sender), amount, currency, region); } } \ No newline at end of file diff --git a/Bukkit/src/net/tnemc/bukkit/command/ShortCommands.java b/Bukkit/src/net/tnemc/bukkit/command/ShortCommands.java index 3f61fbe3..e8cb732e 100644 --- a/Bukkit/src/net/tnemc/bukkit/command/ShortCommands.java +++ b/Bukkit/src/net/tnemc/bukkit/command/ShortCommands.java @@ -40,59 +40,66 @@ */ public class ShortCommands { - @Command({"givemoney", "givebal"}) + @Command({ "givemoney", "givebal" }) @Usage("Money.Give.Arguments") @Description("Money.Give.Description") @CommandPermission("tne.money.give") public void onGive(BukkitCommandActor sender, @Named("account") Account player, @Named("amount") PercentBigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onGive(new BukkitCMDSource(sender), player, amount, region, currency); } - @Command({"givenote", "+note", "addnote"}) + @Command({ "givenote", "+note", "addnote" }) @Usage("Money.GiveNote.Arguments") @Description("Money.GiveNote.Description") @CommandPermission("tne.money.givenote") public void onGiveNote(BukkitCommandActor sender, Account player, @Named("amount") BigDecimal amount, @Default("") @Named("currency") Currency currency) { + net.tnemc.core.command.MoneyCommand.onGiveNote(new BukkitCMDSource(sender), player, amount, currency); } - @Command({"pay"}) + @Command({ "pay" }) @Usage("Money.Pay.Arguments") @Description("Money.Pay.Description") @CommandPermission("tne.money.pay") public void onPay(BukkitCommandActor sender, @Named("account") Account player, @Named("amount") PercentBigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("") String from) { + net.tnemc.core.command.MoneyCommand.onPay(new BukkitCMDSource(sender), player, amount, currency, from); } - @Command({"setmoney", "setbal"}) + @Command({ "setmoney", "setbal" }) @Usage("Money.Set.Arguments") @Description("Money.Set.Description") @CommandPermission("tne.money.set") public void onSet(BukkitCommandActor sender, @Named("account") Account player, @Named("amount") BigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onSet(new BukkitCMDSource(sender), player, amount, region, currency); } - @Command({"takemoney", "takebal"}) + @Command({ "takemoney", "takebal" }) @Usage("Money.Take.Arguments") @Description("Money.Take.Description") @CommandPermission("tne.money.take") public void onTake(BukkitCommandActor sender, @Named("account") Account player, @Named("amount") PercentBigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onTake(new BukkitCMDSource(sender), player, amount, region, currency); } - @Command({"baltop"}) + @Command({ "baltop" }) @Usage("Money.Top.Arguments") @Description("Money.Top.Description") @CommandPermission("tne.money.top") public void onTop(BukkitCommandActor sender, @Default("1") @Named("page") Integer page, @Default("") @Named("currency") Currency currency, @Default("false") Boolean refresh) { + net.tnemc.core.command.MoneyCommand.onTop(new BukkitCMDSource(sender), page, currency, refresh); } - @Command({"transactions"}) + @Command({ "transactions" }) @Usage("Transaction.History.Arguments") @Description("Transaction.History.Description") @CommandPermission("tne.transaction.history") public void history(BukkitCommandActor sender, @Default("1") int page, @Default("world-113") @Named("region") String region, @Default("SELF_ACCOUNT") Account account) { + net.tnemc.core.command.TransactionCommand.history(new BukkitCMDSource(sender), page, region, account); } } \ No newline at end of file diff --git a/Bukkit/src/net/tnemc/bukkit/command/TransactionCommand.java b/Bukkit/src/net/tnemc/bukkit/command/TransactionCommand.java index 65effd79..0ac55699 100644 --- a/Bukkit/src/net/tnemc/bukkit/command/TransactionCommand.java +++ b/Bukkit/src/net/tnemc/bukkit/command/TransactionCommand.java @@ -17,6 +17,7 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . */ + import net.tnemc.core.account.Account; import net.tnemc.core.command.BaseCommand; import net.tnemc.plugincore.bukkit.impl.BukkitCMDSource; @@ -39,46 +40,51 @@ * @author creatorfromhell * @since 0.1.2.0 */ -@Command({"transaction", "trans", "receipt"}) +@Command({ "transaction", "trans", "receipt" }) public class TransactionCommand { - @Subcommand({"help", "?"}) - @DefaultFor({"transaction", "trans", "receipt"}) + @Subcommand({ "help", "?" }) + @DefaultFor({ "transaction", "trans", "receipt" }) @Usage("Help.Arguments") @Description("Help.Description") public void help(BukkitCommandActor actor, CommandHelp helpEntries, @Default("1") int page) { + BaseCommand.help(new BukkitCMDSource(actor), helpEntries, page); } - @Subcommand({"away", "gone", "afk", "afg"}) + @Subcommand({ "away", "gone", "afk", "afg" }) @Usage("Transaction.Away.Arguments") @Description("Transaction.Away.Description") @CommandPermission("tne.transaction.away") public void away(BukkitCommandActor sender, @Default("1") int page) { + net.tnemc.core.command.TransactionCommand.away(new BukkitCMDSource(sender), page); } - @Subcommand({"history", "list", "hist", "archive"}) + @Subcommand({ "history", "list", "hist", "archive" }) @Usage("Transaction.History.Arguments") @Description("Transaction.History.Description") @CommandPermission("tne.transaction.history") public void history(BukkitCommandActor sender, @Default("1") int page, @Default("world-113") @Named("region") String region, @Default("SELF_ACCOUNT") Account account) { + net.tnemc.core.command.TransactionCommand.history(new BukkitCMDSource(sender), page, region, account); } - @Subcommand({"info", "i", "about", "brief"}) + @Subcommand({ "info", "i", "about", "brief" }) @Usage("Transaction.Info.Arguments") @Description("Transaction.Info.Description") @CommandPermission("tne.info.history") public void info(BukkitCommandActor sender, UUID uuid) { + net.tnemc.core.command.TransactionCommand.info(new BukkitCMDSource(sender), uuid); } - @Subcommand({"void", "retract", "undo"}) + @Subcommand({ "void", "retract", "undo" }) @Usage("Transaction.Void.Arguments") @Description("Transaction.Void.Description") @CommandPermission("tne.void.history") public void voidT(BukkitCommandActor sender, Account account, UUID uuid) { + net.tnemc.core.command.TransactionCommand.voidT(new BukkitCMDSource(sender), account, uuid); } } diff --git a/Bukkit/src/net/tnemc/bukkit/depend/faction/FactionAccount.java b/Bukkit/src/net/tnemc/bukkit/depend/faction/FactionAccount.java index 3103e2f2..4f676775 100644 --- a/Bukkit/src/net/tnemc/bukkit/depend/faction/FactionAccount.java +++ b/Bukkit/src/net/tnemc/bukkit/depend/faction/FactionAccount.java @@ -32,6 +32,7 @@ public class FactionAccount extends NonPlayerAccount { public FactionAccount(UUID identifier, String name) { + super(identifier, name); } @@ -42,6 +43,7 @@ public FactionAccount(UUID identifier, String name) { */ @Override public String type() { + return "faction"; } } \ No newline at end of file diff --git a/Bukkit/src/net/tnemc/bukkit/depend/faction/FactionCheck.java b/Bukkit/src/net/tnemc/bukkit/depend/faction/FactionCheck.java index 57fc9181..6762c31d 100644 --- a/Bukkit/src/net/tnemc/bukkit/depend/faction/FactionCheck.java +++ b/Bukkit/src/net/tnemc/bukkit/depend/faction/FactionCheck.java @@ -32,14 +32,15 @@ public class FactionCheck implements AccountTypeCheck { /** - * Returns our check function that should be used to check if a given String identifier, usually name, - * is valid for this account type. + * Returns our check function that should be used to check if a given String identifier, usually + * name, is valid for this account type. * * @return Our function that should be used to check if a given String identifier, usually name, * is valid for this account type. */ @Override public Function check() { - return value -> value.toLowerCase().contains(BukkitConfig.yaml().getString("Bukkit.Faction")); + + return value->value.toLowerCase().contains(BukkitConfig.yaml().getString("Bukkit.Faction")); } } \ No newline at end of file diff --git a/Bukkit/src/net/tnemc/bukkit/depend/faction/FactionHandler.java b/Bukkit/src/net/tnemc/bukkit/depend/faction/FactionHandler.java index 9e4d5d96..c7500ce0 100644 --- a/Bukkit/src/net/tnemc/bukkit/depend/faction/FactionHandler.java +++ b/Bukkit/src/net/tnemc/bukkit/depend/faction/FactionHandler.java @@ -29,6 +29,7 @@ public class FactionHandler { public static void addTypes() { + TNECore.eco().account().addAccountType(FactionAccount.class, new FactionCheck().check()); } } \ No newline at end of file diff --git a/Bukkit/src/net/tnemc/bukkit/depend/towny/NationAccount.java b/Bukkit/src/net/tnemc/bukkit/depend/towny/NationAccount.java index 24b4b16c..5b881766 100644 --- a/Bukkit/src/net/tnemc/bukkit/depend/towny/NationAccount.java +++ b/Bukkit/src/net/tnemc/bukkit/depend/towny/NationAccount.java @@ -33,6 +33,7 @@ public class NationAccount extends NonPlayerAccount { public NationAccount(UUID identifier, String name) { + super(identifier, name); //this.owner = Objects.requireNonNull(TownyAPI.getInstance().getNation(name)).getKing().getUUID(); } @@ -44,6 +45,7 @@ public NationAccount(UUID identifier, String name) { */ @Override public String type() { + return "nation"; } diff --git a/Bukkit/src/net/tnemc/bukkit/depend/towny/NationCheck.java b/Bukkit/src/net/tnemc/bukkit/depend/towny/NationCheck.java index 84c3ed23..11a064db 100644 --- a/Bukkit/src/net/tnemc/bukkit/depend/towny/NationCheck.java +++ b/Bukkit/src/net/tnemc/bukkit/depend/towny/NationCheck.java @@ -30,16 +30,18 @@ * @since 0.1.2.0 */ public class NationCheck implements AccountTypeCheck { + /** - * Returns our check function that should be used to check if a given String identifier, usually name, - * is valid for this account type. + * Returns our check function that should be used to check if a given String identifier, usually + * name, is valid for this account type. * * @return Our function that should be used to check if a given String identifier, usually name, * is valid for this account type. */ @Override public Function check() { - return value -> { + + return value->{ try { return value.contains(TownySettings.getNationAccountPrefix()); } catch(Exception e) { diff --git a/Bukkit/src/net/tnemc/bukkit/depend/towny/TownAccount.java b/Bukkit/src/net/tnemc/bukkit/depend/towny/TownAccount.java index 03e10a8d..87502eac 100644 --- a/Bukkit/src/net/tnemc/bukkit/depend/towny/TownAccount.java +++ b/Bukkit/src/net/tnemc/bukkit/depend/towny/TownAccount.java @@ -33,6 +33,7 @@ public class TownAccount extends NonPlayerAccount { public TownAccount(UUID identifier, String name) { + super(identifier, name); //this.owner = Objects.requireNonNull(TownyAPI.getInstance().getTown(name)).getMayor().getUUID(); } @@ -44,11 +45,13 @@ public TownAccount(UUID identifier, String name) { */ @Override public String type() { + return "town"; } @Override public UUID generateIdentifier(String name) { + try { return Objects.requireNonNull(TownyAPI.getInstance().getTown(name)).getUUID(); } catch(Exception ignore) { diff --git a/Bukkit/src/net/tnemc/bukkit/depend/towny/TownCheck.java b/Bukkit/src/net/tnemc/bukkit/depend/towny/TownCheck.java index f13bd63e..625f9a03 100644 --- a/Bukkit/src/net/tnemc/bukkit/depend/towny/TownCheck.java +++ b/Bukkit/src/net/tnemc/bukkit/depend/towny/TownCheck.java @@ -32,15 +32,16 @@ public class TownCheck implements AccountTypeCheck { /** - * Returns our check function that should be used to check if a given String identifier, usually name, - * is valid for this account type. + * Returns our check function that should be used to check if a given String identifier, usually + * name, is valid for this account type. * * @return Our function that should be used to check if a given String identifier, usually name, * is valid for this account type. */ @Override public Function check() { - return value -> { + + return value->{ try { return value.contains(TownySettings.getTownAccountPrefix()); } catch(Exception e) { diff --git a/Bukkit/src/net/tnemc/bukkit/depend/towny/TownyHandler.java b/Bukkit/src/net/tnemc/bukkit/depend/towny/TownyHandler.java index 8d173a01..7144086b 100644 --- a/Bukkit/src/net/tnemc/bukkit/depend/towny/TownyHandler.java +++ b/Bukkit/src/net/tnemc/bukkit/depend/towny/TownyHandler.java @@ -29,6 +29,7 @@ public class TownyHandler { public static void addTypes() { + TNECore.eco().account().addAccountType(TownAccount.class, new TownCheck().check()); TNECore.eco().account().addAccountType(NationAccount.class, new NationCheck().check()); } diff --git a/Bukkit/src/net/tnemc/bukkit/hook/economy/TNEVault.java b/Bukkit/src/net/tnemc/bukkit/hook/economy/TNEVault.java index 5b2e2347..128825d5 100644 --- a/Bukkit/src/net/tnemc/bukkit/hook/economy/TNEVault.java +++ b/Bukkit/src/net/tnemc/bukkit/hook/economy/TNEVault.java @@ -50,46 +50,55 @@ public class TNEVault implements Economy { /** * Checks if economy method is enabled. + * * @return Success or Failure */ public boolean isEnabled() { + return true; } /** * Gets name of economy method + * * @return Name of Economy Method */ public String getName() { + return "TheNewEconomy"; } /** * Returns true if the given implementation supports banks. + * * @return true if the implementation supports banks */ public boolean hasBankSupport() { + return false; } /** - * Some economy plugins round off after a certain number of digits. - * This function returns the number of digits the plugin keeps - * or -1 if no rounding occurs. + * Some economy plugins round off after a certain number of digits. This function returns the + * number of digits the plugin keeps or -1 if no rounding occurs. + * * @return number of digits after the decimal point kept */ public int fractionalDigits() { + return TNECore.eco().currency().getDefaultCurrency().getDecimalPlaces(); } /** - * Format amount into a human-readable String This provides translation into - * economy specific formatting to improve consistency between plugins. + * Format amount into a human-readable String This provides translation into economy specific + * formatting to improve consistency between plugins. * * @param amount to format + * * @return Human-readable string describing amount */ public String format(double amount) { + return CurrencyFormatter.format(null, new HoldingsEntry(TNECore.eco().region().defaultRegion(), TNECore.eco().currency().getDefaultCurrency().getUid(), BigDecimal.valueOf(amount), @@ -98,44 +107,48 @@ public String format(double amount) { } /** - * Returns the name of the currency in plural form. - * If the economy being used does not support currency names then an empty string will be returned. + * Returns the name of the currency in plural form. If the economy being used does not support + * currency names then an empty string will be returned. * * @return name of the currency (plural) */ public String currencyNamePlural() { + return TNECore.eco().currency().getDefaultCurrency().getDisplayPlural(); } /** - * Returns the name of the currency in singular form. - * If the economy being used does not support currency names then an empty string will be returned. + * Returns the name of the currency in singular form. If the economy being used does not support + * currency names then an empty string will be returned. * * @return name of the currency (singular) */ public String currencyNameSingular() { + return TNECore.eco().currency().getDefaultCurrency().getDisplay(); } /** - * * @deprecated As of VaultAPI 1.4 use {@link #hasAccount(OfflinePlayer)} instead. */ @Deprecated public boolean hasAccount(String name) { + return hasAccount(name, "ahoy matey"); } /** - * Checks if this player has an account on the server yet - * This will always return true if the player has joined the server at least once - * as all major economy plugins auto-generate a player account when the player joins the server + * Checks if this player has an account on the server yet This will always return true if the + * player has joined the server at least once as all major economy plugins auto-generate a player + * account when the player joins the server * * @param player to check + * * @return if the player has an account */ public boolean hasAccount(OfflinePlayer player) { + return hasAccount(player, "woah"); } @@ -144,19 +157,22 @@ public boolean hasAccount(OfflinePlayer player) { */ @Deprecated public boolean hasAccount(String name, String world) { + return TNECore.eco().account().findAccount(name).isPresent(); } /** - * Checks if this player has an account on the server yet on the given world - * This will always return true if the player has joined the server at least once - * as all major economy plugins auto-generate a player account when the player joins the server + * Checks if this player has an account on the server yet on the given world This will always + * return true if the player has joined the server at least once as all major economy plugins + * auto-generate a player account when the player joins the server * * @param player to check in the world - * @param world world-specific account + * @param world world-specific account + * * @return if the player has an account */ public boolean hasAccount(OfflinePlayer player, String world) { + return hasAccount(player.getUniqueId().toString(), world); } @@ -165,6 +181,7 @@ public boolean hasAccount(OfflinePlayer player, String world) { */ @Deprecated public double getBalance(String name) { + return getBalance(name, TNECore.eco().region().defaultRegion()); } @@ -172,9 +189,11 @@ public double getBalance(String name) { * Gets balance of a player * * @param player of the player + * * @return Amount currently held in players account */ public double getBalance(OfflinePlayer player) { + return getBalance(player.getUniqueId().toString(), TNECore.eco().region().defaultRegion()); } @@ -183,6 +202,7 @@ public double getBalance(OfflinePlayer player) { */ @Deprecated public double getBalance(String name, String world) { + PluginCore.log().debug("Vault Balance call. Name: " + name + " World: " + world, DebugLevel.STANDARD); final Optional account = TNECore.eco().account().findAccount(name); @@ -191,7 +211,7 @@ public double getBalance(String name, String world) { PluginCore.log().debug("==== Vault balance call with color code! ====", DebugLevel.DEVELOPER); final StackTraceElement[] elements = Thread.currentThread().getStackTrace(); - for (int i = 1; i < elements.length; i++) { + for(int i = 1; i < elements.length; i++) { final StackTraceElement s = elements[i]; PluginCore.log().debug("\tat " + s.getClassName() + "." + s.getMethodName() + "(" + s.getFileName() + ":" + s.getLineNumber() + ")", DebugLevel.DEVELOPER); } @@ -210,13 +230,16 @@ public double getBalance(String name, String world) { } /** - * Gets balance of a player on the specified world. - * IMPLEMENTATION SPECIFIC - if an economy plugin does not support this the global balance will be returned. + * Gets balance of a player on the specified world. IMPLEMENTATION SPECIFIC - if an economy plugin + * does not support this the global balance will be returned. + * * @param player to check - * @param world name of the world + * @param world name of the world + * * @return Amount currently held in players account */ public double getBalance(OfflinePlayer player, String world) { + final Optional account = TNECore.eco().account().findAccount(player.getUniqueId().toString()); if(player.getName() != null && account.isEmpty()) { return getBalance(player.getName(), world); @@ -229,6 +252,7 @@ public double getBalance(OfflinePlayer player, String world) { */ @Deprecated public boolean has(String name, double amount) { + return has(name, TNECore.eco().region().defaultRegion(), amount); } @@ -237,9 +261,11 @@ public boolean has(String name, double amount) { * * @param player to check * @param amount to check for + * * @return True if player has amount, False else wise */ public boolean has(OfflinePlayer player, double amount) { + final Optional account = TNECore.eco().account().findAccount(player.getUniqueId().toString()); if(player.getName() != null && account.isEmpty()) { return has(player.getName(), TNECore.eco().region().defaultRegion(), amount); @@ -252,21 +278,25 @@ public boolean has(OfflinePlayer player, double amount) { */ @Deprecated public boolean has(String name, String world, double amount) { + final Optional account = TNECore.eco().account().findAccount(name); return account.filter(value->value.getHoldingsTotal(world, TNECore.eco().currency().getDefaultCurrency(world).getUid()) - .compareTo(BigDecimal.valueOf(amount)) >= 0).isPresent(); + .compareTo(BigDecimal.valueOf(amount)) >= 0).isPresent(); } /** * Checks if the player account has the amount in a given world - DO NOT USE NEGATIVE AMOUNTS - * IMPLEMENTATION SPECIFIC - if an economy plugin does not support this the global balance will be returned. + * IMPLEMENTATION SPECIFIC - if an economy plugin does not support this the global balance will be + * returned. * * @param player to check - * @param world to check with + * @param world to check with * @param amount to check for + * * @return True if player has amount, False else wise */ public boolean has(OfflinePlayer player, String world, double amount) { + final Optional account = TNECore.eco().account().findAccount(player.getUniqueId().toString()); if(player.getName() != null && account.isEmpty()) { return has(player.getName(), world, amount); @@ -279,6 +309,7 @@ public boolean has(OfflinePlayer player, String world, double amount) { */ @Deprecated public EconomyResponse withdrawPlayer(String name, double amount) { + return withdrawPlayer(name, TNECore.eco().region().defaultRegion(), amount); } @@ -287,9 +318,11 @@ public EconomyResponse withdrawPlayer(String name, double amount) { * * @param player to withdraw from * @param amount Amount to withdraw + * * @return Detailed response of transaction */ public EconomyResponse withdrawPlayer(OfflinePlayer player, double amount) { + final EconomyResponse response = withdrawPlayer(player.getUniqueId().toString(), TNECore.eco().region().defaultRegion(), amount); PluginCore.log().debug("Player ID: " + player.getUniqueId()); @@ -303,7 +336,8 @@ public EconomyResponse withdrawPlayer(OfflinePlayer player, double amount) { } /** - * @deprecated As of VaultAPI 1.4 use {@link #withdrawPlayer(OfflinePlayer, String, double)} instead. + * @deprecated As of VaultAPI 1.4 use {@link #withdrawPlayer(OfflinePlayer, String, double)} + * instead. */ @Deprecated public EconomyResponse withdrawPlayer(String name, String world, double amount) { @@ -312,7 +346,7 @@ public EconomyResponse withdrawPlayer(String name, String world, double amount) if(account.isEmpty()) { return new EconomyResponse(0.0, 0.0, - EconomyResponse.ResponseType.FAILURE, "Unable to locate associated account."); + EconomyResponse.ResponseType.FAILURE, "Unable to locate associated account."); } final HoldingsModifier modifier = new HoldingsModifier(world, @@ -320,9 +354,9 @@ public EconomyResponse withdrawPlayer(String name, String world, double amount) BigDecimal.valueOf(amount)); final Transaction transaction = new Transaction("take") - .to(account.get(), modifier.counter()) - .processor(EconomyManager.baseProcessor()) - .source(new PluginSource("Vault")); + .to(account.get(), modifier.counter()) + .processor(EconomyManager.baseProcessor()) + .source(new PluginSource("Vault")); try { TransactionResult result = transaction.process(); @@ -337,14 +371,17 @@ public EconomyResponse withdrawPlayer(String name, String world, double amount) } /** - * Withdraw an amount from a player on a given world - DO NOT USE NEGATIVE AMOUNTS - * IMPLEMENTATION SPECIFIC - if an economy plugin does not support this the global balance will be returned. + * Withdraw an amount from a player on a given world - DO NOT USE NEGATIVE AMOUNTS IMPLEMENTATION + * SPECIFIC - if an economy plugin does not support this the global balance will be returned. + * * @param player to withdraw from - * @param world - name of the world + * @param world - name of the world * @param amount Amount to withdraw + * * @return Detailed response of transaction */ public EconomyResponse withdrawPlayer(OfflinePlayer player, String world, double amount) { + final EconomyResponse response = withdrawPlayer(player.getUniqueId().toString(), world, amount); if(response.transactionSuccess() || player.getName() == null) { return response; @@ -357,6 +394,7 @@ public EconomyResponse withdrawPlayer(OfflinePlayer player, String world, double */ @Deprecated public EconomyResponse depositPlayer(String name, double amount) { + return depositPlayer(name, TNECore.eco().region().defaultRegion(), amount); } @@ -365,9 +403,11 @@ public EconomyResponse depositPlayer(String name, double amount) { * * @param player to deposit to * @param amount Amount to deposit + * * @return Detailed response of transaction */ public EconomyResponse depositPlayer(OfflinePlayer player, double amount) { + final EconomyResponse response = depositPlayer(player.getUniqueId().toString(), TNECore.eco().region().defaultRegion(), amount); if(response.transactionSuccess() || player.getName() == null) { return response; @@ -376,7 +416,8 @@ public EconomyResponse depositPlayer(OfflinePlayer player, double amount) { } /** - * @deprecated As of VaultAPI 1.4 use {@link #depositPlayer(OfflinePlayer, String, double)} instead. + * @deprecated As of VaultAPI 1.4 use {@link #depositPlayer(OfflinePlayer, String, double)} + * instead. */ @Deprecated public EconomyResponse depositPlayer(String name, String world, double amount) { @@ -385,7 +426,7 @@ public EconomyResponse depositPlayer(String name, String world, double amount) { if(account.isEmpty()) { return new EconomyResponse(0.0, 0.0, - EconomyResponse.ResponseType.FAILURE, "Unable to locate associated account."); + EconomyResponse.ResponseType.FAILURE, "Unable to locate associated account."); } final HoldingsModifier modifier = new HoldingsModifier(world, @@ -394,9 +435,9 @@ public EconomyResponse depositPlayer(String name, String world, double amount) { final Transaction transaction = new Transaction("give") - .to(account.get(), modifier) - .processor(EconomyManager.baseProcessor()) - .source(new PluginSource("Vault")); + .to(account.get(), modifier) + .processor(EconomyManager.baseProcessor()) + .source(new PluginSource("Vault")); try { TransactionResult result = transaction.process(); @@ -411,15 +452,17 @@ public EconomyResponse depositPlayer(String name, String world, double amount) { } /** - * Deposit an amount to a player - DO NOT USE NEGATIVE AMOUNTS - * IMPLEMENTATION SPECIFIC - if an economy plugin does not support this the global balance will be returned. + * Deposit an amount to a player - DO NOT USE NEGATIVE AMOUNTS IMPLEMENTATION SPECIFIC - if an + * economy plugin does not support this the global balance will be returned. * * @param player to deposit to - * @param world name of the world + * @param world name of the world * @param amount Amount to deposit + * * @return Detailed response of transaction */ public EconomyResponse depositPlayer(OfflinePlayer player, String world, double amount) { + final EconomyResponse response = depositPlayer(player.getUniqueId().toString(), world, amount); if(response.transactionSuccess() || player.getName() == null) { return response; @@ -432,67 +475,83 @@ public EconomyResponse depositPlayer(OfflinePlayer player, String world, double */ @Deprecated public EconomyResponse createBank(String name, String player) { + return new EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, ""); } /** * Creates a bank account with the specified name and the player as the owner - * @param name of account + * + * @param name of account * @param player the account should be linked to + * * @return EconomyResponse Object */ public EconomyResponse createBank(String name, OfflinePlayer player) { + return new EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, ""); } /** * Deletes a bank account with the specified name. + * * @param name of the back to delete + * * @return if the operation completed successfully */ public EconomyResponse deleteBank(String name) { + return new EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, ""); } /** * Returns the amount the bank has + * * @param name of the account + * * @return EconomyResponse Object */ public EconomyResponse bankBalance(String name) { + return new EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, ""); } /** * Returns true or false whether the bank has the amount specified - DO NOT USE NEGATIVE AMOUNTS * - * @param name of the account + * @param name of the account * @param amount to check for + * * @return EconomyResponse Object */ public EconomyResponse bankHas(String name, double amount) { + return new EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, ""); } /** * Withdraw an amount from a bank account - DO NOT USE NEGATIVE AMOUNTS * - * @param name of the account + * @param name of the account * @param amount to withdraw + * * @return EconomyResponse Object */ public EconomyResponse bankWithdraw(String name, double amount) { + return new EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, ""); } /** * Deposit an amount into a bank account - DO NOT USE NEGATIVE AMOUNTS * - * @param name of the account + * @param name of the account * @param amount to deposit + * * @return EconomyResponse Object */ public EconomyResponse bankDeposit(String name, double amount) { + return new EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, ""); } @@ -501,17 +560,20 @@ public EconomyResponse bankDeposit(String name, double amount) { */ @Deprecated public EconomyResponse isBankOwner(String name, String playerName) { + return new EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, ""); } /** * Check if a player is the owner of a bank account * - * @param name of the account + * @param name of the account * @param player to check for ownership + * * @return EconomyResponse Object */ public EconomyResponse isBankOwner(String name, OfflinePlayer player) { + return new EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, ""); } @@ -520,25 +582,30 @@ public EconomyResponse isBankOwner(String name, OfflinePlayer player) { */ @Deprecated public EconomyResponse isBankMember(String name, String playerName) { + return new EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, ""); } /** * Check if the player is a member of the bank account * - * @param name of the account + * @param name of the account * @param player to check membership + * * @return EconomyResponse Object */ public EconomyResponse isBankMember(String name, OfflinePlayer player) { + return new EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, ""); } /** * Gets the list of banks + * * @return the List of Banks */ public List getBanks() { + return new ArrayList<>(); } @@ -547,20 +614,25 @@ public List getBanks() { */ @Deprecated public boolean createPlayerAccount(String name) { + return createPlayerAccount(name, "this doesn't matter."); } /** * Attempts to create a player account for the given player + * * @param player OfflinePlayer + * * @return if the account creation was successful */ public boolean createPlayerAccount(OfflinePlayer player) { + return createPlayerAccount(player, "this doesn't matter."); } /** - * @deprecated As of VaultAPI 1.4 use {{@link #createPlayerAccount(OfflinePlayer, String)} instead. + * @deprecated As of VaultAPI 1.4 use {{@link #createPlayerAccount(OfflinePlayer, String)} + * instead. */ @Deprecated public boolean createPlayerAccount(String name, String world) { @@ -570,10 +642,12 @@ public boolean createPlayerAccount(String name, String world) { } /** - * Attempts to create a player account for the given player on the specified world - * IMPLEMENTATION SPECIFIC - if an economy plugin does not support this then false will always be returned. + * Attempts to create a player account for the given player on the specified world IMPLEMENTATION + * SPECIFIC - if an economy plugin does not support this then false will always be returned. + * * @param player OfflinePlayer - * @param world String name of the world + * @param world String name of the world + * * @return if the account creation was successful */ public boolean createPlayerAccount(OfflinePlayer player, String world) { @@ -590,7 +664,7 @@ public boolean createPlayerAccount(OfflinePlayer player, String world) { PluginCore.log().debug("==== Vault create call with color code! ====", DebugLevel.DEVELOPER); final StackTraceElement[] elements = Thread.currentThread().getStackTrace(); - for (int i = 1; i < elements.length; i++) { + for(int i = 1; i < elements.length; i++) { final StackTraceElement s = elements[i]; PluginCore.log().debug("\tat " + s.getClassName() + "." + s.getMethodName() + "(" + s.getFileName() + ":" + s.getLineNumber() + ")", DebugLevel.DEVELOPER); } @@ -602,6 +676,7 @@ public boolean createPlayerAccount(OfflinePlayer player, String world) { } private EconomyResponse.ResponseType fromResult(@Nullable TransactionResult result) { + if(result != null && result.isSuccessful()) { return EconomyResponse.ResponseType.SUCCESS; } diff --git a/Bukkit/src/net/tnemc/bukkit/hook/economy/TNEVaultUnlocked.java b/Bukkit/src/net/tnemc/bukkit/hook/economy/TNEVaultUnlocked.java index 673b535e..7e533737 100644 --- a/Bukkit/src/net/tnemc/bukkit/hook/economy/TNEVaultUnlocked.java +++ b/Bukkit/src/net/tnemc/bukkit/hook/economy/TNEVaultUnlocked.java @@ -50,6 +50,7 @@ * @since 0.1.2.0 */ public class TNEVaultUnlocked implements Economy { + /** * Checks if economy plugin is enabled. * @@ -57,6 +58,7 @@ public class TNEVaultUnlocked implements Economy { */ @Override public boolean isEnabled() { + return true; } @@ -67,6 +69,7 @@ public boolean isEnabled() { */ @Override public String getName() { + return "TheNewEconomy"; } @@ -77,6 +80,7 @@ public String getName() { */ @Override public boolean hasBankSupport() { + return false; } @@ -87,6 +91,7 @@ public boolean hasBankSupport() { */ @Override public boolean hasMultiCurrencySupport() { + return true; } @@ -99,6 +104,7 @@ public boolean hasMultiCurrencySupport() { */ @Override public int fractionalDigits() { + return TNECore.eco().currency().getDefaultCurrency().getDecimalPlaces(); } @@ -112,10 +118,11 @@ public int fractionalDigits() { */ @Override public String format(BigDecimal amount) { + return CurrencyFormatter.format(null, new HoldingsEntry(TNECore.eco().region().defaultRegion(), - TNECore.eco().currency().getDefaultCurrency().getUid(), - amount, - EconomyManager.NORMAL + TNECore.eco().currency().getDefaultCurrency().getUid(), + amount, + EconomyManager.NORMAL )); } @@ -130,10 +137,11 @@ public String format(BigDecimal amount) { */ @Override public String format(BigDecimal amount, String currency) { + return CurrencyFormatter.format(null, new HoldingsEntry(TNECore.eco().region().defaultRegion(), - TNECore.eco().currency().getDefaultCurrency().getUid(), - amount, - EconomyManager.NORMAL + TNECore.eco().currency().getDefaultCurrency().getUid(), + amount, + EconomyManager.NORMAL )); } @@ -146,6 +154,7 @@ public String format(BigDecimal amount, String currency) { */ @Override public boolean hasCurrency(String currency) { + return TNECore.eco().currency().findCurrency(currency).isPresent(); } @@ -157,6 +166,7 @@ public boolean hasCurrency(String currency) { */ @Override public String defaultCurrency() { + return TNECore.eco().currency().getDefaultCurrency().getIdentifier(); } @@ -168,6 +178,7 @@ public String defaultCurrency() { */ @Override public String defaultCurrencyNamePlural() { + return TNECore.eco().currency().getDefaultCurrency().getDisplayPlural(); } @@ -179,6 +190,7 @@ public String defaultCurrencyNamePlural() { */ @Override public String defaultCurrencyNameSingular() { + return TNECore.eco().currency().getDefaultCurrency().getDisplay(); } @@ -191,6 +203,7 @@ public String defaultCurrencyNameSingular() { */ @Override public Collection currencies() { + return TNECore.eco().currency().getCurIDMap().keySet(); } @@ -204,6 +217,7 @@ public Collection currencies() { */ @Override public boolean createAccount(UUID uuid, String name) { + return TNECore.eco().account().createAccount(uuid.toString(), name).getResponse().success(); } @@ -219,6 +233,7 @@ public boolean createAccount(UUID uuid, String name) { */ @Override public boolean createAccount(UUID uuid, String name, String worldName) { + return createAccount(uuid, name); } @@ -232,6 +247,7 @@ public boolean createAccount(UUID uuid, String name, String worldName) { */ @Override public Map getUUIDNameMap() { + return Map.of(); } @@ -245,6 +261,7 @@ public Map getUUIDNameMap() { */ @Override public Optional getAccountName(UUID uuid) { + final Optional accountOpt = TNECore.eco().account().findAccount(uuid); return accountOpt.map(Account::getName); } @@ -258,6 +275,7 @@ public Optional getAccountName(UUID uuid) { */ @Override public boolean hasAccount(UUID uuid) { + return TNECore.eco().account().findAccount(uuid.toString()).isPresent(); } @@ -271,6 +289,7 @@ public boolean hasAccount(UUID uuid) { */ @Override public boolean hasAccount(UUID uuid, String worldName) { + return hasAccount(uuid); } @@ -285,6 +304,7 @@ public boolean hasAccount(UUID uuid, String worldName) { */ @Override public boolean renameAccount(UUID uuid, String name) { + return false; } @@ -298,6 +318,7 @@ public boolean renameAccount(UUID uuid, String name) { */ @Override public BigDecimal getBalance(String pluginName, UUID uuid) { + return getBalance(pluginName, uuid, TNECore.eco().region().defaultRegion(), defaultCurrency()); } @@ -313,6 +334,7 @@ public BigDecimal getBalance(String pluginName, UUID uuid) { */ @Override public BigDecimal getBalance(String pluginName, UUID uuid, String world) { + return getBalance(pluginName, uuid, world, defaultCurrency()); } @@ -329,6 +351,7 @@ public BigDecimal getBalance(String pluginName, UUID uuid, String world) { */ @Override public BigDecimal getBalance(String pluginName, UUID uuid, String world, String currency) { + final Optional account = TNECore.eco().account().findAccount(uuid.toString()); final Optional currencyOpt = TNECore.eco().currency().findCurrency(currency); @@ -353,6 +376,7 @@ public BigDecimal getBalance(String pluginName, UUID uuid, String world, String */ @Override public boolean has(String pluginName, UUID uuid, BigDecimal amount) { + return has(pluginName, uuid, TNECore.eco().region().defaultRegion(), defaultCurrency(), amount); } @@ -370,6 +394,7 @@ public boolean has(String pluginName, UUID uuid, BigDecimal amount) { */ @Override public boolean has(String pluginName, UUID uuid, String worldName, BigDecimal amount) { + return has(pluginName, uuid, worldName, defaultCurrency(), amount); } @@ -388,11 +413,12 @@ public boolean has(String pluginName, UUID uuid, String worldName, BigDecimal am */ @Override public boolean has(String pluginName, UUID uuid, String worldName, String currency, BigDecimal amount) { + final Optional account = TNECore.eco().account().findAccount(uuid.toString()); final Optional currencyOpt = TNECore.eco().currency().findCurrency(currency); return currencyOpt.filter(currency1->account.filter(value->value.getHoldingsTotal(worldName, currency1.getUid()) - .compareTo(amount) >= 0).isPresent()).isPresent(); + .compareTo(amount) >= 0).isPresent()).isPresent(); } @@ -403,11 +429,13 @@ public boolean has(String pluginName, UUID uuid, String worldName, String curren * @param uuid the UUID associated with the account to withdraw from. * @param amount Amount to withdraw. * - * @return {@link EconomyResponse} which includes the Economy plugin's {@link EconomyResponse.ResponseType} as to - * whether the transaction was a Success, Failure, Unsupported. + * @return {@link EconomyResponse} which includes the Economy plugin's + * {@link EconomyResponse.ResponseType} as to whether the transaction was a Success, Failure, + * Unsupported. */ @Override public EconomyResponse withdraw(String pluginName, UUID uuid, BigDecimal amount) { + return withdraw(pluginName, uuid, TNECore.eco().region().defaultRegion(), defaultCurrency(), amount); } @@ -426,6 +454,7 @@ public EconomyResponse withdraw(String pluginName, UUID uuid, BigDecimal amount) */ @Override public EconomyResponse withdraw(String pluginName, UUID uuid, String worldName, BigDecimal amount) { + return withdraw(pluginName, uuid, worldName, defaultCurrency(), amount); } @@ -445,16 +474,17 @@ public EconomyResponse withdraw(String pluginName, UUID uuid, String worldName, */ @Override public EconomyResponse withdraw(String pluginName, UUID uuid, String worldName, String currency, BigDecimal amount) { + final Optional account = TNECore.eco().account().findAccount(uuid.toString()); if(account.isEmpty()) { return new EconomyResponse(BigDecimal.ZERO, BigDecimal.ZERO, - EconomyResponse.ResponseType.FAILURE, "Unable to locate associated account."); + EconomyResponse.ResponseType.FAILURE, "Unable to locate associated account."); } final HoldingsModifier modifier = new HoldingsModifier(worldName, - TNECore.eco().currency().getDefaultCurrency(worldName).getUid(), - amount); + TNECore.eco().currency().getDefaultCurrency(worldName).getUid(), + amount); final Transaction transaction = new Transaction("take") .to(account.get(), modifier.counter()) @@ -464,12 +494,12 @@ public EconomyResponse withdraw(String pluginName, UUID uuid, String worldName, try { TransactionResult result = transaction.process(); return new EconomyResponse(amount, transaction.getTo().getCombinedEnding(), - fromResult(result), - result.getMessage()); + fromResult(result), + result.getMessage()); } catch(InvalidTransactionException e) { return new EconomyResponse(amount, transaction.getTo().getCombinedEnding(), - EconomyResponse.ResponseType.FAILURE, e.getMessage()); + EconomyResponse.ResponseType.FAILURE, e.getMessage()); } } @@ -485,6 +515,7 @@ public EconomyResponse withdraw(String pluginName, UUID uuid, String worldName, */ @Override public EconomyResponse deposit(String pluginName, UUID uuid, BigDecimal amount) { + return deposit(pluginName, uuid, TNECore.eco().region().defaultRegion(), defaultCurrency(), amount); } @@ -503,6 +534,7 @@ public EconomyResponse deposit(String pluginName, UUID uuid, BigDecimal amount) */ @Override public EconomyResponse deposit(String pluginName, UUID uuid, String worldName, BigDecimal amount) { + return deposit(pluginName, uuid, worldName, defaultCurrency(), amount); } @@ -522,6 +554,7 @@ public EconomyResponse deposit(String pluginName, UUID uuid, String worldName, B */ @Override public EconomyResponse deposit(String pluginName, UUID uuid, String worldName, String currency, BigDecimal amount) { + final Optional account = TNECore.eco().account().findAccount(uuid.toString()); if(account.isEmpty()) { @@ -529,8 +562,8 @@ public EconomyResponse deposit(String pluginName, UUID uuid, String worldName, S } final HoldingsModifier modifier = new HoldingsModifier(worldName, - TNECore.eco().currency().getDefaultCurrency(worldName).getUid(), - amount); + TNECore.eco().currency().getDefaultCurrency(worldName).getUid(), + amount); final Transaction transaction = new Transaction("give") @@ -541,11 +574,11 @@ public EconomyResponse deposit(String pluginName, UUID uuid, String worldName, S try { TransactionResult result = transaction.process(); return new EconomyResponse(amount, transaction.getTo().getCombinedEnding(), fromResult(result), - result.getMessage()); + result.getMessage()); } catch(InvalidTransactionException e) { return new EconomyResponse(amount, transaction.getTo().getCombinedEnding(), - ResponseType.FAILURE, e.getMessage()); + ResponseType.FAILURE, e.getMessage()); } } @@ -560,6 +593,7 @@ public EconomyResponse deposit(String pluginName, UUID uuid, String worldName, S */ @Override public boolean createBank(String pluginName, String name, UUID uuid) { + return false; } @@ -573,6 +607,7 @@ public boolean createBank(String pluginName, String name, UUID uuid) { */ @Override public boolean deleteBank(String pluginName, UUID uuid) { + return false; } @@ -586,6 +621,7 @@ public boolean deleteBank(String pluginName, UUID uuid) { */ @Override public Map getBankUUIDNameMap() { + return Map.of(); } @@ -599,6 +635,7 @@ public Map getBankUUIDNameMap() { */ @Override public String getBankAccountName(UUID uuid) { + return ""; } @@ -611,6 +648,7 @@ public String getBankAccountName(UUID uuid) { */ @Override public boolean hasBankAccount(UUID uuid) { + return false; } @@ -624,6 +662,7 @@ public boolean hasBankAccount(UUID uuid) { */ @Override public boolean bankSupportsCurrency(UUID uuid, String currency) { + return false; } @@ -639,6 +678,7 @@ public boolean bankSupportsCurrency(UUID uuid, String currency) { */ @Override public boolean renameBankAccount(String pluginName, UUID uuid, String name) { + return false; } @@ -652,6 +692,7 @@ public boolean renameBankAccount(String pluginName, UUID uuid, String name) { */ @Override public BigDecimal bankBalance(String pluginName, UUID uuid) { + return BigDecimal.ZERO; } @@ -666,6 +707,7 @@ public BigDecimal bankBalance(String pluginName, UUID uuid) { */ @Override public BigDecimal bankBalance(String pluginName, UUID uuid, String currency) { + return BigDecimal.ZERO; } @@ -680,6 +722,7 @@ public BigDecimal bankBalance(String pluginName, UUID uuid, String currency) { */ @Override public boolean bankHas(String pluginName, UUID uuid, BigDecimal amount) { + return false; } @@ -695,6 +738,7 @@ public boolean bankHas(String pluginName, UUID uuid, BigDecimal amount) { */ @Override public boolean bankHas(String pluginName, UUID uuid, String currency, BigDecimal amount) { + return false; } @@ -710,6 +754,7 @@ public boolean bankHas(String pluginName, UUID uuid, String currency, BigDecimal */ @Override public EconomyResponse bankWithdraw(String pluginName, UUID uuid, BigDecimal amount) { + return new EconomyResponse(BigDecimal.ZERO, BigDecimal.ZERO, ResponseType.NOT_IMPLEMENTED, ""); } @@ -726,6 +771,7 @@ public EconomyResponse bankWithdraw(String pluginName, UUID uuid, BigDecimal amo */ @Override public EconomyResponse bankWithdraw(String pluginName, UUID uuid, String currency, BigDecimal amount) { + return new EconomyResponse(BigDecimal.ZERO, BigDecimal.ZERO, ResponseType.NOT_IMPLEMENTED, ""); } @@ -741,6 +787,7 @@ public EconomyResponse bankWithdraw(String pluginName, UUID uuid, String currenc */ @Override public EconomyResponse bankDeposit(String pluginName, UUID uuid, BigDecimal amount) { + return new EconomyResponse(BigDecimal.ZERO, BigDecimal.ZERO, ResponseType.NOT_IMPLEMENTED, ""); } @@ -752,11 +799,13 @@ public EconomyResponse bankDeposit(String pluginName, UUID uuid, BigDecimal amou * @param currency the currency to use. * @param amount to deposit. * - * @return {@link EconomyResponse} which includes the Economy plugin's {@link EconomyResponse.ResponseType} as to - * whether the transaction was a Success, Failure, Unsupported. + * @return {@link EconomyResponse} which includes the Economy plugin's + * {@link EconomyResponse.ResponseType} as to whether the transaction was a Success, Failure, + * Unsupported. */ @Override public EconomyResponse bankDeposit(String pluginName, UUID uuid, String currency, BigDecimal amount) { + return new EconomyResponse(BigDecimal.ZERO, BigDecimal.ZERO, ResponseType.NOT_IMPLEMENTED, ""); } @@ -770,6 +819,7 @@ public EconomyResponse bankDeposit(String pluginName, UUID uuid, String currency */ @Override public boolean isBankOwner(UUID uuid, UUID bankUUID) { + return false; } @@ -783,6 +833,7 @@ public boolean isBankOwner(UUID uuid, UUID bankUUID) { */ @Override public boolean isBankMember(UUID uuid, UUID bankUUID) { + return false; } @@ -793,10 +844,12 @@ public boolean isBankMember(UUID uuid, UUID bankUUID) { */ @Override public Collection getBanks() { + return List.of(); } private EconomyResponse.ResponseType fromResult(@Nullable TransactionResult result) { + if(result != null && result.isSuccessful()) { return EconomyResponse.ResponseType.SUCCESS; } diff --git a/Bukkit/src/net/tnemc/bukkit/hook/economy/VaultHook.java b/Bukkit/src/net/tnemc/bukkit/hook/economy/VaultHook.java index 11569d73..0ab1bd50 100644 --- a/Bukkit/src/net/tnemc/bukkit/hook/economy/VaultHook.java +++ b/Bukkit/src/net/tnemc/bukkit/hook/economy/VaultHook.java @@ -38,6 +38,7 @@ public class VaultHook implements Hook { */ @Override public boolean enabled() { + return false; } @@ -46,8 +47,9 @@ public boolean enabled() { */ @Override public void register() { + BukkitCore.instance().getPlugin().getServer().getServicesManager().register(Economy.class, new TNEVault(), - BukkitCore.instance().getPlugin(), ServicePriority.Highest); + BukkitCore.instance().getPlugin(), ServicePriority.Highest); PluginCore.log().inform("Hooked into Vault"); } diff --git a/Bukkit/src/net/tnemc/bukkit/hook/economy/VaultUnlockedHook.java b/Bukkit/src/net/tnemc/bukkit/hook/economy/VaultUnlockedHook.java index 8892800d..97f86d3e 100644 --- a/Bukkit/src/net/tnemc/bukkit/hook/economy/VaultUnlockedHook.java +++ b/Bukkit/src/net/tnemc/bukkit/hook/economy/VaultUnlockedHook.java @@ -37,6 +37,7 @@ public class VaultUnlockedHook implements Hook { */ @Override public boolean enabled() { + return false; } @@ -45,8 +46,9 @@ public boolean enabled() { */ @Override public void register() { + BukkitCore.instance().getPlugin().getServer().getServicesManager().register(Economy.class, new TNEVaultUnlocked(), - BukkitCore.instance().getPlugin(), ServicePriority.Highest); + BukkitCore.instance().getPlugin(), ServicePriority.Highest); PluginCore.log().inform("Hooked into VaultUnlocked"); } diff --git a/Bukkit/src/net/tnemc/bukkit/hook/misc/PAPIHook.java b/Bukkit/src/net/tnemc/bukkit/hook/misc/PAPIHook.java index ae0ddf5a..482bba6a 100644 --- a/Bukkit/src/net/tnemc/bukkit/hook/misc/PAPIHook.java +++ b/Bukkit/src/net/tnemc/bukkit/hook/misc/PAPIHook.java @@ -47,21 +47,25 @@ public class PAPIHook extends PlaceholderExpansion { @Override public String getAuthor() { + return "creatorfromhell"; } @Override public String getIdentifier() { + return "TNE"; } @Override public String getVersion() { + return "0.1.2.8"; } @Override public boolean persist() { + return true; } @@ -109,9 +113,9 @@ public String onPlaceholderRequest(Player player, @NotNull String identifier) { } final HoldingsEntry entry = new HoldingsEntry(TNECore.eco().region().defaultRegion(), - curID, - amount, - EconomyManager.NORMAL); + curID, + amount, + EconomyManager.NORMAL); return CurrencyFormatter.format(account.get(), entry); } else { return amount.toPlainString(); @@ -233,10 +237,12 @@ public String onPlaceholderRequest(Player player, @NotNull String identifier) { } public boolean formatted(final String parameter) { + return parameter.contains("formatted"); } public Optional findFromArgs(final String parameter) { + return TNECore.eco().account().findAccount(parameter); } } \ No newline at end of file diff --git a/Bukkit/src/net/tnemc/bukkit/listeners/mcmmo/PlayerFishingTreasureListener.java b/Bukkit/src/net/tnemc/bukkit/listeners/mcmmo/PlayerFishingTreasureListener.java index 6610bf41..60281524 100644 --- a/Bukkit/src/net/tnemc/bukkit/listeners/mcmmo/PlayerFishingTreasureListener.java +++ b/Bukkit/src/net/tnemc/bukkit/listeners/mcmmo/PlayerFishingTreasureListener.java @@ -32,9 +32,10 @@ public class PlayerFishingTreasureListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void onFishReward(final McMMOPlayerFishingTreasureEvent event) { + if(BukkitConfig.yaml().getBoolean("Bukkit.McMMORewards")) { Optional currency = TNECore.eco().currency().findCurrencyByMaterial(event.getTreasure().getType().name()); - if (currency.isPresent()) event.setCancelled(true); + if(currency.isPresent()) event.setCancelled(true); } } } diff --git a/Bukkit/src/net/tnemc/bukkit/listeners/player/PlayerInteractListener.java b/Bukkit/src/net/tnemc/bukkit/listeners/player/PlayerInteractListener.java index d9c0fe38..b1d7e254 100644 --- a/Bukkit/src/net/tnemc/bukkit/listeners/player/PlayerInteractListener.java +++ b/Bukkit/src/net/tnemc/bukkit/listeners/player/PlayerInteractListener.java @@ -39,6 +39,7 @@ public class PlayerInteractListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void onInteract(final PlayerInteractEvent event) { + final PlayerProvider provider = PluginCore.server().initializePlayer(event.getPlayer()); final ItemStack stack = event.getItem(); @@ -46,7 +47,7 @@ public void onInteract(final PlayerInteractEvent event) { if(stack == null) return; if(event.getAction().equals(Action.RIGHT_CLICK_AIR) || - event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { + event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { new PlayerInteractHandler().handle(provider, BukkitItemStack.locale(stack)); } diff --git a/Bukkit/src/net/tnemc/bukkit/listeners/player/PlayerJoinListener.java b/Bukkit/src/net/tnemc/bukkit/listeners/player/PlayerJoinListener.java index 8fea948d..b0934e13 100644 --- a/Bukkit/src/net/tnemc/bukkit/listeners/player/PlayerJoinListener.java +++ b/Bukkit/src/net/tnemc/bukkit/listeners/player/PlayerJoinListener.java @@ -37,9 +37,10 @@ public class PlayerJoinListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void onJoin(final PlayerJoinEvent event) { + final PlayerProvider provider = PluginCore.server().initializePlayer(event.getPlayer()); final HandlerResponse handle = new PlayerJoinHandler() - .handle(provider); + .handle(provider); if(handle.isCancelled()) { event.getPlayer().kickPlayer(handle.getResponse()); diff --git a/Bukkit/src/net/tnemc/bukkit/listeners/player/PlayerQuitListener.java b/Bukkit/src/net/tnemc/bukkit/listeners/player/PlayerQuitListener.java index f2d53422..433977ab 100644 --- a/Bukkit/src/net/tnemc/bukkit/listeners/player/PlayerQuitListener.java +++ b/Bukkit/src/net/tnemc/bukkit/listeners/player/PlayerQuitListener.java @@ -35,6 +35,7 @@ public class PlayerQuitListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void onQuit(final PlayerQuitEvent event) { + new PlayerLeaveHandler().handle(PluginCore.server().initializePlayer(event.getPlayer())); } } diff --git a/Bukkit/src/net/tnemc/bukkit/listeners/server/MessageChannelListener.java b/Bukkit/src/net/tnemc/bukkit/listeners/server/MessageChannelListener.java index f2c5cc92..07e2b1f6 100644 --- a/Bukkit/src/net/tnemc/bukkit/listeners/server/MessageChannelListener.java +++ b/Bukkit/src/net/tnemc/bukkit/listeners/server/MessageChannelListener.java @@ -30,8 +30,10 @@ * @since 0.1.2.0 */ public class MessageChannelListener implements PluginMessageListener { + @Override public void onPluginMessageReceived(@NotNull String channel, @NotNull Player player, byte[] bytes) { + PluginCore.instance().getChannelMessageManager().handle(channel, bytes); } } \ No newline at end of file diff --git a/Bukkit/src/net/tnemc/bukkit/listeners/server/PluginEnableListener.java b/Bukkit/src/net/tnemc/bukkit/listeners/server/PluginEnableListener.java index c5872633..be5f68f3 100644 --- a/Bukkit/src/net/tnemc/bukkit/listeners/server/PluginEnableListener.java +++ b/Bukkit/src/net/tnemc/bukkit/listeners/server/PluginEnableListener.java @@ -33,6 +33,7 @@ public class PluginEnableListener implements Listener { @EventHandler public void onEvent(PluginEnableEvent event) { + if(event.getPlugin().getName().equalsIgnoreCase("placeholderapi")) { new PAPIHook().register(); } diff --git a/Bukkit/src/net/tnemc/bukkit/listeners/world/WorldLoadListener.java b/Bukkit/src/net/tnemc/bukkit/listeners/world/WorldLoadListener.java index 83eb129b..af021ece 100644 --- a/Bukkit/src/net/tnemc/bukkit/listeners/world/WorldLoadListener.java +++ b/Bukkit/src/net/tnemc/bukkit/listeners/world/WorldLoadListener.java @@ -35,6 +35,7 @@ public class WorldLoadListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void onLoad(final WorldLoadEvent event) { + new RegionLoadHandler().handle(event.getWorld().getName(), RegionType.WORLD); } } \ No newline at end of file diff --git a/BukkitEarly/pom.xml b/BukkitEarly/pom.xml index fa65904d..817560b4 100644 --- a/BukkitEarly/pom.xml +++ b/BukkitEarly/pom.xml @@ -1,4 +1,6 @@ - + 4.0.0 BukkitEarlyCore jar @@ -12,7 +14,6 @@ - clean package target @@ -69,7 +70,9 @@ - ${project.build.directory}/dependency-reduced-pom.xml + + ${project.build.directory}/dependency-reduced-pom.xml + net.tnemc:* diff --git a/BukkitEarly/src/paper/PaperServerProvider.java b/BukkitEarly/src/paper/PaperServerProvider.java index cfaf8326..f8ba25b6 100644 --- a/BukkitEarly/src/paper/PaperServerProvider.java +++ b/BukkitEarly/src/paper/PaperServerProvider.java @@ -30,6 +30,7 @@ public class PaperServerProvider extends BukkitServerProvider { @Override public String name() { + return "paper"; } } \ No newline at end of file diff --git a/BukkitEarly/src/paper/TNE.java b/BukkitEarly/src/paper/TNE.java index 4712ffec..731ff044 100644 --- a/BukkitEarly/src/paper/TNE.java +++ b/BukkitEarly/src/paper/TNE.java @@ -33,16 +33,19 @@ public class TNE extends JavaPlugin { @Override public void onLoad() { + this.bukkit.load(this, new PaperServerProvider()); } @Override public void onEnable() { + this.bukkit.enable(this); } @Override public void onDisable() { + this.bukkit.disable(this); } } \ No newline at end of file diff --git a/Bungee/pom.xml b/Bungee/pom.xml index dcac715c..5654d525 100644 --- a/Bungee/pom.xml +++ b/Bungee/pom.xml @@ -21,7 +21,6 @@ - clean package target @@ -78,7 +77,9 @@ - ${project.build.directory}/dependency-reduced-pom.xml + + ${project.build.directory}/dependency-reduced-pom.xml + diff --git a/Bungee/src/net/tnemc/bungee/BungeeCore.java b/Bungee/src/net/tnemc/bungee/BungeeCore.java index 71026c28..095fdb32 100644 --- a/Bungee/src/net/tnemc/bungee/BungeeCore.java +++ b/Bungee/src/net/tnemc/bungee/BungeeCore.java @@ -43,6 +43,7 @@ public class BungeeCore extends Plugin { @Override public void onEnable() { + instance = this; this.manager = new MessageManager(new BungeeProxy()); @@ -55,14 +56,17 @@ public void onEnable() { } public static BungeeCore instance() { + return instance; } public Map getBacklog() { + return backlog; } public void remove(final UUID server) { + backlog.remove(server); } } \ No newline at end of file diff --git a/Bungee/src/net/tnemc/bungee/BungeeProxy.java b/Bungee/src/net/tnemc/bungee/BungeeProxy.java index a1d1da1d..760b349b 100644 --- a/Bungee/src/net/tnemc/bungee/BungeeProxy.java +++ b/Bungee/src/net/tnemc/bungee/BungeeProxy.java @@ -39,6 +39,7 @@ public class BungeeProxy implements ProxyProvider { */ @Override public void sendToAll(String channel, byte[] out, boolean backlog) { + BungeeCore.instance().getProxy().getServers().values().forEach(server->{ if(!server.getPlayers().isEmpty()) { server.sendData(channel, out, true); @@ -60,6 +61,7 @@ public void sendToAll(String channel, byte[] out, boolean backlog) { */ @Override public void sendTo(String serverName, String channel, byte[] out) { + BungeeCore.instance().getProxy().getServers().values().forEach(server->{ if(server.getName().equalsIgnoreCase(serverName)) { server.sendData(channel, out, true); @@ -74,6 +76,7 @@ public void sendTo(String serverName, String channel, byte[] out) { */ @Override public void sendBacklog(@NotNull MessageData data) { + BungeeCore.instance().getProxy().getServers().values().forEach(server->{ if(server.getSocketAddress().toString().equalsIgnoreCase(data.getServerName())) { for(BacklogEntry entry : data.getBacklog()) { diff --git a/Bungee/src/net/tnemc/bungee/ProxyProvider.java b/Bungee/src/net/tnemc/bungee/ProxyProvider.java index 6b3fca00..61e66468 100644 --- a/Bungee/src/net/tnemc/bungee/ProxyProvider.java +++ b/Bungee/src/net/tnemc/bungee/ProxyProvider.java @@ -31,21 +31,24 @@ public interface ProxyProvider { /** * Used to send data to every server that is not this server. + * * @param channel The channel to use for sending the data. - * @param out The data to send. + * @param out The data to send. */ void sendToAll(final String channel, byte[] out, boolean backlog); /** * Used to send data to a specific server. + * * @param serverName The server name. - * @param channel The channel to use for sending the data. - * @param out The data to send. + * @param channel The channel to use for sending the data. + * @param out The data to send. */ void sendTo(final String serverName, final String channel, byte[] out); /** * Used to send any backlog data to a server. + * * @param data The {@link MessageData} to use for determining the server, and backlog to send. */ void sendBacklog(@NotNull final MessageData data); diff --git a/Bungee/src/net/tnemc/bungee/event/MessageListener.java b/Bungee/src/net/tnemc/bungee/event/MessageListener.java index 6e405f1f..fada33ee 100644 --- a/Bungee/src/net/tnemc/bungee/event/MessageListener.java +++ b/Bungee/src/net/tnemc/bungee/event/MessageListener.java @@ -34,6 +34,7 @@ public class MessageListener implements Listener { @EventHandler public void onMessage(PluginMessageEvent event) { + if(!event.getTag().startsWith("tne:")) { return; } diff --git a/Bungee/src/net/tnemc/bungee/message/MessageHandler.java b/Bungee/src/net/tnemc/bungee/message/MessageHandler.java index f600e8f1..9275713e 100644 --- a/Bungee/src/net/tnemc/bungee/message/MessageHandler.java +++ b/Bungee/src/net/tnemc/bungee/message/MessageHandler.java @@ -36,26 +36,32 @@ public abstract class MessageHandler { private final String tag; public MessageHandler(String tag) { + this.tag = tag; } public static void sendToAll(final String channel, ByteArrayDataOutput out, boolean backlog) { + MessageManager.instance().proxy().sendToAll(channel, out.toByteArray(), backlog); } public static void sendToAll(final String channel, byte[] out, boolean backlog) { + MessageManager.instance().proxy().sendToAll(channel, out, backlog); } public static void sendTo(final String serverName, final String channel, ByteArrayDataOutput out) { + MessageManager.instance().proxy().sendTo(serverName, channel, out.toByteArray()); } public static void sendTo(final String serverName, final String channel, byte[] out) { + MessageManager.instance().proxy().sendTo(serverName, channel, out); } public static void sendBacklog(@NotNull final MessageData data) { + MessageManager.instance().proxy().sendBacklog(data); } diff --git a/Bungee/src/net/tnemc/bungee/message/MessageManager.java b/Bungee/src/net/tnemc/bungee/message/MessageManager.java index 8739613c..65b6c47b 100644 --- a/Bungee/src/net/tnemc/bungee/message/MessageManager.java +++ b/Bungee/src/net/tnemc/bungee/message/MessageManager.java @@ -49,6 +49,7 @@ public class MessageManager { private static MessageManager instance; public MessageManager(final ProxyProvider proxy) { + instance = this; this.proxy = proxy; handlers.put("balance", new BalanceMessageHandler()); @@ -82,18 +83,22 @@ public void onMessage(final String channel, final byte[] data) { } public ProxyProvider proxy() { + return proxy; } public Map getHubs() { + return hubs; } public static MessageManager instance() { + return instance; } public void backlog(final String server) { + if(data.containsKey(server)) { proxy.sendBacklog(data.get(server)); data.remove(server); @@ -101,6 +106,7 @@ public void backlog(final String server) { } public void addData(final String server, BacklogEntry entry) { + if(data.containsKey(server)) { data.get(server).getBacklog().add(entry); return; diff --git a/Bungee/src/net/tnemc/bungee/message/backlog/ConfigEntry.java b/Bungee/src/net/tnemc/bungee/message/backlog/ConfigEntry.java index e5cc2fd9..9b6b7a66 100644 --- a/Bungee/src/net/tnemc/bungee/message/backlog/ConfigEntry.java +++ b/Bungee/src/net/tnemc/bungee/message/backlog/ConfigEntry.java @@ -45,26 +45,32 @@ public class ConfigEntry { private final String pin; public ConfigEntry(String pin) { + this.pin = pin; } public List getConfigs() { + return configs; } public List getCurrencies() { + return currencies; } public List getSynced() { + return synced; } public String getPin() { + return pin; } public byte[] getBytes() { + return bytes; } diff --git a/Bungee/src/net/tnemc/bungee/message/backlog/MessageData.java b/Bungee/src/net/tnemc/bungee/message/backlog/MessageData.java index 52dab377..e38eb5ed 100644 --- a/Bungee/src/net/tnemc/bungee/message/backlog/MessageData.java +++ b/Bungee/src/net/tnemc/bungee/message/backlog/MessageData.java @@ -34,14 +34,17 @@ public class MessageData { private final String serverName; public MessageData(String serverName) { + this.serverName = serverName; } public String getServerName() { + return serverName; } public List getBacklog() { + return backlog; } } \ No newline at end of file diff --git a/Bungee/src/net/tnemc/bungee/message/handlers/AccountHandler.java b/Bungee/src/net/tnemc/bungee/message/handlers/AccountHandler.java index 9c971b87..cb23b390 100644 --- a/Bungee/src/net/tnemc/bungee/message/handlers/AccountHandler.java +++ b/Bungee/src/net/tnemc/bungee/message/handlers/AccountHandler.java @@ -33,6 +33,7 @@ public abstract class AccountHandler extends MessageHandler { public AccountHandler(String tag) { + super(tag); } @@ -46,7 +47,7 @@ public void handle(UUID server, DataInputStream in) { final String accountName = in.readUTF(); handle(account, accountName, server, in); - } catch (IOException e) { + } catch(IOException e) { e.printStackTrace(); } } diff --git a/Bungee/src/net/tnemc/bungee/message/handlers/BalanceMessageHandler.java b/Bungee/src/net/tnemc/bungee/message/handlers/BalanceMessageHandler.java index 367701fa..bda4cb29 100644 --- a/Bungee/src/net/tnemc/bungee/message/handlers/BalanceMessageHandler.java +++ b/Bungee/src/net/tnemc/bungee/message/handlers/BalanceMessageHandler.java @@ -32,7 +32,9 @@ * @since 0.1.2.0 */ public class BalanceMessageHandler extends AccountHandler { + public BalanceMessageHandler() { + super("balance"); } @@ -45,12 +47,13 @@ public void handle(String account, String accountName, UUID server, DataInputStr final String handler = stream.readUTF(); final String amount = stream.readUTF(); send(server, account, accountName, region, currency, handler, amount); - } catch (IOException e) { + } catch(IOException e) { e.printStackTrace(); } } public static void send(UUID server, String account, String accountName, String region, String currency, String handler, String amount) { + final ByteArrayDataOutput out = ByteStreams.newDataOutput(); out.writeUTF(server.toString()); out.writeUTF(account); diff --git a/Bungee/src/net/tnemc/bungee/message/handlers/ConfigMessageHandler.java b/Bungee/src/net/tnemc/bungee/message/handlers/ConfigMessageHandler.java index cabd14af..95883997 100644 --- a/Bungee/src/net/tnemc/bungee/message/handlers/ConfigMessageHandler.java +++ b/Bungee/src/net/tnemc/bungee/message/handlers/ConfigMessageHandler.java @@ -34,7 +34,9 @@ * @since 0.1.2.0 */ public class ConfigMessageHandler extends MessageHandler { + public ConfigMessageHandler() { + super("config"); } @@ -50,6 +52,7 @@ public void handle(UUID server, DataInputStream stream) { } public static void send(UUID server, byte[] left) { + final ByteArrayDataOutput out = ByteStreams.newDataOutput(); diff --git a/Bungee/src/net/tnemc/bungee/message/handlers/MessageMessageHandler.java b/Bungee/src/net/tnemc/bungee/message/handlers/MessageMessageHandler.java index a926360b..0ca98637 100644 --- a/Bungee/src/net/tnemc/bungee/message/handlers/MessageMessageHandler.java +++ b/Bungee/src/net/tnemc/bungee/message/handlers/MessageMessageHandler.java @@ -32,7 +32,9 @@ * @since 0.1.2.0 */ public class MessageMessageHandler extends MessageHandler { + public MessageMessageHandler() { + super("message"); } @@ -44,12 +46,13 @@ public void handle(UUID server, DataInputStream stream) { final String message = stream.readUTF(); send(server, identifier, message); - } catch (IOException e) { + } catch(IOException e) { e.printStackTrace(); } } public static void send(UUID server, String identifier, String message) { + final ByteArrayDataOutput out = ByteStreams.newDataOutput(); diff --git a/Bungee/src/net/tnemc/bungee/message/handlers/SyncAllMessageHandler.java b/Bungee/src/net/tnemc/bungee/message/handlers/SyncAllMessageHandler.java index b3bfbf23..2d7fc812 100644 --- a/Bungee/src/net/tnemc/bungee/message/handlers/SyncAllMessageHandler.java +++ b/Bungee/src/net/tnemc/bungee/message/handlers/SyncAllMessageHandler.java @@ -30,7 +30,9 @@ * @since 0.1.2.0 */ public class SyncAllMessageHandler extends AccountHandler { + public SyncAllMessageHandler() { + super("sync"); } diff --git a/Core/pom.xml b/Core/pom.xml index 5d1450d3..bf3dcea9 100644 --- a/Core/pom.xml +++ b/Core/pom.xml @@ -1,4 +1,6 @@ - + 4.0.0 EconomyCore jar @@ -114,7 +116,9 @@ - ${project.build.directory}/dependency-reduced-pom.xml + + ${project.build.directory}/dependency-reduced-pom.xml + net.tnemc:* diff --git a/Core/resources/config.yml b/Core/resources/config.yml index 882c699d..d99ef4a9 100644 --- a/Core/resources/config.yml +++ b/Core/resources/config.yml @@ -109,10 +109,10 @@ Core: #A list of values to use to exclude certain users from baltop if the username contains these values. Exclusions: - - "^town-.*" - - "^nation-.*" - - "^faction-.*" - - "^towny-.*" + - "^town-.*" + - "^nation-.*" + - "^faction-.*" + - "^towny-.*" #Extra configurations regarding the pay command Pay: @@ -125,7 +125,7 @@ Core: #All configurations relating to update checking Update: - + #Should TNE check for updates? Check: true diff --git a/Core/resources/messages.yml b/Core/resources/messages.yml index 173a27d7..3357849c 100644 --- a/Core/resources/messages.yml +++ b/Core/resources/messages.yml @@ -122,7 +122,7 @@ Messages: EnderChest: "Some funds were put in your ender chest because your inventory was full!" Dropped: "Some funds were dropped on the ground because your inventory was full!" -#Messages.Menu. + #Messages.Menu. Menu: Shared: diff --git a/Core/resources/structure.sql b/Core/resources/structure.sql index 43611ee1..86e314d8 100644 --- a/Core/resources/structure.sql +++ b/Core/resources/structure.sql @@ -1,94 +1,302 @@ -- accounts table -CREATE TABLE IF NOT EXISTS tne_accounts ( - uid BINARY(16) NOT NULL PRIMARY KEY, - username VARCHAR(50) NOT NULL UNIQUE, - account_type VARCHAR(30) NOT NULL, +CREATE TABLE IF NOT EXISTS tne_accounts +( + uid + BINARY +( + 16 +) NOT NULL PRIMARY KEY, + username VARCHAR +( + 50 +) NOT NULL UNIQUE, + account_type VARCHAR +( + 30 +) NOT NULL, created DATETIME NOT NULL, - pin VARCHAR(16), - status VARCHAR(36) + pin VARCHAR +( + 16 +), + status VARCHAR +( + 36 +) ); -CREATE TABLE IF NOT EXISTS tne_non_players_accounts ( - uid BINARY(16) NOT NULL UNIQUE, - owner BINARY(16) NOT NULL, - - FOREIGN KEY(uid) REFERENCES tne_accounts(uid) ON DELETE CASCADE, - FOREIGN KEY(owner) REFERENCES tne_accounts(uid) ON DELETE CASCADE +CREATE TABLE IF NOT EXISTS tne_non_players_accounts +( + uid + BINARY +( + 16 +) NOT NULL UNIQUE, + owner BINARY +( + 16 +) NOT NULL, + FOREIGN KEY +( + uid +) REFERENCES tne_accounts +( + uid +) ON DELETE CASCADE, + FOREIGN KEY +( + owner +) REFERENCES tne_accounts +( + uid +) + ON DELETE CASCADE ); -CREATE TABLE IF NOT EXISTS tne_players_accounts ( - uid BINARY(16) NOT NULL UNIQUE, +CREATE TABLE IF NOT EXISTS tne_players_accounts +( + uid + BINARY +( + 16 +) NOT NULL UNIQUE, last_online DATETIME NOT NULL, - FOREIGN KEY(uid) REFERENCES tne_accounts(uid) ON DELETE CASCADE + FOREIGN KEY +( + uid +) REFERENCES tne_accounts +( + uid +) ON DELETE CASCADE ); -CREATE TABLE IF NOT EXISTS tne_account_members ( - uid BINARY(16) NOT NULL, - account BINARY(16) NOT NULL, - perm VARCHAR(36) NOT NULL, - perm_value TINYINT(1) NOT NULL, - - FOREIGN KEY(uid) REFERENCES tne_accounts(uid) ON DELETE CASCADE, - FOREIGN KEY(account) REFERENCES tne_accounts(uid) ON DELETE CASCADE +CREATE TABLE IF NOT EXISTS tne_account_members +( + uid + BINARY +( + 16 +) NOT NULL, + account BINARY +( + 16 +) NOT NULL, + perm VARCHAR +( + 36 +) NOT NULL, + perm_value TINYINT +( + 1 +) NOT NULL, + FOREIGN KEY +( + uid +) REFERENCES tne_accounts +( + uid +) ON DELETE CASCADE, + FOREIGN KEY +( + account +) REFERENCES tne_accounts +( + uid +) + ON DELETE CASCADE ); -- holdings table -CREATE TABLE IF NOT EXISTS tne_holdings ( - uid BINARY(16) NOT NULL, - server VARCHAR(40) NOT NULL, - region VARCHAR(40) NOT NULL, - currency BINARY(16) NOT NULL, - holdings_type VARCHAR(30) NOT NULL, - holdings DECIMAL(49, 4) NOT NULL, - - UNIQUE(`uid`, `server`, `region`, `currency`, `holdings_type`), - FOREIGN KEY(uid) REFERENCES tne_accounts(uid) ON DELETE CASCADE +CREATE TABLE IF NOT EXISTS tne_holdings +( + uid + BINARY +( + 16 +) NOT NULL, + server VARCHAR +( + 40 +) NOT NULL, + region VARCHAR +( + 40 +) NOT NULL, + currency BINARY +( + 16 +) NOT NULL, + holdings_type VARCHAR +( + 30 +) NOT NULL, + holdings DECIMAL +( + 49, + 4 +) NOT NULL, + UNIQUE +( + `uid`, + `server`, + `region`, + `currency`, + `holdings_type` +), + FOREIGN KEY +( + uid +) REFERENCES tne_accounts +( + uid +) ON DELETE CASCADE ); -- receipt table -CREATE TABLE IF NOT EXISTS tne_receipts ( - uid BINARY(16) NOT NULL, +CREATE TABLE IF NOT EXISTS tne_receipts +( + uid + BINARY +( + 16 +) NOT NULL, performed DATETIME NOT NULL, - receipt_type VARCHAR(30) NOT NULL, - receipt_source VARCHAR(60) NOT NULL, - receipt_source_type VARCHAR(30) NOT NULL, - archive TINYINT(1) NOT NULL, - voided TINYINT(1) NOT NULL + receipt_type VARCHAR +( + 30 +) NOT NULL, + receipt_source VARCHAR +( + 60 +) NOT NULL, + receipt_source_type VARCHAR +( + 30 +) NOT NULL, + archive TINYINT +( + 1 +) NOT NULL, + voided TINYINT +( + 1 +) NOT NULL ); -- receipt table -CREATE TABLE IF NOT EXISTS tne_receipts_holdings ( - uid BINARY(16) NOT NULL UNIQUE, - participant BINARY(16) NOT NULL, - ending TINYINT(1) NOT NULL, - server VARCHAR(40) NOT NULL, - region VARCHAR(40) NOT NULL, - currency BINARY(16) NOT NULL, - holdings_type VARCHAR(30) NOT NULL, - holdings DECIMAL(49, 4) NOT NULL, - - FOREIGN KEY(uid) REFERENCES tne_receipts(uid) ON DELETE CASCADE +CREATE TABLE IF NOT EXISTS tne_receipts_holdings +( + uid + BINARY +( + 16 +) NOT NULL UNIQUE, + participant BINARY +( + 16 +) NOT NULL, + ending TINYINT +( + 1 +) NOT NULL, + server VARCHAR +( + 40 +) NOT NULL, + region VARCHAR +( + 40 +) NOT NULL, + currency BINARY +( + 16 +) NOT NULL, + holdings_type VARCHAR +( + 30 +) NOT NULL, + holdings DECIMAL +( + 49, + 4 +) NOT NULL, + FOREIGN KEY +( + uid +) REFERENCES tne_receipts +( + uid +) ON DELETE CASCADE ); -- Participants of transactions/receipts. -CREATE TABLE IF NOT EXISTS tne_receipts_participants ( - uid BINARY(16) NOT NULL PRIMARY KEY, - participant BINARY(16) NOT NULL, - participant_type VARCHAR(10) NOT NULL, - tax DECIMAL(49, 4) NOT NULL, - - FOREIGN KEY(uid) REFERENCES tne_receipts(uid) ON DELETE CASCADE +CREATE TABLE IF NOT EXISTS tne_receipts_participants +( + uid + BINARY +( + 16 +) NOT NULL PRIMARY KEY, + participant BINARY +( + 16 +) NOT NULL, + participant_type VARCHAR +( + 10 +) NOT NULL, + tax DECIMAL +( + 49, + 4 +) NOT NULL, + FOREIGN KEY +( + uid +) REFERENCES tne_receipts +( + uid +) ON DELETE CASCADE ); -- Holdings modifiers for receipts -CREATE TABLE IF NOT EXISTS tne_receipts_modifiers ( - uid VARCHAR(36) NOT NULL PRIMARY KEY, - participant BINARY(16) NOT NULL, - participant_type VARCHAR(10) NOT NULL, - operation VARCHAR(10) NOT NULL, - region VARCHAR(40) NOT NULL, - currency BINARY(16) NOT NULL, - modifier DECIMAL(49, 4) NOT NULL, - - FOREIGN KEY(uid) REFERENCES tne_receipts(uid) ON DELETE CASCADE +CREATE TABLE IF NOT EXISTS tne_receipts_modifiers +( + uid + VARCHAR +( + 36 +) NOT NULL PRIMARY KEY, + participant BINARY +( + 16 +) NOT NULL, + participant_type VARCHAR +( + 10 +) NOT NULL, + operation VARCHAR +( + 10 +) NOT NULL, + region VARCHAR +( + 40 +) NOT NULL, + currency BINARY +( + 16 +) NOT NULL, + modifier DECIMAL +( + 49, + 4 +) NOT NULL, + FOREIGN KEY +( + uid +) REFERENCES tne_receipts +( + uid +) ON DELETE CASCADE ); \ No newline at end of file diff --git a/Core/src/net/tnemc/core/EconomyManager.java b/Core/src/net/tnemc/core/EconomyManager.java index f4fa8211..de18828e 100644 --- a/Core/src/net/tnemc/core/EconomyManager.java +++ b/Core/src/net/tnemc/core/EconomyManager.java @@ -89,6 +89,7 @@ public class EconomyManager { private static EconomyManager instance; public EconomyManager() { + instance = this; this.accountManager = new AccountManager(); @@ -123,78 +124,96 @@ public void init() { } public Optional findID(String id) { + return Optional.ofNullable(ids.get(id)); } public Optional findHandler(final Identifier identifier) { + return Optional.ofNullable(handlers.get(identifier.asID())); } public void addHandler(final HoldingsHandler handler) { + handlers.put(handler.identifier().asID(), handler); } public void addIdentifier(final Identifier id) { + ids.put(id.asID(), id); } public LinkedList getFor(final Account account) { + return handlers.values().stream() - .filter(handler->handler.appliesTo(account)).collect(Collectors.toCollection(LinkedList::new)); + .filter(handler->handler.appliesTo(account)).collect(Collectors.toCollection(LinkedList::new)); } public LinkedList getFor(final CurrencyType type) { + return handlers.values().stream() - .filter(handler->handler.supports(type)).collect(Collectors.toCollection(LinkedList::new)); + .filter(handler->handler.supports(type)).collect(Collectors.toCollection(LinkedList::new)); } public LinkedList getFor(final Account account, final CurrencyType type) { + return handlers.values().stream() - .filter(handler->handler.appliesTo(account) && handler.supports(type)) - .collect(Collectors.toCollection(LinkedList::new)); + .filter(handler->handler.appliesTo(account) && handler.supports(type)) + .collect(Collectors.toCollection(LinkedList::new)); } public void clearCache() { + accountManager.getAccounts().clear(); } public AccountManager account() { + return accountManager; } public CurrencyManager currency() { + return currencyManager; } public TransactionManager transaction() { + return transactionManager; } public RegionProvider region() { + return regionProvider; } public TopManager getTopManager() { + return topManager; } public static EconomyManager instance() { + return instance; } public static List invalidCurrencies() { + return instance.invalidCurrencies; } public static boolean limitCurrency() { + return instance.limitCurrency; } public static TransactionProcessor baseProcessor() { + return instance.transactionManager.getProcessor(); } public void printInvalid() { + if(!invalidCurrencies.isEmpty()) { for(final String currency : invalidCurrencies) { PluginCore.log().inform("Account Balances found for non existent currency ID: " + currency); diff --git a/Core/src/net/tnemc/core/TNECore.java b/Core/src/net/tnemc/core/TNECore.java index b8811904..c918a5aa 100644 --- a/Core/src/net/tnemc/core/TNECore.java +++ b/Core/src/net/tnemc/core/TNECore.java @@ -93,8 +93,8 @@ /** * The core class of TNE which should be used within each implementation's class. * - * @since 0.1.1.17 * @author creatorfromhell + * @since 0.1.1.17 */ public abstract class TNECore extends PluginEngine { @@ -126,21 +126,25 @@ public abstract class TNECore extends PluginEngine { protected UUID serverAccount; public TNECore() { + instance = this; } @Override public String versionCheckSite() { + return "https://tnemc.net/files/tnebuild.txt"; } @Override public String version() { + return version; } @Override public String build() { + return build; } @@ -167,6 +171,7 @@ public void registerConfigs() { @Override public void registerPluginChannels() { + PluginCore.instance().getChannelMessageManager().register(new BalanceHandler()); PluginCore.instance().getChannelMessageManager().register(new SyncHandler()); PluginCore.instance().getChannelMessageManager().register(new net.tnemc.core.channel.MessageHandler()); @@ -174,6 +179,7 @@ public void registerPluginChannels() { @Override public void registerStorage() { + final StorageSettings settings = new StorageSettings( DataConfig.yaml().getString("Data.Database.File"), DataConfig.yaml().getString("Data.Database.SQL.Host"), @@ -189,7 +195,7 @@ public void registerStorage() { DataConfig.yaml().getLong("Data.Pool.MaxLife"), DataConfig.yaml().getLong("Data.Pool.Timeout"), DataConfig.yaml().getString("Data.Sync.Type") - ); + ); final JedisPoolConfig config = new JedisPoolConfig(); config.setMaxTotal(DataConfig.yaml().getInt("Data.Sync.Redis.Pool.MaxSize", 10)); @@ -197,13 +203,13 @@ public void registerStorage() { config.setMinIdle(DataConfig.yaml().getInt("Data.Sync.Redis.Pool.MinIdle", 1)); this.storage = new StorageManager(DataConfig.yaml().getString("Data.Database.Type"), - new TNEStorageProvider(), settings, new JedisPool(config, DataConfig.yaml().getString("Data.Sync.Redis.Host"), - DataConfig.yaml().getInt("Data.Sync.Redis.Port"), - DataConfig.yaml().getInt("Data.Sync.Redis.Timeout"), - DataConfig.yaml().getString("Data.Sync.Redis.User"), - DataConfig.yaml().getString("Data.Sync.Redis.Password"), - DataConfig.yaml().getInt("Data.Sync.Redis.Index"), - DataConfig.yaml().getBoolean("Data.Sync.Redis.SSL"))); + new TNEStorageProvider(), settings, new JedisPool(config, DataConfig.yaml().getString("Data.Sync.Redis.Host"), + DataConfig.yaml().getInt("Data.Sync.Redis.Port"), + DataConfig.yaml().getInt("Data.Sync.Redis.Timeout"), + DataConfig.yaml().getString("Data.Sync.Redis.User"), + DataConfig.yaml().getString("Data.Sync.Redis.Password"), + DataConfig.yaml().getInt("Data.Sync.Redis.Index"), + DataConfig.yaml().getBoolean("Data.Sync.Redis.SSL"))); } @Override @@ -230,6 +236,7 @@ public void registerCommands() { @Override public void registerCallbacks(CallbackManager callbackManager) { + callbackManager.addCallback(TNECallbacks.ACCOUNT_TYPES.toString(), new CallbackEntry(AccountTypesCallback.class)); callbackManager.addCallback(TNECallbacks.ACCOUNT_LOAD.toString(), new CallbackEntry(AccountLoadCallback.class)); callbackManager.addCallback(TNECallbacks.ACCOUNT_SAVE.toString(), new CallbackEntry(AccountSaveCallback.class)); @@ -244,6 +251,7 @@ public void registerCallbacks(CallbackManager callbackManager) { @Override public String commandHelpWriter(ExecutableCommand command, CommandActor actor) { + final MessageData data = new MessageData("Messages.Commands.Help.Entry"); data.addReplacement("$command", command.getPath().toRealString()); data.addReplacement("$arguments", MessageHandler.getInstance().getTranslator().translateNode(new MessageData("Messages.Commands." + command.getUsage()), "default")); @@ -254,6 +262,7 @@ public String commandHelpWriter(ExecutableCommand command, CommandActor actor) { @Override public void registerUpdateChecker() { + if(MainConfig.yaml().getBoolean("Core.Update.Check")) { this.updateChecker = new Updater(); @@ -314,10 +323,12 @@ public void postConfigs() { @Override public void postStorage() { + } @Override public void postEnable() { + MenuManager.instance().addMenu(new MyEcoMenu()); MenuManager.instance().addMenu(new MyBalMenu()); MenuManager.instance().addMenu(new TransactionMenu()); @@ -345,9 +356,9 @@ public void postEnable() { final BigDecimal defaultBalance = new BigDecimal(MainConfig.yaml().getString("Core.Server.Account.Balance")); if(defaultBalance.compareTo(BigDecimal.ZERO) > 0) { response.getAccount().ifPresent(value->value.setHoldings(new HoldingsEntry(economyManager.region().defaultRegion(), - economyManager.currency().getDefaultCurrency().getUid(), - defaultBalance, - EconomyManager.NORMAL + economyManager.currency().getDefaultCurrency().getUid(), + defaultBalance, + EconomyManager.NORMAL ))); } } else { @@ -360,21 +371,22 @@ public void postEnable() { if(DataConfig.yaml().getBoolean("Data.AutoSaver.Enabled")) { this.autoSaver = PluginCore.server().scheduler().createRepeatingTask(()->{ - storage.storeAll(); - }, new ChoreTime(0), - new ChoreTime(DataConfig.yaml().getInt("Data.AutoSaver.Interval"), TimeUnit.SECONDS), - ChoreExecution.SECONDARY); + storage.storeAll(); + }, new ChoreTime(0), + new ChoreTime(DataConfig.yaml().getInt("Data.AutoSaver.Interval"), TimeUnit.SECONDS), + ChoreExecution.SECONDARY); } economyManager.printInvalid(); - PluginCore.server().scheduler().createDelayedTask(()-> economyManager.getTopManager().load(), new ChoreTime(2), ChoreExecution.SECONDARY); - PluginCore.server().scheduler().createRepeatingTask(()-> economyManager.getTopManager().load(), new ChoreTime(2), new ChoreTime(MainConfig.yaml().getInt("Core.Commands.Top.Refresh"), TimeUnit.SECONDS), ChoreExecution.SECONDARY); + PluginCore.server().scheduler().createDelayedTask(()->economyManager.getTopManager().load(), new ChoreTime(2), ChoreExecution.SECONDARY); + PluginCore.server().scheduler().createRepeatingTask(()->economyManager.getTopManager().load(), new ChoreTime(2), new ChoreTime(MainConfig.yaml().getInt("Core.Commands.Top.Refresh"), TimeUnit.SECONDS), ChoreExecution.SECONDARY); } @Override public void postDisable() { + if(autoSaver != null) { autoSaver.cancel(); } @@ -388,47 +400,58 @@ public void postDisable() { /** * The implementation's {@link EconomyManager}, which is used to manage everything economy related * in TNE. + * * @return The {@link EconomyManager Economy Manager}. */ public static EconomyManager eco() { + return instance.economyManager; } public static YamlStorageManager yaml() { + return instance.yamlManager; } public MainConfig config() { + return config; } public DataConfig data() { + return data; } public MessageConfig message() { + return messageConfig; } public static TNECore instance() { + return instance; } public static TNEAPI api() { + return instance.api; } public UUID getServerAccount() { + return serverAccount; } public abstract ItemCalculations itemCalculations(); public AbstractItemStack denominationToStack(final ItemDenomination denomination) { + return denominationToStack(denomination, 1); } public AbstractItemStack denominationToStack(final ItemDenomination denomination, int amount) { + return PluginCore.server().stackBuilder().of(denomination.getMaterial(), amount) .enchant(denomination.getEnchantments()) .lore(denomination.getLore()) diff --git a/Core/src/net/tnemc/core/TNEStorageProvider.java b/Core/src/net/tnemc/core/TNEStorageProvider.java index 3cd6e57d..f0d6eeaf 100644 --- a/Core/src/net/tnemc/core/TNEStorageProvider.java +++ b/Core/src/net/tnemc/core/TNEStorageProvider.java @@ -76,12 +76,12 @@ public void initialize(String engine) { try { Class.forName("org.mariadb.jdbc.Driver"); maria = true; - } catch(Exception ignore) {} + } catch(Exception ignore) { } try { Class.forName("org.mariadb.jdbc.MariaDbDataSource"); maria = true; - } catch(Exception ignore) {} + } catch(Exception ignore) { } switch(engine.toLowerCase()) { case "mysql" -> { @@ -128,8 +128,8 @@ public void initialize(String engine) { } final Datable account = (this.engine instanceof StandardSQL)? new SQLAccount() : new YAMLAccount(); - final Datable entry = (this.engine instanceof StandardSQL)? new SQLHoldings() : new YAMLHoldings(); - final Datable receipt = (this.engine instanceof StandardSQL)? new SQLReceipt() : new YAMLReceipt(); + final Datable entry = (this.engine instanceof StandardSQL)? new SQLHoldings() : new YAMLHoldings(); + final Datable receipt = (this.engine instanceof StandardSQL)? new SQLReceipt() : new YAMLReceipt(); this.engine.datables().put(Account.class, account); this.engine.datables().put(NonPlayerAccount.class, account); @@ -143,19 +143,22 @@ public void initialize(String engine) { @Override public StorageConnector connector() { + return this.connector; } @Override public StorageEngine engine() { + return this.engine; } @Override public void initialize() { + if(connector instanceof SQLConnector sql - && this.engine instanceof StandardSQL sqlEngine - && sqlEngine.dialect() instanceof TNEDialect tneDialect) { + && this.engine instanceof StandardSQL sqlEngine + && sqlEngine.dialect() instanceof TNEDialect tneDialect) { sql.executeUpdate(tneDialect.accountsTable(), new Object[]{}); sql.executeUpdate(tneDialect.accountsNonPlayerTable(), new Object[]{}); @@ -171,6 +174,7 @@ public void initialize() { @Override public void storeAll(@NotNull String identifier) { + final Optional> data = Optional.ofNullable(engine.datables().get(HoldingsEntry.class)); //Our account storeAll requires no identifier, so we set it to null @@ -179,6 +183,7 @@ public void storeAll(@NotNull String identifier) { @Override public void storeAll() { + final Optional> data = Optional.ofNullable(engine.datables().get(Account.class)); //Our account storeAll requires no identifier, so we set it to null @@ -200,6 +205,7 @@ public void purge() { @Override public void reset() { + TNECore.eco().clearCache(); } diff --git a/Core/src/net/tnemc/core/account/Account.java b/Core/src/net/tnemc/core/account/Account.java index 663de97c..a592013a 100644 --- a/Core/src/net/tnemc/core/account/Account.java +++ b/Core/src/net/tnemc/core/account/Account.java @@ -43,8 +43,8 @@ * An object that is used to represent an Account within the economy plugin. * * @author creatorfromhell - * @since 0.1.2.0 * @see ReceiptBox + * @since 0.1.2.0 */ public class Account extends ReceiptBox { @@ -58,6 +58,7 @@ public class Account extends ReceiptBox { protected AccountStatus status; public Account(UUID identifier, String name) { + super(identifier); this.identifier = identifier; this.name = name; @@ -74,9 +75,11 @@ public Account(UUID identifier, String name) { /** * Used to get the type of account that this is. This is for data-purposes only. + * * @return The account type. */ public String type() { + return "account"; } @@ -86,24 +89,26 @@ public String type() { * @return True if this {@link Account account} represents a Player, otherwise false. */ public boolean isPlayer() { + return (this instanceof PlayerAccount); } /** - * Used to determine if this {@link Account account} supports balances based on inventories. - * This is usually item-based currencies, or experience-based currencies. This should only return - * true if the account is a {@link PlayerAccount player}. + * Used to determine if this {@link Account account} supports balances based on inventories. This + * is usually item-based currencies, or experience-based currencies. This should only return true + * if the account is a {@link PlayerAccount player}. * * @return True if this {@link Account account} supports balances based on inventories. */ public boolean supportsInventoryBalances() { + return isPlayer(); } /** * Used to get the BigDecimal value of this account's holding based on the specifications. * - * @param region The region to use + * @param region The region to use * @param currency The currency to use. * * @return The total of every {@link HoldingsEntry} for the specifications. @@ -120,34 +125,35 @@ public BigDecimal getHoldingsTotal(final @NotNull String region, } /** - * Used to get the holdings based on specific specifications, or returns an empty optional - * if no holdings for the specifications exists. + * Used to get the holdings based on specific specifications, or returns an empty optional if no + * holdings for the specifications exists. * - * @param region The region to use + * @param region The region to use * @param currency The currency to use. * - * @return The holdings based on specific specifications, or an empty optional if no - * holdings for the specifications exists. + * @return The holdings based on specific specifications, or an empty optional if no holdings for + * the specifications exists. */ public List getHoldings(final @NotNull String region, - final @NotNull UUID currency) { + final @NotNull UUID currency) { + return getHoldings(region, currency, EconomyManager.NORMAL); } /** - * Used to get the holdings based on specific specifications, or returns an empty optional - * if no holdings for the specifications exists. + * Used to get the holdings based on specific specifications, or returns an empty optional if no + * holdings for the specifications exists. * - * @param region The region to use + * @param region The region to use * @param currency The currency to use. - * @param type The {@link Identifier identifier} of the holdings handler to use. + * @param type The {@link Identifier identifier} of the holdings handler to use. * - * @return The holdings based on specific specifications, or an empty optional if no - * holdings for the specifications exists. + * @return The holdings based on specific specifications, or an empty optional if no holdings for + * the specifications exists. */ public List getHoldings(final @NotNull String region, - final @NotNull UUID currency, - final @NotNull Identifier type) { + final @NotNull UUID currency, + final @NotNull Identifier type) { final Optional currencyObject = TNECore.eco().currency().findCurrency(currency); @@ -159,14 +165,14 @@ public List getHoldings(final @NotNull String region, } /** - * Used to get the holdings based on specific specifications, or returns an empty optional - * if no holdings for the specifications exists. + * Used to get the holdings based on specific specifications, or returns an empty optional if no + * holdings for the specifications exists. * * @param region The region to use - * @param type The {@link Identifier identifier} of the holdings handler to use. + * @param type The {@link Identifier identifier} of the holdings handler to use. * - * @return The holdings based on specific specifications, or an empty optional if no - * holdings for the specifications exists. + * @return The holdings based on specific specifications, or an empty optional if no holdings for + * the specifications exists. */ public List getAllHoldings(final @NotNull String region, final @NotNull Identifier type) { @@ -186,16 +192,19 @@ public List getAllHoldings(final @NotNull String region, /** * Sets the holdings for the specified entry in this wallet. + * * @param entry The entry to set in this wallet. */ public boolean setHoldings(final @NotNull HoldingsEntry entry) { + return setHoldings(entry, EconomyManager.NORMAL); } /** * Sets the holdings for the specified entry and in this wallet. + * * @param entry The entry to set in this wallet. - * @param type The {@link Identifier identifier} of the holdings handler to use. + * @param type The {@link Identifier identifier} of the holdings handler to use. */ public boolean setHoldings(final @NotNull HoldingsEntry entry, final @NotNull Identifier type) { @@ -207,10 +216,10 @@ public boolean setHoldings(final @NotNull HoldingsEntry entry, final @NotNull Id if(currencyObject.isPresent()) { result = currencyObject.get().type().setHoldings(this, - region, - currencyObject.get(), - type, - entry.getAmount()); + region, + currencyObject.get(), + type, + entry.getAmount()); } if(result) { @@ -231,46 +240,57 @@ public boolean setHoldings(final @NotNull HoldingsEntry entry, final @NotNull Id @MapKey public UUID getIdentifier() { + return identifier; } public String getName() { + return name; } public void setName(String name) { + this.name = name; } public long getCreationDate() { + return creationDate; } public void setCreationDate(long creationDate) { + this.creationDate = creationDate; } public String getPin() { + return pin; } public void setPin(String pin) { + this.pin = pin; } public AccountStatus getStatus() { + return status; } public void setStatus(AccountStatus status) { + this.status = status; } public Wallet getWallet() { + return wallet; } public void setWallet(Wallet wallet) { + this.wallet = wallet; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/account/AccountStatus.java b/Core/src/net/tnemc/core/account/AccountStatus.java index 1cd62f29..962235f2 100644 --- a/Core/src/net/tnemc/core/account/AccountStatus.java +++ b/Core/src/net/tnemc/core/account/AccountStatus.java @@ -22,12 +22,12 @@ import org.jetbrains.annotations.NotNull; /** - * Represents the status of an {@link Account accout}. The account - * status affects things such as using the balance and receiving payments. + * Represents the status of an {@link Account accout}. The account status affects things such as + * using the balance and receiving payments. * + * @author creatorfromhell * @see Account * @since 0.1.2.0 - * @author creatorfromhell */ public interface AccountStatus { @@ -35,7 +35,8 @@ public interface AccountStatus { * @return The identifier of this account status. */ @MapKey - @NotNull String identifier(); + @NotNull + String identifier(); /** * Whether this status can be unlocked by entering the account's pin. @@ -46,12 +47,14 @@ public interface AccountStatus { /** * Whether the account may use money from their account. + * * @return True if the account is able to use funds from its balance, otherwise false. */ boolean use(); /** * Whether the account may receive money into their account. + * * @return True if the account is able to receive funds into its balance, otherwise false. */ boolean receive(); diff --git a/Core/src/net/tnemc/core/account/AccountTypeCheck.java b/Core/src/net/tnemc/core/account/AccountTypeCheck.java index f485fd5f..51004e0c 100644 --- a/Core/src/net/tnemc/core/account/AccountTypeCheck.java +++ b/Core/src/net/tnemc/core/account/AccountTypeCheck.java @@ -29,8 +29,8 @@ public interface AccountTypeCheck { /** - * Returns our check function that should be used to check if a given String identifier, usually name, - * is valid for this account type. + * Returns our check function that should be used to check if a given String identifier, usually + * name, is valid for this account type. * * @return Our function that should be used to check if a given String identifier, usually name, * is valid for this account type. diff --git a/Core/src/net/tnemc/core/account/GeyserAccount.java b/Core/src/net/tnemc/core/account/GeyserAccount.java index 676a6587..06974d09 100644 --- a/Core/src/net/tnemc/core/account/GeyserAccount.java +++ b/Core/src/net/tnemc/core/account/GeyserAccount.java @@ -29,6 +29,7 @@ public class GeyserAccount extends PlayerAccount { public GeyserAccount(UUID identifier, String name) { + super(identifier, name); } @@ -39,6 +40,7 @@ public GeyserAccount(UUID identifier, String name) { */ @Override public String type() { + return "bedrock"; } } diff --git a/Core/src/net/tnemc/core/account/NonPlayerAccount.java b/Core/src/net/tnemc/core/account/NonPlayerAccount.java index 3d4dc2d7..cb0921bb 100644 --- a/Core/src/net/tnemc/core/account/NonPlayerAccount.java +++ b/Core/src/net/tnemc/core/account/NonPlayerAccount.java @@ -24,13 +24,14 @@ /** * Represents an account that is not associated with a player. * - * @see Account * @author creatorfromhell + * @see Account * @since 0.1.2.0 */ public class NonPlayerAccount extends SharedAccount { public NonPlayerAccount(UUID identifier, String name) { + super(identifier, name, null); this.identifier = generateIdentifier(name); @@ -43,10 +44,12 @@ public NonPlayerAccount(UUID identifier, String name) { */ @Override public String type() { + return "non-player"; } public UUID generateIdentifier(final String name) { + return UUID.nameUUIDFromBytes(("NonPlayer:" + name).getBytes(StandardCharsets.UTF_8)); } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/account/PlayerAccount.java b/Core/src/net/tnemc/core/account/PlayerAccount.java index 9093b58a..456e18cf 100644 --- a/Core/src/net/tnemc/core/account/PlayerAccount.java +++ b/Core/src/net/tnemc/core/account/PlayerAccount.java @@ -29,8 +29,8 @@ /** * Represents an account that is associated with a player. * - * @see Account * @author creatorfromhell + * @see Account * @since 0.1.2.0 */ public class PlayerAccount extends Account { @@ -40,6 +40,7 @@ public class PlayerAccount extends Account { protected String language; public PlayerAccount(UUID identifier, String name) { + super(identifier, name); this.uuid = identifier; @@ -50,6 +51,7 @@ public PlayerAccount(UUID identifier, String name) { } public String region() { + String region = TNECore.eco().region().defaultRegion(); final Optional player = getPlayer(); @@ -62,10 +64,11 @@ public String region() { /** * Attempts to find a {@link PlayerProvider player} based on an {@link UUID identifier}. * - * @return An Optional containing the located {@link PlayerProvider player}, or an empty - * Optional if no player is located. + * @return An Optional containing the located {@link PlayerProvider player}, or an empty Optional + * if no player is located. */ public Optional getPlayer() { + return PluginCore.server().findPlayer(uuid); } @@ -77,6 +80,7 @@ public Optional getPlayer() { * holder is offline. */ public Optional location() { + if(getPlayer().isEmpty()) { return Optional.empty(); } @@ -90,30 +94,37 @@ public Optional location() { */ @Override public String type() { + return "player"; } public boolean isOnline() { + return getPlayer().isPresent(); } public UUID getUUID() { + return uuid; } public long getLastOnline() { + return lastOnline; } public void setLastOnline(long lastOnline) { + this.lastOnline = lastOnline; } public String getLanguage() { + return language; } public void setLanguage(String language) { + this.language = language; } } diff --git a/Core/src/net/tnemc/core/account/SharedAccount.java b/Core/src/net/tnemc/core/account/SharedAccount.java index 9440d64c..3a6dccb4 100644 --- a/Core/src/net/tnemc/core/account/SharedAccount.java +++ b/Core/src/net/tnemc/core/account/SharedAccount.java @@ -28,8 +28,8 @@ /** * Represents an Account object that is shared by multiple players. * - * @see Account * @author creatorfromhell + * @see Account * @since 0.1.2.0 */ public class SharedAccount extends Account { @@ -42,6 +42,7 @@ public class SharedAccount extends Account { protected UUID owner; public SharedAccount(UUID identifier, String name, UUID owner) { + super(identifier, name); this.owner = owner; @@ -49,22 +50,26 @@ public SharedAccount(UUID identifier, String name, UUID owner) { /** * Checks if the specified identifier is a member of this account. + * * @param identifier The identifier to check. + * * @return True if the specified identifier is a member, otherwise false. */ public boolean isMember(UUID identifier) { + return owner.equals(identifier) || members.containsKey(identifier); } /** - * Used to find a specific {@link Member member} of this account if it - * exists. + * Used to find a specific {@link Member member} of this account if it exists. * * @param identifier The identifier to use for the search. - * @return An Optional containing the {@link Member member} if exists, otherwise an - * empty Optional. + * + * @return An Optional containing the {@link Member member} if exists, otherwise an empty + * Optional. */ public Optional findMember(UUID identifier) { + return Optional.ofNullable(members.get(identifier)); } @@ -73,9 +78,10 @@ public Optional findMember(UUID identifier) { * * @param identifier The identifier of the member to use. * @param permission The permission to set. - * @param value The value to set for the permission. + * @param value The value to set for the permission. */ public void addPermission(UUID identifier, Permission permission, boolean value) { + final Member member = members.getOrDefault(identifier, new Member(identifier)); member.addPermission(permission, value); members.put(identifier, member); @@ -86,9 +92,10 @@ public void addPermission(UUID identifier, Permission permission, boolean value) * * @param identifier The identifier of the member to use. * @param permission The permission to set. - * @param value The value to set for the permission. + * @param value The value to set for the permission. */ public void addPermission(UUID identifier, String permission, boolean value) { + final Member member = members.getOrDefault(identifier, new Member(identifier)); member.addPermission(permission, value); members.put(identifier, member); @@ -101,6 +108,7 @@ public void addPermission(UUID identifier, String permission, boolean value) { * @param permission The permission to set. */ public void removePermission(UUID identifier, Permission permission) { + findMember(identifier).ifPresent(mem->mem.removePermission(permission)); } @@ -111,6 +119,7 @@ public void removePermission(UUID identifier, Permission permission) { * @param permission The permission to set. */ public void removePermission(UUID identifier, String permission) { + findMember(identifier).ifPresent(mem->mem.removePermission(permission)); } @@ -119,23 +128,28 @@ public void removePermission(UUID identifier, String permission) { * * @param identifier The identifier of the member to use. * @param permission The permission to we are checking for. + * * @return True if the specified member has the specified permission, otherwise false. */ public boolean hasPermission(UUID identifier, Permission permission) { + if(owner.equals(identifier)) return true; return findMember(identifier).map(value->value.hasPermission(permission)) - .orElseGet(permission::defaultValue); + .orElseGet(permission::defaultValue); } /** * Checks if the specified member has the specified permission. * - * @param identifier The identifier of the member to use. - * @param permission The permission to we are checking for. - * @param defaultValue The default value to return if this account doesn't contain the permission. + * @param identifier The identifier of the member to use. + * @param permission The permission to we are checking for. + * @param defaultValue The default value to return if this account doesn't contain the + * permission. + * * @return True if the specified member has the specified permission, otherwise false. */ public boolean hasPermission(UUID identifier, String permission, boolean defaultValue) { + if(owner.equals(identifier)) return true; return findMember(identifier).map(value->value.hasPermission(permission, defaultValue)).orElse(defaultValue); } @@ -147,18 +161,22 @@ public boolean hasPermission(UUID identifier, String permission, boolean default */ @Override public String type() { + return "shared"; } public ConcurrentHashMap getMembers() { + return members; } public UUID getOwner() { + return owner; } public void setOwner(UUID owner) { + this.owner = owner; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/account/holdings/CurrencyHoldings.java b/Core/src/net/tnemc/core/account/holdings/CurrencyHoldings.java index a9186ac8..2b9d9b52 100644 --- a/Core/src/net/tnemc/core/account/holdings/CurrencyHoldings.java +++ b/Core/src/net/tnemc/core/account/holdings/CurrencyHoldings.java @@ -37,23 +37,29 @@ public class CurrencyHoldings { /** * Used to add {@link HoldingsEntry holdings} for a specific {@link Identifier}. - * @param type The type to add the holdings to. + * + * @param type The type to add the holdings to. * @param entry The holdings to add to the type. */ public void setHoldingsEntry(final @NotNull HoldingsEntry entry, final @NotNull Identifier type) { + holdings.put(type.asID(), entry); } /** * Used to get the {@link HoldingsEntry holdings} for a specific {@link Identifier}. + * * @param type The type to add the holdings to. + * * @return The {@link HoldingsEntry} if it belongs, or an empty optional if it doesn't. */ public Optional getHoldingsEntry(final @NotNull Identifier type) { + return Optional.ofNullable(holdings.get(type.asID())); } public Map getHoldings() { + return holdings; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/account/holdings/HoldingsEntry.java b/Core/src/net/tnemc/core/account/holdings/HoldingsEntry.java index 6bc4cf13..24bfff32 100644 --- a/Core/src/net/tnemc/core/account/holdings/HoldingsEntry.java +++ b/Core/src/net/tnemc/core/account/holdings/HoldingsEntry.java @@ -64,13 +64,14 @@ public class HoldingsEntry { /** * Constructs an object that represents a holding's entry. * - * @param region The name of the region involved. This is usually a world, but could be something - * else such as a world guard region name/identifier. + * @param region The name of the region involved. This is usually a world, but could be + * something else such as a world guard region name/identifier. * @param currency The identifier of the currency involved. - * @param amount The {@link BigDecimal amount} that this charge is for. + * @param amount The {@link BigDecimal amount} that this charge is for. */ public HoldingsEntry(final @NotNull String region, final @NotNull UUID currency, final @NotNull BigDecimal amount, final @NotNull Identifier handler) { + this.region = region; this.currency = currency; this.amount = amount; @@ -83,52 +84,63 @@ public HoldingsEntry(final @NotNull String region, final @NotNull UUID currency, * @param modifier The modifier to build this entry from. */ public HoldingsEntry(final @NotNull HoldingsModifier modifier) { + this.region = modifier.getRegion(); this.currency = modifier.getCurrency(); this.amount = modifier.getModifier(); } public void modify(final HoldingsModifier modifier) { + amount = modifier.modify(amount); } public HoldingsEntry modifyGrab(final BigDecimal modifier) { + HoldingsEntry entry = new HoldingsEntry(region, currency, amount, handler); entry.modify(new HoldingsModifier(region, currency, modifier)); return entry; } public HoldingsEntry modifyGrab(final HoldingsModifier modifier) { + HoldingsEntry entry = new HoldingsEntry(region, currency, amount, handler); entry.modify(modifier); return entry; } public Optional currency() { + return TNECore.eco().currency().findCurrency(currency); } public UUID getCurrency() { + return currency; } public void setCurrency(UUID currency) { + this.currency = currency; } public String getRegion() { + return region; } public void setRegion(String region) { + this.region = region; } public BigDecimal getAmount() { + return amount; } public Monetary asMonetary() { + if(monetary != null) { return monetary; } @@ -138,16 +150,19 @@ public Monetary asMonetary() { } public void setAmount(BigDecimal amount) { + this.amount = amount; final Optional cur = currency(); monetary = new Monetary(amount, cur.map(Currency::getDecimalPlaces).orElse(2)); } public Identifier getHandler() { + return handler; } public void setHandler(Identifier handler) { + this.handler = handler; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/account/holdings/HoldingsHandler.java b/Core/src/net/tnemc/core/account/holdings/HoldingsHandler.java index cc91385c..db4911a7 100644 --- a/Core/src/net/tnemc/core/account/holdings/HoldingsHandler.java +++ b/Core/src/net/tnemc/core/account/holdings/HoldingsHandler.java @@ -29,22 +29,25 @@ * HoldingsHandler represents a handler that could provide additional holding types. * * @author creatorfromhell - * @since 0.1.2.0 * @see Account * @see CurrencyType * @see Identifier + * @since 0.1.2.0 */ public interface HoldingsHandler { /** * The identifier for this handler. + * * @return The identifier that represents this handler. */ Identifier identifier(); /** * Used to determine if this handler may be used for the specified {@link CurrencyType}. + * * @param type The currency type. + * * @return True if it supports the currency type, otherwise false. */ boolean supports(CurrencyType type); @@ -52,18 +55,22 @@ public interface HoldingsHandler { /** * Used to determine if this handler may be used for the specified {@link Account}. This defaults * to true for all accounts. + * * @param account The account. + * * @return True if it supports the account, otherwise false. */ default boolean appliesTo(Account account) { + return true; } /** - * @return If balances of this handler should be saved to the database. Return false to do - * your own data handling. + * @return If balances of this handler should be saved to the database. Return false to do your + * own data handling. */ default boolean database() { + return true; } @@ -71,11 +78,11 @@ default boolean database() { * Used to set the holdings for a specific account. * * @param account The account. - * @param region The name of the region involved. This is usually a world, but could be something - * else such as a world guard region name/identifier. + * @param region The name of the region involved. This is usually a world, but could be + * something else such as a world guard region name/identifier. * @param currency The instance of the currency to use. - * @param type The currency type. - * @param amount The amount to set the player's holdings to. + * @param type The currency type. + * @param amount The amount to set the player's holdings to. * * @return True if the holdings have been set, otherwise false. */ @@ -84,11 +91,12 @@ default boolean database() { /** * Used to get the holdings for a specific account from this handler. * - * @param account The Account. - * @param region The name of the region involved. This is usually a world, but could be something - * else such as a world guard region name/identifier. + * @param account The Account. + * @param region The name of the region involved. This is usually a world, but could be + * something else such as a world guard region name/identifier. * @param currency The instance of the currency to use. - * @param type The currency type. + * @param type The currency type. + * * @return The holdings for the specific account. */ HoldingsEntry getHoldings(Account account, String region, Currency currency, CurrencyType type); diff --git a/Core/src/net/tnemc/core/account/holdings/RegionHoldings.java b/Core/src/net/tnemc/core/account/holdings/RegionHoldings.java index 5f17fd37..dcc0c388 100644 --- a/Core/src/net/tnemc/core/account/holdings/RegionHoldings.java +++ b/Core/src/net/tnemc/core/account/holdings/RegionHoldings.java @@ -40,11 +40,12 @@ public class RegionHoldings { * Sets the holdings entry for a specific type in the currency holdings map. * * @param entry The holdings entry to set. - * @param type The type of identifier to associate the entry with. + * @param type The type of identifier to associate the entry with. */ public void setHoldingsEntry(final HoldingsEntry entry, final Identifier type) { + final CurrencyHoldings currencyHoldings = - holdings.getOrDefault(entry.getCurrency(), new CurrencyHoldings()); + holdings.getOrDefault(entry.getCurrency(), new CurrencyHoldings()); currencyHoldings.setHoldingsEntry(entry, type); @@ -55,9 +56,12 @@ public void setHoldingsEntry(final HoldingsEntry entry, final Identifier type) { * Retrieves the holdings entry for the specified currency. * * @param currency The identifier of the currency for which to retrieve the holdings entry. - * @return An Optional object containing the holdings entry if it exists, or an empty Optional if it does not exist. + * + * @return An Optional object containing the holdings entry if it exists, or an empty Optional if + * it does not exist. */ public Optional getHoldingsEntry(final UUID currency) { + return getHoldingsEntry(currency, EconomyManager.NORMAL); } @@ -65,10 +69,13 @@ public Optional getHoldingsEntry(final UUID currency) { * Retrieves the holdings entry for the specified currency and type. * * @param currency The identifier of the currency for which to retrieve the holdings entry. - * @param type The type identifier associated with the holdings entry. - * @return An Optional object containing the holdings entry if it exists, or an empty Optional if it does not exist. + * @param type The type identifier associated with the holdings entry. + * + * @return An Optional object containing the holdings entry if it exists, or an empty Optional if + * it does not exist. */ public Optional getHoldingsEntry(final UUID currency, final Identifier type) { + if(holdings.containsKey(currency)) { return holdings.get(currency).getHoldingsEntry(type); } @@ -76,14 +83,15 @@ public Optional getHoldingsEntry(final UUID currency, final Ident } /** - * Returns the holdings map which keeps track of regional holdings for an account. - * The map is structured as follows: - * - Key: UUID of the currency - * - Value: CurrencyHoldings object that represents the holdings for that currency + * Returns the holdings map which keeps track of regional holdings for an account. The map is + * structured as follows: - Key: UUID of the currency - Value: CurrencyHoldings object that + * represents the holdings for that currency * - * @return Returns a map of UUIDs to CurrencyHoldings objects representing the holdings for each currency. + * @return Returns a map of UUIDs to CurrencyHoldings objects representing the holdings for each + * currency. */ public Map getHoldings() { + return holdings; } @@ -91,9 +99,11 @@ public Map getHoldings() { * Determines if the specified currency is contained in the holdings map. * * @param currency The identifier of the currency to check. + * * @return {@code true} if the currency is contained in the holdings map, {@code false} otherwise. */ public boolean containsCurrency(final UUID currency) { + return holdings.containsKey(currency); } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/account/holdings/Wallet.java b/Core/src/net/tnemc/core/account/holdings/Wallet.java index ddb8959b..6aebafc6 100644 --- a/Core/src/net/tnemc/core/account/holdings/Wallet.java +++ b/Core/src/net/tnemc/core/account/holdings/Wallet.java @@ -41,47 +41,50 @@ public class Wallet { private final Map holdings = new ConcurrentHashMap<>(); /** - * Used to get the holdings based on specific specifications, or returns an empty optional - * if no holdings for the specifications exists. + * Used to get the holdings based on specific specifications, or returns an empty optional if no + * holdings for the specifications exists. * * @param region The region to use * - * @return The holdings based on specific specifications, or an empty optional if no - * holdings for the specifications exists. + * @return The holdings based on specific specifications, or an empty optional if no holdings for + * the specifications exists. */ public Optional getHoldings(final @NotNull String region) { + return Optional.ofNullable(holdings.get(region)); } /** - * Used to get the holdings based on specific specifications, or returns an empty optional - * if no holdings for the specifications exists. + * Used to get the holdings based on specific specifications, or returns an empty optional if no + * holdings for the specifications exists. * - * @param region The region to use + * @param region The region to use * @param currency The currency to use. * - * @return The holdings based on specific specifications, or an empty optional if no - * holdings for the specifications exists. + * @return The holdings based on specific specifications, or an empty optional if no holdings for + * the specifications exists. */ public Optional getHoldings(final @NotNull String region, final @NotNull UUID currency) { + return getHoldings(region, currency, EconomyManager.NORMAL); } /** - * Used to get the holdings based on specific specifications, or returns an empty optional - * if no holdings for the specifications exists. + * Used to get the holdings based on specific specifications, or returns an empty optional if no + * holdings for the specifications exists. * - * @param region The region to use + * @param region The region to use * @param currency The currency to use. - * @param type The {@link Identifier type} to use. + * @param type The {@link Identifier type} to use. * - * @return The holdings based on specific specifications, or an empty optional if no - * holdings for the specifications exists. + * @return The holdings based on specific specifications, or an empty optional if no holdings for + * the specifications exists. */ public Optional getHoldings(final @NotNull String region, final @NotNull UUID currency, final @NotNull Identifier type) { + if(holdings.containsKey(region)) { return holdings.get(region).getHoldingsEntry(currency, type); } @@ -92,18 +95,19 @@ public Optional getHoldings(final @NotNull String region, * Used to get the holdings based on specific specifications, or returns the specified default * value if no holdings for the specifications exists. * - * @param region The region to use - * @param currency The currency to use. - * @param type The {@link Identifier type} to use. + * @param region The region to use + * @param currency The currency to use. + * @param type The {@link Identifier type} to use. * @param defaultValue The default value to return if nothing exists. * * @return The holdings based on specific specifications, or the specified default value if no * holdings for the specifications exists. */ public HoldingsEntry getHoldings(final @NotNull String region, - final @NotNull UUID currency, - final @NotNull Identifier type, - final @NotNull HoldingsEntry defaultValue) { + final @NotNull UUID currency, + final @NotNull Identifier type, + final @NotNull HoldingsEntry defaultValue) { + if(holdings.containsKey(region)) { return holdings.get(region).getHoldingsEntry(currency, type).orElse(defaultValue); } @@ -112,6 +116,7 @@ public HoldingsEntry getHoldings(final @NotNull String region, /** * Sets the holdings for the specified entry and in this wallet. + * * @param entry The entry to set in this wallet. */ public void setHoldings(final @NotNull HoldingsEntry entry) { @@ -130,6 +135,7 @@ public void setHoldings(final @NotNull HoldingsEntry entry) { * @param modifier The modifier to use */ public void modifyHoldings(final @NotNull HoldingsModifier modifier) { + modifyHoldings(modifier, EconomyManager.NORMAL); } @@ -138,7 +144,7 @@ public void modifyHoldings(final @NotNull HoldingsModifier modifier) { * currency and type it will set the holdings to the modifier. * * @param modifier The modifier to use - * @param type The type to use. + * @param type The type to use. */ public void modifyHoldings(final @NotNull HoldingsModifier modifier, Identifier type) { @@ -154,18 +160,22 @@ public void modifyHoldings(final @NotNull HoldingsModifier modifier, Identifier /** * Used to delete specific holdings from this wallet holder. + * * @param region The region from which to delete the holdings */ public void deleteHoldings(final @NotNull String region) { + holdings.remove(region); } /** * Used to delete specific holdings from this wallet holder. - * @param region The region from which to delete the holdings + * + * @param region The region from which to delete the holdings * @param currency The currency from which to delete the holdings */ public void deleteHoldings(final @NotNull String region, final @NotNull UUID currency) { + if(holdings.containsKey(region)) { holdings.get(region).getHoldings().remove(currency); } @@ -173,9 +183,10 @@ public void deleteHoldings(final @NotNull String region, final @NotNull UUID cur /** * Used to delete specific holdings from this wallet holder. - * @param region The region from which to delete the holdings + * + * @param region The region from which to delete the holdings * @param currency The currency from which to delete the holdings - * @param type The {@link Identifier type} from which to delete the holdings. + * @param type The {@link Identifier type} from which to delete the holdings. */ public void deleteHoldings(final @NotNull String region, final @NotNull UUID currency, @@ -188,15 +199,18 @@ public void deleteHoldings(final @NotNull String region, //delete all holdings public void deleteAllHoldings() { + holdings.clear(); } /** * Used to merge another {@link Wallet wallet} into this one. After it has been merged, the old * wallet will have all of its holdings cleared. + * * @param wallet The other wallet to merge. */ public void merge(@NotNull Wallet wallet) { + for(RegionHoldings region : wallet.getHoldings().values()) { for(CurrencyHoldings currency : region.getHoldings().values()) { for(Map.Entry entry : currency.getHoldings().entrySet()) { @@ -211,11 +225,13 @@ public void merge(@NotNull Wallet wallet) { /** * Checks if the specified region contains the given currency in the wallet. * - * @param region The region to check. + * @param region The region to check. * @param currency The currency to check. + * * @return true if the region contains the currency in the wallet, false otherwise. */ public boolean contains(final @NotNull String region, final @NotNull UUID currency) { + return holdings.containsKey(region) && holdings.get(region).containsCurrency(currency); } @@ -242,9 +258,11 @@ public List entryList() { /** * Retrieves the holdings map for the wallet. * - * @return A map of region names to RegionHoldings objects representing the holdings for each region. + * @return A map of region names to RegionHoldings objects representing the holdings for each + * region. */ public Map getHoldings() { + return holdings; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/account/holdings/handlers/EnderChestHandler.java b/Core/src/net/tnemc/core/account/holdings/handlers/EnderChestHandler.java index ac48dab6..9b5b8252 100644 --- a/Core/src/net/tnemc/core/account/holdings/handlers/EnderChestHandler.java +++ b/Core/src/net/tnemc/core/account/holdings/handlers/EnderChestHandler.java @@ -50,6 +50,7 @@ public class EnderChestHandler implements HoldingsHandler { */ @Override public Identifier identifier() { + return EconomyManager.E_CHEST; } @@ -62,6 +63,7 @@ public Identifier identifier() { */ @Override public boolean supports(CurrencyType type) { + return type.supportsItems(); } @@ -69,8 +71,8 @@ public boolean supports(CurrencyType type) { * Used to set the holdings for a specific account. * * @param account The account. - * @param region The name of the region involved. This is usually a world, but could be something - * else such as a world guard region name/identifier. + * @param region The name of the region involved. This is usually a world, but could be + * something else such as a world guard region name/identifier. * @param currency The instance of the currency to use. * @param type The currency type. * @param amount The amount to set the player's holdings to. @@ -85,7 +87,7 @@ public boolean setHoldings(Account account, String region, Currency currency, Cu if(account.isPlayer() && PluginCore.server().online(account.getIdentifier().toString()) && !TNECore.eco().account().getImporting().contains(account.getIdentifier())) { final CalculationData data = new CalculationData<>((ItemCurrency)currency, ((PlayerAccount)account).getPlayer() - .get().inventory().getInventory(true), + .get().inventory().getInventory(true), ((PlayerAccount)account).getUUID()); TNECore.instance().itemCalculations().setItems(data, amount); return true; @@ -97,8 +99,8 @@ public boolean setHoldings(Account account, String region, Currency currency, Cu * Used to get the holdings for a specific account from this handler. * * @param account The Account. - * @param region The name of the region involved. This is usually a world, but could be something - * else such as a world guard region name/identifier. + * @param region The name of the region involved. This is usually a world, but could be + * something else such as a world guard region name/identifier. * @param currency The instance of the currency to use. * @param type The currency type. * @@ -106,16 +108,17 @@ public boolean setHoldings(Account account, String region, Currency currency, Cu */ @Override public HoldingsEntry getHoldings(Account account, String region, Currency currency, CurrencyType type) { + if((currency instanceof ItemCurrency) && account.isPlayer()) { if(!PluginCore.server().online(account.getIdentifier().toString()) || - TNECore.eco().account().getLoading().contains(account.getIdentifier()) - && !TNECore.eco().account().getImporting().contains(account.getIdentifier())) { + TNECore.eco().account().getLoading().contains(account.getIdentifier()) + && !TNECore.eco().account().getImporting().contains(account.getIdentifier())) { //Offline players have their balances saved to their wallet so check it. final Optional holdings = account.getWallet().getHoldings(region, currency.getUid(), identifier() - ); + ); PluginCore.log().debug("Getting holdings from DB", DebugLevel.DEVELOPER); if(holdings.isPresent()) { @@ -129,7 +132,7 @@ public HoldingsEntry getHoldings(Account account, String region, Currency curren PluginCore.log().debug("Getting holdings from Ender Chest", DebugLevel.DEVELOPER); final CalculationData data = new CalculationData<>((ItemCurrency)currency, ((PlayerAccount)account).getPlayer() - .get().inventory().getInventory(true), + .get().inventory().getInventory(true), ((PlayerAccount)account).getUUID()); return new HoldingsEntry(region, currency.getUid(), diff --git a/Core/src/net/tnemc/core/account/holdings/handlers/ExperienceHandler.java b/Core/src/net/tnemc/core/account/holdings/handlers/ExperienceHandler.java index 361cdabd..514ec9fc 100644 --- a/Core/src/net/tnemc/core/account/holdings/handlers/ExperienceHandler.java +++ b/Core/src/net/tnemc/core/account/holdings/handlers/ExperienceHandler.java @@ -40,6 +40,7 @@ * @since 0.1.2.0 */ public class ExperienceHandler implements HoldingsHandler { + /** * The identifier for this handler. * @@ -47,6 +48,7 @@ public class ExperienceHandler implements HoldingsHandler { */ @Override public Identifier identifier() { + return EXPERIENCE; } @@ -59,6 +61,7 @@ public Identifier identifier() { */ @Override public boolean supports(CurrencyType type) { + return (type instanceof ExperienceType); } @@ -66,8 +69,8 @@ public boolean supports(CurrencyType type) { * Used to set the holdings for a specific account. * * @param account The account. - * @param region The name of the region involved. This is usually a world, but could be something - * else such as a world guard region name/identifier. + * @param region The name of the region involved. This is usually a world, but could be + * something else such as a world guard region name/identifier. * @param currency The instance of the currency to use. * @param type The currency type. * @param amount The amount to set the player's holdings to. @@ -76,6 +79,7 @@ public boolean supports(CurrencyType type) { */ @Override public boolean setHoldings(Account account, String region, Currency currency, CurrencyType type, BigDecimal amount) { + account.getWallet().setHoldings(new HoldingsEntry(region, currency.getUid(), amount, identifier())); if(account.isPlayer() && ((PlayerAccount)account).isOnline()) { Experience.setExperience(((PlayerAccount)account).getPlayer().get(), amount.intValueExact()); @@ -87,8 +91,8 @@ public boolean setHoldings(Account account, String region, Currency currency, Cu * Used to get the holdings for a specific account from this handler. * * @param account The Account. - * @param region The name of the region involved. This is usually a world, but could be something - * else such as a world guard region name/identifier. + * @param region The name of the region involved. This is usually a world, but could be + * something else such as a world guard region name/identifier. * @param currency The instance of the currency to use. * @param type The currency type. * @@ -96,12 +100,13 @@ public boolean setHoldings(Account account, String region, Currency currency, Cu */ @Override public HoldingsEntry getHoldings(Account account, String region, Currency currency, CurrencyType type) { + if(!account.isPlayer() || !((PlayerAccount)account).isOnline()) { //Offline players/non-players have their balances saved to their wallet so check it. final Optional holdings = account.getWallet().getHoldings(region, currency.getUid(), EXPERIENCE - ); + ); return holdings.orElseGet(()->new HoldingsEntry(region, currency.getUid(), diff --git a/Core/src/net/tnemc/core/account/holdings/handlers/ExperienceLevelHandler.java b/Core/src/net/tnemc/core/account/holdings/handlers/ExperienceLevelHandler.java index 258da8fa..a20a6508 100644 --- a/Core/src/net/tnemc/core/account/holdings/handlers/ExperienceLevelHandler.java +++ b/Core/src/net/tnemc/core/account/holdings/handlers/ExperienceLevelHandler.java @@ -41,6 +41,7 @@ * @since 0.1.2.0 */ public class ExperienceLevelHandler implements HoldingsHandler { + /** * The identifier for this handler. * @@ -48,6 +49,7 @@ public class ExperienceLevelHandler implements HoldingsHandler { */ @Override public Identifier identifier() { + return EXPERIENCE_LEVEL; } @@ -60,6 +62,7 @@ public Identifier identifier() { */ @Override public boolean supports(CurrencyType type) { + return (type instanceof ExperienceLevelType); } @@ -67,8 +70,8 @@ public boolean supports(CurrencyType type) { * Used to set the holdings for a specific account. * * @param account The account. - * @param region The name of the region involved. This is usually a world, but could be something - * else such as a world guard region name/identifier. + * @param region The name of the region involved. This is usually a world, but could be + * something else such as a world guard region name/identifier. * @param currency The instance of the currency to use. * @param type The currency type. * @param amount The amount to set the player's holdings to. @@ -77,6 +80,7 @@ public boolean supports(CurrencyType type) { */ @Override public boolean setHoldings(Account account, String region, Currency currency, CurrencyType type, BigDecimal amount) { + account.getWallet().setHoldings(new HoldingsEntry(region, currency.getUid(), amount, identifier())); if(account instanceof PlayerAccount player && player.isOnline() && player.getPlayer().isPresent()) { @@ -89,8 +93,8 @@ public boolean setHoldings(Account account, String region, Currency currency, Cu * Used to get the holdings for a specific account from this handler. * * @param account The Account. - * @param region The name of the region involved. This is usually a world, but could be something - * else such as a world guard region name/identifier. + * @param region The name of the region involved. This is usually a world, but could be + * something else such as a world guard region name/identifier. * @param currency The instance of the currency to use. * @param type The currency type. * @@ -98,6 +102,7 @@ public boolean setHoldings(Account account, String region, Currency currency, Cu */ @Override public HoldingsEntry getHoldings(Account account, String region, Currency currency, CurrencyType type) { + if(account instanceof PlayerAccount player && player.isOnline() && player.getPlayer().isPresent()) { final BigDecimal amount = new BigDecimal(player.getPlayer().get().getExpLevel()); @@ -108,14 +113,14 @@ public HoldingsEntry getHoldings(Account account, String region, Currency curren } final Optional holdings = account.getWallet().getHoldings(region, - currency.getUid(), - EXPERIENCE_LEVEL - ); + currency.getUid(), + EXPERIENCE_LEVEL + ); return holdings.orElseGet(()->new HoldingsEntry(region, - currency.getUid(), - BigDecimal.ZERO, - EXPERIENCE_LEVEL + currency.getUid(), + BigDecimal.ZERO, + EXPERIENCE_LEVEL )); } } diff --git a/Core/src/net/tnemc/core/account/holdings/handlers/InventoryHandler.java b/Core/src/net/tnemc/core/account/holdings/handlers/InventoryHandler.java index c45d50d4..803f3c7c 100644 --- a/Core/src/net/tnemc/core/account/holdings/handlers/InventoryHandler.java +++ b/Core/src/net/tnemc/core/account/holdings/handlers/InventoryHandler.java @@ -50,6 +50,7 @@ public class InventoryHandler implements HoldingsHandler { */ @Override public Identifier identifier() { + return EconomyManager.INVENTORY_ONLY; } @@ -62,6 +63,7 @@ public Identifier identifier() { */ @Override public boolean supports(CurrencyType type) { + return type.supportsItems(); } @@ -69,8 +71,8 @@ public boolean supports(CurrencyType type) { * Used to set the holdings for a specific account. * * @param account The account. - * @param region The name of the region involved. This is usually a world, but could be something - * else such as a world guard region name/identifier. + * @param region The name of the region involved. This is usually a world, but could be + * something else such as a world guard region name/identifier. * @param currency The instance of the currency to use. * @param type The currency type. * @param amount The amount to set the player's holdings to. @@ -79,12 +81,13 @@ public boolean supports(CurrencyType type) { */ @Override public boolean setHoldings(Account account, String region, Currency currency, CurrencyType type, BigDecimal amount) { + account.getWallet().setHoldings(new HoldingsEntry(region, currency.getUid(), amount, identifier())); if(account.isPlayer() && PluginCore.server().online(account.getIdentifier().toString()) && !TNECore.eco().account().getImporting().contains(account.getIdentifier())) { final CalculationData data = new CalculationData<>((ItemCurrency)currency, ((PlayerAccount)account).getPlayer() - .get().inventory().getInventory(false), + .get().inventory().getInventory(false), ((PlayerAccount)account).getUUID()); TNECore.instance().itemCalculations().setItems(data, amount); return true; @@ -96,8 +99,8 @@ public boolean setHoldings(Account account, String region, Currency currency, Cu * Used to get the holdings for a specific account from this handler. * * @param account The Account. - * @param region The name of the region involved. This is usually a world, but could be something - * else such as a world guard region name/identifier. + * @param region The name of the region involved. This is usually a world, but could be + * something else such as a world guard region name/identifier. * @param currency The instance of the currency to use. * @param type The currency type. * @@ -105,17 +108,18 @@ public boolean setHoldings(Account account, String region, Currency currency, Cu */ @Override public HoldingsEntry getHoldings(Account account, String region, Currency currency, CurrencyType type) { + if((currency instanceof ItemCurrency)) { if(!account.isPlayer() || !PluginCore.server().online(account.getIdentifier().toString()) || - TNECore.eco().account().getLoading().contains(account.getIdentifier()) - && !TNECore.eco().account().getImporting().contains(account.getIdentifier())) { + TNECore.eco().account().getLoading().contains(account.getIdentifier()) + && !TNECore.eco().account().getImporting().contains(account.getIdentifier())) { //Offline players have their balances saved to their wallet so check it. final Optional holdings = account.getWallet().getHoldings(region, currency.getUid(), identifier() - ); + ); PluginCore.log().debug("Getting holdings from Inventory DB", DebugLevel.DEVELOPER); if(holdings.isPresent()) { @@ -129,7 +133,7 @@ public HoldingsEntry getHoldings(Account account, String region, Currency curren PluginCore.log().debug("Getting holdings from Inventory", DebugLevel.DEVELOPER); final CalculationData data = new CalculationData<>((ItemCurrency)currency, ((PlayerAccount)account).getPlayer() - .get().inventory().getInventory(false), + .get().inventory().getInventory(false), ((PlayerAccount)account).getUUID()); return new HoldingsEntry(region, currency.getUid(), diff --git a/Core/src/net/tnemc/core/account/holdings/handlers/VirtualHandler.java b/Core/src/net/tnemc/core/account/holdings/handlers/VirtualHandler.java index b8a8ce0b..e2760c22 100644 --- a/Core/src/net/tnemc/core/account/holdings/handlers/VirtualHandler.java +++ b/Core/src/net/tnemc/core/account/holdings/handlers/VirtualHandler.java @@ -38,6 +38,7 @@ * @since 0.1.2.0 */ public class VirtualHandler implements HoldingsHandler { + /** * The identifier for this handler. * @@ -45,6 +46,7 @@ public class VirtualHandler implements HoldingsHandler { */ @Override public Identifier identifier() { + return EconomyManager.VIRTUAL; } @@ -57,6 +59,7 @@ public Identifier identifier() { */ @Override public boolean supports(CurrencyType type) { + return type.supportsVirtual(); } @@ -64,8 +67,8 @@ public boolean supports(CurrencyType type) { * Used to set the holdings for a specific account. * * @param account The account. - * @param region The name of the region involved. This is usually a world, but could be something - * else such as a world guard region name/identifier. + * @param region The name of the region involved. This is usually a world, but could be + * something else such as a world guard region name/identifier. * @param currency The instance of the currency to use. * @param type The currency type. * @param amount The amount to set the player's holdings to. @@ -74,6 +77,7 @@ public boolean supports(CurrencyType type) { */ @Override public boolean setHoldings(Account account, String region, Currency currency, CurrencyType type, BigDecimal amount) { + return true; } @@ -81,8 +85,8 @@ public boolean setHoldings(Account account, String region, Currency currency, Cu * Used to get the holdings for a specific account from this handler. * * @param account The Account. - * @param region The name of the region involved. This is usually a world, but could be something - * else such as a world guard region name/identifier. + * @param region The name of the region involved. This is usually a world, but could be + * something else such as a world guard region name/identifier. * @param currency The instance of the currency to use. * @param type The currency type. * @@ -94,7 +98,7 @@ public HoldingsEntry getHoldings(Account account, String region, Currency curren final Optional holdings = account.getWallet().getHoldings(region, currency.getUid(), EconomyManager.VIRTUAL - ); + ); PluginCore.log().debug("Getting holdings from Virtual", DebugLevel.DEVELOPER); diff --git a/Core/src/net/tnemc/core/account/holdings/modify/HoldingsModifier.java b/Core/src/net/tnemc/core/account/holdings/modify/HoldingsModifier.java index f451e936..b6654f2a 100644 --- a/Core/src/net/tnemc/core/account/holdings/modify/HoldingsModifier.java +++ b/Core/src/net/tnemc/core/account/holdings/modify/HoldingsModifier.java @@ -46,13 +46,14 @@ public class HoldingsModifier { * Represents an object that may be utilized to modify an {@link Account account's} holdings. This * class is able to then be applied directly to the holdings of an account. * - * @param region The name of the region involved. This is usually a world, but could be something - * else such as a world guard region name/identifier. + * @param region The name of the region involved. This is usually a world, but could be + * something else such as a world guard region name/identifier. * @param currency The currency to use for the modification. * @param modifier The amount we are utilizing to modify the holdings. This may be negative to * take the holdings down. */ public HoldingsModifier(final String region, final UUID currency, final BigDecimal modifier) { + this.region = region; this.currency = currency; this.modifier = modifier; @@ -64,13 +65,14 @@ public HoldingsModifier(final String region, final UUID currency, final BigDecim * Represents an object that may be utilized to modify an {@link Account account's} holdings. This * class is able to then be applied directly to the holdings of an account. * - * @param region The name of the region involved. This is usually a world, but could be something - * else such as a world guard region name/identifier. + * @param region The name of the region involved. This is usually a world, but could be + * something else such as a world guard region name/identifier. * @param currency The currency to use for the modification. * @param modifier The amount we are utilizing to modify the holdings. This may be negative to * take the holdings down. */ public HoldingsModifier(final String region, final UUID currency, final PercentBigDecimal modifier) { + this.region = region; this.currency = currency; this.modifier = modifier.value(); @@ -88,14 +90,15 @@ public HoldingsModifier(final String region, final UUID currency, final PercentB * Represents an object that may be utilized to modify an {@link Account account's} holdings. This * class is able to then be applied directly to the holdings of an account. * - * @param region The name of the region involved. This is usually a world, but could be something - * else such as a world guard region name/identifier. + * @param region The name of the region involved. This is usually a world, but could be + * something else such as a world guard region name/identifier. * @param currency The currency to use for the modification. * @param modifier The amount we are utilizing to modify the holdings. This may be negative to * take the holdings down. - * @param id The {@link Identifier} for the holdings type to perform this transaction on. + * @param id The {@link Identifier} for the holdings type to perform this transaction on. */ public HoldingsModifier(final String region, final UUID currency, final BigDecimal modifier, final Identifier id) { + this.region = region; this.currency = currency; this.modifier = modifier; @@ -107,14 +110,15 @@ public HoldingsModifier(final String region, final UUID currency, final BigDecim * Represents an object that may be utilized to modify an {@link Account account's} holdings. This * class is able to then be applied directly to the holdings of an account. * - * @param region The name of the region involved. This is usually a world, but could be something - * else such as a world guard region name/identifier. + * @param region The name of the region involved. This is usually a world, but could be + * something else such as a world guard region name/identifier. * @param currency The currency to use for the modification. * @param modifier The amount we are utilizing to modify the holdings. This may be negative to * take the holdings down. - * @param id The {@link Identifier} for the holdings type to perform this transaction on. + * @param id The {@link Identifier} for the holdings type to perform this transaction on. */ public HoldingsModifier(final String region, final UUID currency, final PercentBigDecimal modifier, final Identifier id) { + this.region = region; this.currency = currency; this.modifier = modifier.value(); @@ -135,6 +139,7 @@ public HoldingsModifier(final String region, final UUID currency, final PercentB * @param entry The holdings entry to populate this modifier from. */ public HoldingsModifier(final HoldingsEntry entry) { + this.region = entry.getRegion(); this.currency = entry.getCurrency(); this.modifier = entry.getAmount(); @@ -145,15 +150,17 @@ public HoldingsModifier(final HoldingsEntry entry) { /** * Represents an object that may be utilized to modify an {@link Account account's} holdings. This * class is able to then be applied directly to the holdings of an account. - * @param currency The currency to use for the modification. - * @param region The name of the region involved. This is usually a world, but could be something - * else such as a world guard region name/identifier. - * @param modifier The amount we are utilizing to modify the holdings. This may be negative to - * take the holdings down. + * + * @param currency The currency to use for the modification. + * @param region The name of the region involved. This is usually a world, but could be + * something else such as a world guard region name/identifier. + * @param modifier The amount we are utilizing to modify the holdings. This may be negative to + * take the holdings down. * @param operation The operation that should be performed with the modifier. */ public HoldingsModifier(final String region, final UUID currency, final BigDecimal modifier, final HoldingsOperation operation) { + this.currency = currency; this.region = region; this.modifier = modifier; @@ -164,16 +171,18 @@ public HoldingsModifier(final String region, final UUID currency, final BigDecim /** * Represents an object that may be utilized to modify an {@link Account account's} holdings. This * class is able to then be applied directly to the holdings of an account. - * @param currency The currency to use for the modification. - * @param region The name of the region involved. This is usually a world, but could be something - * else such as a world guard region name/identifier. - * @param modifier The amount we are utilizing to modify the holdings. This may be negative to - * take the holdings down. + * + * @param currency The currency to use for the modification. + * @param region The name of the region involved. This is usually a world, but could be + * something else such as a world guard region name/identifier. + * @param modifier The amount we are utilizing to modify the holdings. This may be negative to + * take the holdings down. * @param operation The operation that should be performed with the modifier. - * @param id The {@link Identifier} for the holdings type to perform this transaction on. + * @param id The {@link Identifier} for the holdings type to perform this transaction on. */ public HoldingsModifier(final String region, final UUID currency, final BigDecimal modifier, final HoldingsOperation operation, final Identifier id) { + this.currency = currency; this.region = region; this.modifier = modifier; @@ -184,10 +193,12 @@ public HoldingsModifier(final String region, final UUID currency, final BigDecim /** * Represents an object that may be utilized to modify an {@link Account account's} holdings. This * class is able to then be applied directly to the holdings of an account. - * @param entry The holdings entry to populate this modifier from. + * + * @param entry The holdings entry to populate this modifier from. * @param operation The operation that should be performed with the modifier. */ public HoldingsModifier(final HoldingsEntry entry, final HoldingsOperation operation) { + this.region = entry.getRegion(); this.currency = entry.getCurrency(); this.modifier = entry.getAmount(); @@ -198,9 +209,11 @@ public HoldingsModifier(final HoldingsEntry entry, final HoldingsOperation opera /** * Returns a new {@link HoldingsModifier} object that is the opposite in terms of amount from this * one. + * * @return The new opposite holdings modifier object. */ public HoldingsModifier counter() { + final HoldingsModifier mod = new HoldingsModifier(region, currency, modifier.negate(), operation, holdingsID); //System.out.println("Percent Counter: " + percent); mod.setPercent(percent); @@ -210,10 +223,13 @@ public HoldingsModifier counter() { /** * Returns a new {@link HoldingsModifier} object that is the opposite in terms of amount from this * one. + * * @param type The {@link Identifier} for the holdings type to perform this transaction on. + * * @return The new opposite holdings modifier object. */ public HoldingsModifier counter(final Identifier type) { + final HoldingsModifier mod = new HoldingsModifier(region, currency, modifier.negate(), operation, type); mod.setPercent(percent); return mod; @@ -221,51 +237,63 @@ public HoldingsModifier counter(final Identifier type) { /** * Used to determine if this modifier is used to remove froms. + * * @return True if this will remove funds, otherwise false. */ public boolean isRemoval() { + return operation.equals(HoldingsOperation.SUBTRACT) - || operation.equals(HoldingsOperation.DIVIDE) - || modifier.compareTo(BigDecimal.ZERO) < 0; + || operation.equals(HoldingsOperation.DIVIDE) + || modifier.compareTo(BigDecimal.ZERO) < 0; } public BigDecimal modify(final BigDecimal value) { + return operation.perform(value, modifier); } public void modifier(final BigDecimal value) { + this.modifier = modifier.add(value); } public UUID getCurrency() { + return currency; } public String getRegion() { + return region; } public BigDecimal getModifier() { + return modifier; } public HoldingsOperation getOperation() { + return operation; } public Identifier getType() { + return holdingsID; } public HoldingsEntry asEntry() { + return new HoldingsEntry(region, currency, modifier, EconomyManager.NORMAL); } public boolean isPercent() { + return percent; } public void setPercent(boolean percent) { + this.percent = percent; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/account/holdings/modify/HoldingsOperation.java b/Core/src/net/tnemc/core/account/holdings/modify/HoldingsOperation.java index fc076c08..d745aae2 100644 --- a/Core/src/net/tnemc/core/account/holdings/modify/HoldingsOperation.java +++ b/Core/src/net/tnemc/core/account/holdings/modify/HoldingsOperation.java @@ -36,18 +36,21 @@ public enum HoldingsOperation { ADD { @Override public BigDecimal perform(final BigDecimal value, final BigDecimal modifier) { + return super.perform(value, modifier); } }, SUBTRACT { @Override public BigDecimal perform(final BigDecimal value, final BigDecimal modifier) { + return value.subtract(modifier); } }, MULTIPLY { @Override public BigDecimal perform(final BigDecimal value, final BigDecimal modifier) { + return value.multiply(modifier); } }, @@ -65,24 +68,28 @@ public BigDecimal perform(final BigDecimal value, final BigDecimal modifier) { PERCENT_SUBTRACT { @Override public BigDecimal perform(final BigDecimal value, final BigDecimal modifier) { + return value.subtract(value.multiply(modifier.divide(new BigDecimal(100), new MathContext(2, RoundingMode.DOWN)))); } }, SET { @Override public BigDecimal perform(final BigDecimal value, final BigDecimal modifier) { + return modifier; } }, DIVIDE { @Override public BigDecimal perform(final BigDecimal value, final BigDecimal modifier) { + return value.divide(modifier, RoundingMode.valueOf(9)); } }; public BigDecimal perform(final BigDecimal value, final BigDecimal modifier) { + return value.add(modifier); } } diff --git a/Core/src/net/tnemc/core/account/shared/Member.java b/Core/src/net/tnemc/core/account/shared/Member.java index f27feb22..b73a1d39 100644 --- a/Core/src/net/tnemc/core/account/shared/Member.java +++ b/Core/src/net/tnemc/core/account/shared/Member.java @@ -27,86 +27,105 @@ /** * Represents a player that has access to an account. * + * @author creatorfromhell * @see Account * @since 0.1.1.17 - * @author creatorfromhell */ public class Member { private final Map permissions = new HashMap<>(); /** - * The {@link UUID identifier} associated with the player that is - * represented by this member object. + * The {@link UUID identifier} associated with the player that is represented by this member + * object. */ private final UUID id; /** * Construct a new member using an {@link UUID identifier}. + * * @param id The {@link UUID identifier} of this member. */ public Member(final UUID id) { + this.id = id; } public UUID getId() { + return id; } /** * Sets the permission specified to the specified value for this member. + * * @param permission The permission to set. - * @param value The value to set for the permission. + * @param value The value to set for the permission. */ public void addPermission(Permission permission, boolean value) { + permissions.put(permission.identifier(), value); } /** * Sets the permission specified to the specified value for this member. + * * @param permission The permission to set. - * @param value The value to set for the permission. + * @param value The value to set for the permission. */ public void addPermission(String permission, boolean value) { + permissions.put(permission, value); } /** * Removes the permission specified from this member. + * * @param permission The permission to set. */ public void removePermission(Permission permission) { + permissions.remove(permission.identifier()); } /** * Removes the permission specified from this member. + * * @param permission The permission to set. */ public void removePermission(String permission) { + permissions.remove(permission); } /** * Checks if this member has the specified permission. + * * @param permission The permission to we are checking for. + * * @return True if this member has the specified permission, otherwise false. */ public boolean hasPermission(Permission permission) { + return permissions.getOrDefault(permission.identifier(), permission.defaultValue()); } /** * Checks if this member has the specified permission. - * @param permission The permission to we are checking for. - * @param defaultValue The default value to return if this account doesn't contain the permission. + * + * @param permission The permission to we are checking for. + * @param defaultValue The default value to return if this account doesn't contain the + * permission. + * * @return True if this member has the specified permission, otherwise false. */ public boolean hasPermission(String permission, final boolean defaultValue) { + return permissions.getOrDefault(permission, defaultValue); } public Map getPermissions() { + return permissions; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/account/shared/MemberPermissions.java b/Core/src/net/tnemc/core/account/shared/MemberPermissions.java index b2596373..37181dd5 100644 --- a/Core/src/net/tnemc/core/account/shared/MemberPermissions.java +++ b/Core/src/net/tnemc/core/account/shared/MemberPermissions.java @@ -21,10 +21,10 @@ /** * Represents the {@link Permission permissions} for {@link Member members}. * + * @author creatorfromhell * @see Member * @see Permission * @since 0.1.1.17 - * @author creatorfromhell */ public enum MemberPermissions implements Permission { @@ -32,7 +32,6 @@ public enum MemberPermissions implements Permission { * Can the member check the balance? */ BALANCE { - /** * The identifier of the permission. * @@ -40,6 +39,7 @@ public enum MemberPermissions implements Permission { */ @Override public String identifier() { + return "BALANCE"; } @@ -50,6 +50,7 @@ public String identifier() { */ @Override public boolean defaultValue() { + return true; } }, @@ -58,7 +59,6 @@ public boolean defaultValue() { * Can the member withdraw from the account? */ WITHDRAW { - /** * The identifier of the permission. * @@ -66,6 +66,7 @@ public boolean defaultValue() { */ @Override public String identifier() { + return "WITHDRAW"; } @@ -76,6 +77,7 @@ public String identifier() { */ @Override public boolean defaultValue() { + return false; } }, @@ -84,7 +86,6 @@ public boolean defaultValue() { * Can the member deposit to the account? */ DEPOSIT { - /** * The identifier of the permission. * @@ -92,6 +93,7 @@ public boolean defaultValue() { */ @Override public String identifier() { + return "DEPOSIT"; } @@ -102,6 +104,7 @@ public String identifier() { */ @Override public boolean defaultValue() { + return false; } }, @@ -110,7 +113,6 @@ public boolean defaultValue() { * Can the member add other members? */ ADD_MEMBER { - /** * The identifier of the permission. * @@ -118,6 +120,7 @@ public boolean defaultValue() { */ @Override public String identifier() { + return "ADD_MEMBER"; } @@ -128,6 +131,7 @@ public String identifier() { */ @Override public boolean defaultValue() { + return false; } }, @@ -136,7 +140,6 @@ public boolean defaultValue() { * Can the member modify the permissions of other members? */ MODIFY_MEMBER { - /** * The identifier of the permission. * @@ -144,6 +147,7 @@ public boolean defaultValue() { */ @Override public String identifier() { + return "MODIFY_MEMBER"; } @@ -154,6 +158,7 @@ public String identifier() { */ @Override public boolean defaultValue() { + return false; } }, @@ -162,7 +167,6 @@ public boolean defaultValue() { * Can the member remove other members? */ REMOVE_MEMBER { - /** * The identifier of the permission. * @@ -170,6 +174,7 @@ public boolean defaultValue() { */ @Override public String identifier() { + return "REMOVE_MEMBER"; } @@ -180,6 +185,7 @@ public String identifier() { */ @Override public boolean defaultValue() { + return false; } }, @@ -188,7 +194,6 @@ public boolean defaultValue() { * Can the member delete the account? */ DELETE_ACCOUNT { - /** * The identifier of the permission. * @@ -196,6 +201,7 @@ public boolean defaultValue() { */ @Override public String identifier() { + return "DELETE_ACCOUNT"; } @@ -206,6 +212,7 @@ public String identifier() { */ @Override public boolean defaultValue() { + return false; } }, @@ -214,7 +221,6 @@ public boolean defaultValue() { * Can the member transfer ownership of the account? */ TRANSFER_OWNERSHIP { - /** * The identifier of the permission. * @@ -222,6 +228,7 @@ public boolean defaultValue() { */ @Override public String identifier() { + return "TRANSFER_OWNERSHIP"; } @@ -232,6 +239,7 @@ public String identifier() { */ @Override public boolean defaultValue() { + return false; } } diff --git a/Core/src/net/tnemc/core/account/shared/Permission.java b/Core/src/net/tnemc/core/account/shared/Permission.java index c225771f..24495413 100644 --- a/Core/src/net/tnemc/core/account/shared/Permission.java +++ b/Core/src/net/tnemc/core/account/shared/Permission.java @@ -21,24 +21,25 @@ import net.tnemc.core.account.Account; /** - * Represents a permission for an {@link Member member} of an - * {@link Account account}. + * Represents a permission for an {@link Member member} of an {@link Account account}. * + * @author creatorfromhell * @see Member * @see Account * @since 0.1.1.17 - * @author creatorfromhell */ public interface Permission { /** * The identifier of the permission. + * * @return The identifier of the permission. */ String identifier(); /** * The default value of the permission. + * * @return The default value of the permission. */ boolean defaultValue(); diff --git a/Core/src/net/tnemc/core/account/status/AccountLockedStatus.java b/Core/src/net/tnemc/core/account/status/AccountLockedStatus.java index 01388e83..ff5c1fe4 100644 --- a/Core/src/net/tnemc/core/account/status/AccountLockedStatus.java +++ b/Core/src/net/tnemc/core/account/status/AccountLockedStatus.java @@ -29,12 +29,14 @@ * @since 0.1.2.0 */ public class AccountLockedStatus implements AccountStatus { + /** * @return The identifier of this account status. */ @Override @MapKey public @NotNull String identifier() { + return "locked"; } @@ -45,6 +47,7 @@ public class AccountLockedStatus implements AccountStatus { */ @Override public boolean unlockable() { + return true; } @@ -55,6 +58,7 @@ public boolean unlockable() { */ @Override public boolean use() { + return false; } @@ -65,6 +69,7 @@ public boolean use() { */ @Override public boolean receive() { + return true; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/account/status/AccountNormalStatus.java b/Core/src/net/tnemc/core/account/status/AccountNormalStatus.java index a53b71dd..1dc6650c 100644 --- a/Core/src/net/tnemc/core/account/status/AccountNormalStatus.java +++ b/Core/src/net/tnemc/core/account/status/AccountNormalStatus.java @@ -29,12 +29,14 @@ * @since 0.1.2.0 */ public class AccountNormalStatus implements AccountStatus { + /** * @return The identifier of this account status. */ @Override @MapKey public @NotNull String identifier() { + return "normal"; } @@ -45,6 +47,7 @@ public class AccountNormalStatus implements AccountStatus { */ @Override public boolean unlockable() { + return false; } @@ -55,6 +58,7 @@ public boolean unlockable() { */ @Override public boolean use() { + return true; } @@ -65,6 +69,7 @@ public boolean use() { */ @Override public boolean receive() { + return true; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/account/status/AccountRestrictedStatus.java b/Core/src/net/tnemc/core/account/status/AccountRestrictedStatus.java index 8714f637..ac81940e 100644 --- a/Core/src/net/tnemc/core/account/status/AccountRestrictedStatus.java +++ b/Core/src/net/tnemc/core/account/status/AccountRestrictedStatus.java @@ -29,12 +29,14 @@ * @since 0.1.2.0 */ public class AccountRestrictedStatus implements AccountStatus { + /** * @return The identifier of this account status. */ @Override @MapKey public @NotNull String identifier() { + return "restricted"; } @@ -45,6 +47,7 @@ public class AccountRestrictedStatus implements AccountStatus { */ @Override public boolean unlockable() { + return false; } @@ -55,6 +58,7 @@ public boolean unlockable() { */ @Override public boolean use() { + return false; } @@ -65,6 +69,7 @@ public boolean use() { */ @Override public boolean receive() { + return false; } } diff --git a/Core/src/net/tnemc/core/actions/ActionSource.java b/Core/src/net/tnemc/core/actions/ActionSource.java index c65cb111..5340ca34 100644 --- a/Core/src/net/tnemc/core/actions/ActionSource.java +++ b/Core/src/net/tnemc/core/actions/ActionSource.java @@ -25,8 +25,8 @@ import java.util.UUID; /** - * Represents the source of an action that was performed. This could be anything from balance changes - * in the economy API to other API-related actions. + * Represents the source of an action that was performed. This could be anything from balance + * changes in the economy API to other API-related actions. * * @author creatorfromhell * @since 0.1.2.0 @@ -34,14 +34,13 @@ public interface ActionSource { /** - * * Used to get the name of the source of the action. * * Please note: There is no guarantee of uniqueness. * - * @return The name of the source for a specific action. This could be user-friendly - * or not. This should be the name of the source that has caused this action to occur. For - * instance, a plugin name. + * @return The name of the source for a specific action. This could be user-friendly or not. This + * should be the name of the source that has caused this action to occur. For instance, a plugin + * name. * * @since 0.1.2.0 */ @@ -49,11 +48,13 @@ public interface ActionSource { /** * Used to get the type of action source. + * * @return The name of the type of action source. */ String type(); default String asString() { + return type() + " " + name(); } @@ -62,7 +63,7 @@ static ActionSource create(String name, String type) { if(type.toLowerCase(Locale.ROOT).equals("player")) { try { return new PlayerSource(UUID.fromString(name)); - } catch(Exception ignore) {} + } catch(Exception ignore) { } } else { return new PluginSource(name); } diff --git a/Core/src/net/tnemc/core/actions/EconomyResponse.java b/Core/src/net/tnemc/core/actions/EconomyResponse.java index cedc8437..62f16e03 100644 --- a/Core/src/net/tnemc/core/actions/EconomyResponse.java +++ b/Core/src/net/tnemc/core/actions/EconomyResponse.java @@ -27,16 +27,19 @@ public interface EconomyResponse { /** - * @since 0.1.2.0 * @return True if the associated action was performed correctly. + * + * @since 0.1.2.0 */ boolean success(); /** - * @since 0.1.2.0 * @return The string to return to the performer of the action. + * + * @since 0.1.2.0 */ default String response() { + return "Default response string"; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/actions/response/AccountResponse.java b/Core/src/net/tnemc/core/actions/response/AccountResponse.java index 7c8d25d5..e8db1ea3 100644 --- a/Core/src/net/tnemc/core/actions/response/AccountResponse.java +++ b/Core/src/net/tnemc/core/actions/response/AccountResponse.java @@ -24,8 +24,8 @@ /** * Contains some default responses that relate to {@link Account account} operations. * - * @see Account * @author creatorfromhell + * @see Account * @since 0.1.2.0 */ public enum AccountResponse implements EconomyResponse { @@ -38,11 +38,13 @@ public enum AccountResponse implements EconomyResponse { CREATED { @Override public boolean success() { + return true; } @Override public String response() { + return "Messages.Admin.Created"; } }, @@ -55,29 +57,33 @@ public String response() { CREATION_FAILED { @Override public boolean success() { + return false; } @Override public String response() { + return "Messages.Admin.CreationFailed"; } }, /** - * The action failed, and during it an account was not created. This is because a plugin has blocked - * the account creation. + * The action failed, and during it an account was not created. This is because a plugin has + * blocked the account creation. * * @since 0.1.2.0 */ CREATION_FAILED_PLUGIN { @Override public boolean success() { + return false; } @Override public String response() { + return "Messages.Admin.CreationFailed"; } }, @@ -90,11 +96,13 @@ public String response() { ALREADY_EXISTS { @Override public boolean success() { + return false; } @Override public String response() { + return "Messages.Admin.Exists"; } }, @@ -107,11 +115,13 @@ public String response() { DELETED { @Override public boolean success() { + return true; } @Override public String response() { + return "Messages.Admin.Deleted"; } }, @@ -124,11 +134,13 @@ public String response() { DOESNT_EXIST { @Override public boolean success() { + return false; } @Override public String response() { + return "Messages.Account.NoSuch"; } }, diff --git a/Core/src/net/tnemc/core/actions/response/CustomResponse.java b/Core/src/net/tnemc/core/actions/response/CustomResponse.java index 85f42913..54563eee 100644 --- a/Core/src/net/tnemc/core/actions/response/CustomResponse.java +++ b/Core/src/net/tnemc/core/actions/response/CustomResponse.java @@ -32,27 +32,30 @@ public class CustomResponse implements EconomyResponse { private final String response; /** - * This is a helper class for to return custom responses during API calls - * that return an {@link EconomyResponse} object. + * This is a helper class for to return custom responses during API calls that return an + * {@link EconomyResponse} object. * * @param success Whether the action was performed successfully. - * @param response The message to send describing the response. Example: "Action failed because account - * doesn't exist" + * @param response The message to send describing the response. Example: "Action failed because + * account doesn't exist" * * @since 0.1.2.0 */ public CustomResponse(final boolean success, final String response) { + this.success = success; this.response = response; } @Override public boolean success() { + return success; } @Override public String response() { + return response; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/actions/response/GeneralResponse.java b/Core/src/net/tnemc/core/actions/response/GeneralResponse.java index e39eddf3..6427f5ee 100644 --- a/Core/src/net/tnemc/core/actions/response/GeneralResponse.java +++ b/Core/src/net/tnemc/core/actions/response/GeneralResponse.java @@ -22,8 +22,8 @@ /** * Represents general responses that may be utilized for multiple reasons. - * - * @author creatorfromhell + * + * @author creatorfromhell * @since 0.1.2.0 */ public enum GeneralResponse implements EconomyResponse { @@ -36,11 +36,13 @@ public enum GeneralResponse implements EconomyResponse { SUCCESS { @Override public boolean success() { + return true; } @Override public String response() { + return "The action was successful."; } }, @@ -53,11 +55,13 @@ public String response() { FAILED { @Override public boolean success() { + return false; } @Override public String response() { + return "The action was unsuccessful."; } }, @@ -70,11 +74,13 @@ public String response() { FAILED_PLUGIN { @Override public boolean success() { + return false; } @Override public String response() { + return "The action was unsuccessful, because it was blocked by a plugin."; } }, @@ -87,11 +93,13 @@ public String response() { UNSUPPORTED { @Override public boolean success() { + return false; } @Override public String response() { + return "This action is not supported by this version of TNE."; } } diff --git a/Core/src/net/tnemc/core/actions/response/HoldingsResponse.java b/Core/src/net/tnemc/core/actions/response/HoldingsResponse.java index 33d16c28..9cd5042b 100644 --- a/Core/src/net/tnemc/core/actions/response/HoldingsResponse.java +++ b/Core/src/net/tnemc/core/actions/response/HoldingsResponse.java @@ -37,11 +37,13 @@ public enum HoldingsResponse implements EconomyResponse { MAX_HOLDINGS { @Override public boolean success() { + return false; } @Override public String response() { + return "Messages.Money.ExceedsOtherPlayerMaximum"; } }, @@ -54,11 +56,13 @@ public String response() { MIN_HOLDINGS { @Override public boolean success() { + return false; } @Override public String response() { + return "Messages.Money.ExceedsOtherPlayerMinimum"; } }, @@ -71,11 +75,13 @@ public String response() { MIN_DENOM_INCAPABLE { @Override public boolean success() { + return false; } @Override public String response() { + return "Messages.Money.MinimumDenomination"; } }, @@ -88,11 +94,13 @@ public String response() { INSUFFICIENT { @Override public boolean success() { + return false; } @Override public String response() { + return "Messages.Money.Insufficient"; } }, @@ -105,11 +113,13 @@ public String response() { INSUFFICIENT_OTHER { @Override public boolean success() { + return false; } @Override public String response() { + return "Messages.Money.InsufficientOther"; } }, @@ -122,11 +132,13 @@ public String response() { RESTRICTED { @Override public boolean success() { + return false; } @Override public String response() { + return "Messages.Money.Restricted"; } }, @@ -139,11 +151,13 @@ public String response() { RECEIVE_LOCK { @Override public boolean success() { + return false; } @Override public String response() { + return "Messages.Account.ReceiveLock"; } }, @@ -156,11 +170,13 @@ public String response() { USE_LOCK { @Override public boolean success() { + return false; } @Override public String response() { + return "Messages.Account.UseLock"; } }, @@ -173,11 +189,13 @@ public String response() { */ @Override public boolean success() { + return false; } @Override public String response() { + return "Messages.General.Disabled"; } } diff --git a/Core/src/net/tnemc/core/actions/source/PlayerSource.java b/Core/src/net/tnemc/core/actions/source/PlayerSource.java index 573b4b5a..2c501a6a 100644 --- a/Core/src/net/tnemc/core/actions/source/PlayerSource.java +++ b/Core/src/net/tnemc/core/actions/source/PlayerSource.java @@ -35,13 +35,15 @@ public record PlayerSource(UUID id) implements ActionSource { *

* Please note: There is no guarantee of uniqueness. * - * @return The name of the source for a specific action. This could be user-friendly - * or not. This should be the name of the source that has caused this action to occur. For - * instance, a plugin name. + * @return The name of the source for a specific action. This could be user-friendly or not. This + * should be the name of the source that has caused this action to occur. For instance, a plugin + * name. + * * @since 0.1.2.0 */ @Override public String name() { + return id.toString(); } @@ -52,6 +54,7 @@ public String name() { */ @Override public String type() { + return "player"; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/actions/source/PluginSource.java b/Core/src/net/tnemc/core/actions/source/PluginSource.java index bb54208d..ec616a40 100644 --- a/Core/src/net/tnemc/core/actions/source/PluginSource.java +++ b/Core/src/net/tnemc/core/actions/source/PluginSource.java @@ -41,15 +41,16 @@ public class PluginSource implements ActionSource { * @since 0.1.2.0 */ public PluginSource(String plugin) { + this.plugin = plugin; } /** * Used to get the name of the source of the action. * - * @return The name of the source for a specific action. This could be user-friendly - * or not. This should be the name of the implementation that has caused this action to occur. For - * instance, a plugin name. + * @return The name of the source for a specific action. This could be user-friendly or not. This + * should be the name of the implementation that has caused this action to occur. For instance, a + * plugin name. *

* Please note: There is no guarantee of uniqueness. * @@ -57,6 +58,7 @@ public PluginSource(String plugin) { */ @Override public String name() { + return plugin; } @@ -67,6 +69,7 @@ public String name() { */ @Override public String type() { + return "plugin"; } } diff --git a/Core/src/net/tnemc/core/api/TNEAPI.java b/Core/src/net/tnemc/core/api/TNEAPI.java index e846653c..f768db28 100644 --- a/Core/src/net/tnemc/core/api/TNEAPI.java +++ b/Core/src/net/tnemc/core/api/TNEAPI.java @@ -65,6 +65,7 @@ public class TNEAPI { * @return The callback manager that is being used. */ public CallbackManager callbacks() { + return PluginCore.callbacks(); } @@ -72,11 +73,13 @@ public CallbackManager callbacks() { * Used to add a new {@link HoldingsHandler} to the {@link net.tnemc.core.EconomyManager}. These * handlers are able to add additional holdings sources for accounts. * - * @see Handlers Wiki - * * @param handler The handler to add. + * + * @see Handlers + * Wiki */ public void addHandler(HoldingsHandler handler) { + EconomyManager.instance().addHandler(handler); } @@ -98,6 +101,7 @@ public void addAccountType(Class type, Function - * This method could return any of the following account types: - * - {@link NonPlayerAccount} - * - {@link SharedAccount} + * This method could return any of the following account types: - {@link NonPlayerAccount} - + * {@link SharedAccount} *

* This method is safe to search for non-player accounts. * * @param identifier The string identifier for the account that is being looked for. - * @param name The string name for the account that is being looked for. + * @param name The string name for the account that is being looked for. * * @return The correlating {@link Account account} object if found, otherwise the one created. + * * @since 0.1.2.0 */ public AccountAPIResponse getOrCreateAccount(@NotNull String identifier, @NotNull String name) { + AccountAPIResponse response = TNECore.eco().account().createAccount(identifier, name); return response; @@ -158,64 +167,70 @@ public AccountAPIResponse getOrCreateAccount(@NotNull String identifier, @NotNul * This method is not safe to search for non-player accounts. * * @param identifier The {@link UUID} identifier for the account that is being looked for. - * @param name The string name for the account that is being looked for. + * @param name The string name for the account that is being looked for. * * @return The correlating {@link AccountAPIResponse response}. + * * @since 0.1.2.0 */ public AccountAPIResponse getOrCreatePlayerAccount(@NotNull UUID identifier, @NotNull String name) { + return getOrCreateAccount(identifier.toString(), name); } /** - * Attempts to create an account with the given identifier. This method returns true if the account - * was created, otherwise false. + * Attempts to create an account with the given identifier. This method returns true if the + * account was created, otherwise false. *

* This method is intended for non-player accounts. * * @param identifier The String identifier for the account that is being created. * * @return If the account is created an Optional containing the {@link SharedAccount account}, or - * an empty Optional. + * an empty Optional. + * * @since 0.1.2.0 */ public Optional createAccount(@NotNull String identifier) { + return TNECore.eco().account().createNonPlayerAccount(identifier); } /** - * Attempts to create an account with the given identifier. This method returns true if the account - * was created, otherwise false. + * Attempts to create an account with the given identifier. This method returns true if the + * account was created, otherwise false. *

* This method is not intended for non-player accounts. * * @param identifier The {@link UUID} identifier for the account that is being created. - * @param name The String representation of the name for the account being created, usually the username - * of the player. + * @param name The String representation of the name for the account being created, usually + * the username of the player. * * @return The correlating {@link AccountAPIResponse response}. + * * @since 0.1.2.0 */ public AccountAPIResponse createPlayerAccount(@NotNull UUID identifier, @NotNull String name) { + return TNECore.eco().account().createAccount(identifier.toString(), name); } /** * Looks for an account based on the provided identifier. *

- * This method could return any of the following account types: - * - {@link PlayerAccount} - * - {@link NonPlayerAccount} - * - {@link SharedAccount} + * This method could return any of the following account types: - {@link PlayerAccount} - + * {@link NonPlayerAccount} - {@link SharedAccount} *

* This method is safe to search for non-player accounts. * * @param identifier The string identifier for the account that is being looked for. * * @return An optional containing the {@link Account} if found, otherwise an empty optional. + * * @since 0.1.2.0 */ public Optional getAccount(@NotNull String identifier) { + return TNECore.eco().account().findAccount(identifier); } @@ -226,11 +241,12 @@ public Optional getAccount(@NotNull String identifier) { * * @param identifier The {@link UUID identifier} for the account that is being looked for. * - * @return An optional containing the {@link PlayerAccount} - * if found, otherwise an empty optional. + * @return An optional containing the {@link PlayerAccount} if found, otherwise an empty optional. + * * @since 0.1.2.0 */ public Optional getPlayerAccount(@NotNull UUID identifier) { + return TNECore.eco().account().findPlayerAccount(identifier); } @@ -242,10 +258,13 @@ public Optional getPlayerAccount(@NotNull UUID identifier) { * @param identifier The identifier associated with the account that you wish to delete. * @param source The {@link ActionSource source} response for this deletion call. * - * @return The {@link EconomyResponse response} that should be returned based on the deletion action. + * @return The {@link EconomyResponse response} that should be returned based on the deletion + * action. + * * @since 0.1.2.0 */ public EconomyResponse deleteAccount(@NotNull String identifier, @NotNull ActionSource source) { + return TNECore.eco().account().deleteAccount(identifier); } @@ -257,10 +276,13 @@ public EconomyResponse deleteAccount(@NotNull String identifier, @NotNull Action * @param identifier The identifier associated with the account that you wish to delete. * @param source The {@link ActionSource source} response for this deletion call. * - * @return The {@link EconomyResponse response} that should be returned based on the deletion action. + * @return The {@link EconomyResponse response} that should be returned based on the deletion + * action. + * * @since 0.1.2.0 **/ public EconomyResponse deleteAccount(@NotNull UUID identifier, @NotNull ActionSource source) { + return TNECore.eco().account().deleteAccount(identifier); } @@ -270,6 +292,7 @@ public EconomyResponse deleteAccount(@NotNull UUID identifier, @NotNull ActionSo * @param type The {@link CurrencyType} to be added. */ public void addCurrencyType(CurrencyType type) { + TNECore.eco().currency().addType(type); } @@ -279,6 +302,7 @@ public void addCurrencyType(CurrencyType type) { * @param currency The {@link Currency} to be added. */ public void addCurrency(Currency currency) { + TNECore.eco().currency().addCurrency(currency); } @@ -288,6 +312,7 @@ public void addCurrency(Currency currency) { * @param rule The {@link FormatRule} to be added for balance formatting. */ public void addBalanceFormatRule(FormatRule rule) { + CurrencyFormatter.addRule(rule); } @@ -297,9 +322,11 @@ public void addBalanceFormatRule(FormatRule rule) { * * @return The currency that is the default for the server if multi-world support is not available * otherwise the default for the default world. + * * @since 0.1.2.0 */ public @NotNull Currency getDefaultCurrency() { + return TNECore.api().getDefaultCurrency(); } @@ -312,9 +339,11 @@ public void addBalanceFormatRule(FormatRule rule) { * * @return The default currency for the specified world if this implementation has multi-world * support, otherwise the default currency for the server. + * * @since 0.1.2.0 */ public @NotNull Currency getDefaultCurrency(@NotNull String region) { + return TNECore.eco().currency().getDefaultCurrency(region); } @@ -322,24 +351,29 @@ public void addBalanceFormatRule(FormatRule rule) { * Used to get a set of every {@link Currency} object for the server. * * @return A set of every {@link Currency} object that is available for the server. + * * @since 0.1.2.0 */ public Collection getCurrencies() { + return TNECore.eco().currency().currencies(); } /** * Used to get a set of every {@link Currency} object that is available in the specified world if - * this implementation has multi-world support, otherwise all {@link Currency} objects for the server. + * this implementation has multi-world support, otherwise all {@link Currency} objects for the + * server. * - * @param region The region to get the currencies for. This could be a world, biomes, or a - * third party based region. + * @param region The region to get the currencies for. This could be a world, biomes, or a third + * party based region. + * + * @return A set of every {@link Currency} object that is available in the specified world if this + * implementation has multi-world support, otherwise all {@link Currency} objects for the server. * - * @return A set of every {@link Currency} object that is available in the specified world if - * this implementation has multi-world support, otherwise all {@link Currency} objects for the server. * @since 0.1.2.0 */ public Collection getCurrencies(@NotNull String region) { + return TNECore.api().getCurrencies(region); } @@ -353,6 +387,7 @@ public Collection getCurrencies(@NotNull String region) { * @return The holdings in {@link BigDecimal} format. */ public BigDecimal getHoldings(String identifier, String world, String currency) { + final Optional account = TNECore.eco().account().findAccount(identifier); final Optional currency1 = TNECore.eco().currency().findCurrency(currency); @@ -373,6 +408,7 @@ public BigDecimal getHoldings(String identifier, String world, String currency) * @return True if the specified identifier has the holdings, otherwise false. */ public boolean hasHoldings(String identifier, String world, String currency, BigDecimal amount) { + return getHoldings(identifier, world, currency).compareTo(amount) >= 0; } @@ -388,14 +424,15 @@ public boolean hasHoldings(String identifier, String world, String currency, Big * @return The associated {@link TransactionResult result} from the transaction. */ public TransactionResult removeHoldings(String identifier, String world, String currency, BigDecimal amount, String pluginName) { + final Optional account = TNECore.eco().account().findAccount(identifier); final Optional currencyObject = TNECore.eco().currency().findCurrency(currency); if(account.isPresent() && currencyObject.isPresent()) { final HoldingsModifier modifier = new HoldingsModifier(world, - currencyObject.get().getUid(), - amount); + currencyObject.get().getUid(), + amount); final Transaction transaction = new Transaction("take") .to(account.get(), modifier) @@ -423,14 +460,15 @@ public TransactionResult removeHoldings(String identifier, String world, String * @return The associated {@link TransactionResult result} from the transaction. */ public TransactionResult addHoldings(String identifier, String world, String currency, BigDecimal amount, String pluginName) { + final Optional account = TNECore.eco().account().findAccount(identifier); final Optional currencyOptional = TNECore.eco().currency().findCurrency(currency); if(account.isPresent() && currencyOptional.isPresent()) { final HoldingsModifier modifier = new HoldingsModifier(world, - currencyOptional.get().getUid(), - amount); + currencyOptional.get().getUid(), + amount); final Transaction transaction = new Transaction("give") .to(account.get(), modifier) @@ -456,6 +494,7 @@ public TransactionResult addHoldings(String identifier, String world, String cur * @return True if the transactions was successful, otherwise false. */ public boolean setHoldings(String identifier, String world, String currency, BigDecimal amount) { + final Optional account = TNECore.eco().account().findAccount(identifier); final Optional currencyOptional = TNECore.eco().currency().findCurrency(currency); diff --git a/Core/src/net/tnemc/core/api/callback/TNECallbackProvider.java b/Core/src/net/tnemc/core/api/callback/TNECallbackProvider.java index 7b347cda..792141b7 100644 --- a/Core/src/net/tnemc/core/api/callback/TNECallbackProvider.java +++ b/Core/src/net/tnemc/core/api/callback/TNECallbackProvider.java @@ -28,6 +28,7 @@ * @since 0.1.2.0 */ public class TNECallbackProvider implements CallbackProvider { + @Override public void init(CallbackManager callbackManager) { diff --git a/Core/src/net/tnemc/core/api/callback/TNECallbacks.java b/Core/src/net/tnemc/core/api/callback/TNECallbacks.java index 1bf7d4e0..f60ead8d 100644 --- a/Core/src/net/tnemc/core/api/callback/TNECallbacks.java +++ b/Core/src/net/tnemc/core/api/callback/TNECallbacks.java @@ -41,10 +41,12 @@ public enum TNECallbacks { final String identifier; TNECallbacks(String identifier) { + this.identifier = identifier; } public String id() { + return identifier; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/api/callback/account/AccountCallback.java b/Core/src/net/tnemc/core/api/callback/account/AccountCallback.java index ab948869..e43a292d 100644 --- a/Core/src/net/tnemc/core/api/callback/account/AccountCallback.java +++ b/Core/src/net/tnemc/core/api/callback/account/AccountCallback.java @@ -32,6 +32,7 @@ public abstract class AccountCallback implements Callback { protected final Account account; public AccountCallback(Account account) { + this.account = account; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/api/callback/account/AccountCreateCallback.java b/Core/src/net/tnemc/core/api/callback/account/AccountCreateCallback.java index fad15bb9..ade250b5 100644 --- a/Core/src/net/tnemc/core/api/callback/account/AccountCreateCallback.java +++ b/Core/src/net/tnemc/core/api/callback/account/AccountCreateCallback.java @@ -28,7 +28,9 @@ * @since 0.1.2.0 */ public class AccountCreateCallback extends AccountCallback { + public AccountCreateCallback(Account account) { + super(account); } @@ -39,6 +41,7 @@ public AccountCreateCallback(Account account) { */ @Override public String name() { + return TNECallbacks.ACCOUNT_CREATE.id(); } } diff --git a/Core/src/net/tnemc/core/api/callback/account/AccountDeleteCallback.java b/Core/src/net/tnemc/core/api/callback/account/AccountDeleteCallback.java index 56b0fca1..9d47713e 100644 --- a/Core/src/net/tnemc/core/api/callback/account/AccountDeleteCallback.java +++ b/Core/src/net/tnemc/core/api/callback/account/AccountDeleteCallback.java @@ -36,6 +36,7 @@ public record AccountDeleteCallback(String identifier) implements Callback { */ @Override public String name() { + return TNECallbacks.ACCOUNT_DELETE.id(); } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/api/callback/account/AccountLoadCallback.java b/Core/src/net/tnemc/core/api/callback/account/AccountLoadCallback.java index 12230688..8d66f5f2 100644 --- a/Core/src/net/tnemc/core/api/callback/account/AccountLoadCallback.java +++ b/Core/src/net/tnemc/core/api/callback/account/AccountLoadCallback.java @@ -28,7 +28,9 @@ * @since 0.1.2.0 */ public class AccountLoadCallback extends AccountCallback { + public AccountLoadCallback(Account account) { + super(account); } @@ -39,6 +41,7 @@ public AccountLoadCallback(Account account) { */ @Override public String name() { + return TNECallbacks.ACCOUNT_LOAD.id(); } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/api/callback/account/AccountSaveCallback.java b/Core/src/net/tnemc/core/api/callback/account/AccountSaveCallback.java index 9f87fa09..8c142da2 100644 --- a/Core/src/net/tnemc/core/api/callback/account/AccountSaveCallback.java +++ b/Core/src/net/tnemc/core/api/callback/account/AccountSaveCallback.java @@ -30,6 +30,7 @@ public class AccountSaveCallback extends AccountCallback { public AccountSaveCallback(Account account) { + super(account); } @@ -40,6 +41,7 @@ public AccountSaveCallback(Account account) { */ @Override public String name() { + return TNECallbacks.ACCOUNT_SAVE.id(); } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/api/callback/account/AccountTypesCallback.java b/Core/src/net/tnemc/core/api/callback/account/AccountTypesCallback.java index e7f7ae18..59f38d06 100644 --- a/Core/src/net/tnemc/core/api/callback/account/AccountTypesCallback.java +++ b/Core/src/net/tnemc/core/api/callback/account/AccountTypesCallback.java @@ -29,7 +29,7 @@ */ public class AccountTypesCallback implements Callback { - + /** * The name of this callback. * @@ -37,6 +37,7 @@ public class AccountTypesCallback implements Callback { */ @Override public String name() { + return TNECallbacks.ACCOUNT_TYPES.toString(); } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/api/callback/currency/CurrencyDropCallback.java b/Core/src/net/tnemc/core/api/callback/currency/CurrencyDropCallback.java index 4889f15e..3fa611f2 100644 --- a/Core/src/net/tnemc/core/api/callback/currency/CurrencyDropCallback.java +++ b/Core/src/net/tnemc/core/api/callback/currency/CurrencyDropCallback.java @@ -39,6 +39,7 @@ public class CurrencyDropCallback implements Callback { private final Collection> drops; public CurrencyDropCallback(UUID player, Currency currency, Collection> drops) { + this.player = player; this.currency = currency; this.drops = drops; @@ -51,22 +52,27 @@ public CurrencyDropCallback(UUID player, Currency currency, Collection> getDrops() { + return drops; } public Currency getCurrency() { + return currency; } public UUID getPlayer() { + return player; } public void setCurrency(Currency currency) { + this.currency = currency; } } diff --git a/Core/src/net/tnemc/core/api/callback/currency/CurrencyLoadCallback.java b/Core/src/net/tnemc/core/api/callback/currency/CurrencyLoadCallback.java index 9c32d032..9b123ad4 100644 --- a/Core/src/net/tnemc/core/api/callback/currency/CurrencyLoadCallback.java +++ b/Core/src/net/tnemc/core/api/callback/currency/CurrencyLoadCallback.java @@ -32,6 +32,7 @@ public class CurrencyLoadCallback implements Callback { private Currency currency; public CurrencyLoadCallback(Currency currency) { + this.currency = currency; } @@ -42,14 +43,17 @@ public CurrencyLoadCallback(Currency currency) { */ @Override public String name() { + return "currency_load"; } public Currency getCurrency() { + return currency; } public void setCurrency(Currency currency) { + this.currency = currency; } } diff --git a/Core/src/net/tnemc/core/api/callback/currency/DenominationLoadCallback.java b/Core/src/net/tnemc/core/api/callback/currency/DenominationLoadCallback.java index 38288a65..5cf4341c 100644 --- a/Core/src/net/tnemc/core/api/callback/currency/DenominationLoadCallback.java +++ b/Core/src/net/tnemc/core/api/callback/currency/DenominationLoadCallback.java @@ -34,6 +34,7 @@ public class DenominationLoadCallback implements Callback { private Denomination denomination; public DenominationLoadCallback(Currency currency, Denomination denomination) { + this.currency = currency; this.denomination = denomination; } @@ -45,22 +46,27 @@ public DenominationLoadCallback(Currency currency, Denomination denomination) { */ @Override public String name() { + return "denomination_load"; } public Currency getCurrency() { + return currency; } public void setCurrency(Currency currency) { + this.currency = currency; } public Denomination getDenomination() { + return denomination; } public void setDenomination(Denomination denomination) { + this.denomination = denomination; } } diff --git a/Core/src/net/tnemc/core/api/callback/transaction/PostTransactionCallback.java b/Core/src/net/tnemc/core/api/callback/transaction/PostTransactionCallback.java index b5927dbe..18e7f8be 100644 --- a/Core/src/net/tnemc/core/api/callback/transaction/PostTransactionCallback.java +++ b/Core/src/net/tnemc/core/api/callback/transaction/PostTransactionCallback.java @@ -23,8 +23,8 @@ import net.tnemc.plugincore.core.api.callback.Callback; /** - * PostTransactionCallback called after a transaction has been processed. Can't cancel the transaction at - * this point. This should be used for logging/tracking purposes. + * PostTransactionCallback called after a transaction has been processed. Can't cancel the + * transaction at this point. This should be used for logging/tracking purposes. *

* Please note: This doesn't mean the transaction is successful. * @@ -40,6 +40,7 @@ public record PostTransactionCallback(TransactionResult result) implements Callb */ @Override public String name() { + return TNECallbacks.TRANSACTION_POST.id(); } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/api/callback/transaction/PreTransactionCallback.java b/Core/src/net/tnemc/core/api/callback/transaction/PreTransactionCallback.java index 99df52aa..7c7f94bf 100644 --- a/Core/src/net/tnemc/core/api/callback/transaction/PreTransactionCallback.java +++ b/Core/src/net/tnemc/core/api/callback/transaction/PreTransactionCallback.java @@ -23,8 +23,8 @@ import net.tnemc.plugincore.core.api.callback.Callback; /** - * PreTransactionCallback represents a callback that is called before a transaction is performed. This - * makes it cancellable. + * PreTransactionCallback represents a callback that is called before a transaction is performed. + * This makes it cancellable. * * @author creatorfromhell * @since 0.1.2.0 @@ -34,6 +34,7 @@ public class PreTransactionCallback implements Callback { protected Transaction transaction; public PreTransactionCallback(Transaction transaction) { + this.transaction = transaction; } @@ -44,14 +45,17 @@ public PreTransactionCallback(Transaction transaction) { */ @Override public String name() { + return TNECallbacks.TRANSACTION_PRE.id(); } public Transaction getTransaction() { + return transaction; } public void setTransaction(Transaction transaction) { + this.transaction = transaction; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/api/response/AccountAPIResponse.java b/Core/src/net/tnemc/core/api/response/AccountAPIResponse.java index 212deb09..5d648aac 100644 --- a/Core/src/net/tnemc/core/api/response/AccountAPIResponse.java +++ b/Core/src/net/tnemc/core/api/response/AccountAPIResponse.java @@ -30,8 +30,8 @@ * AccountAPIResponse represents an API response that is related to an account. * * @author creatorfromhell - * @since 0.1.2.0 * @see TNEAPI,Account,EconomyResponse + * @since 0.1.2.0 */ public class AccountAPIResponse { @@ -39,15 +39,18 @@ public class AccountAPIResponse { private final EconomyResponse response; public AccountAPIResponse(@Nullable Account account, EconomyResponse response) { + this.account = account; this.response = response; } public Optional getAccount() { + return Optional.ofNullable(account); } public Optional getPlayerAccount() { + if(account != null && (account instanceof PlayerAccount)) { return Optional.of((PlayerAccount)account); } @@ -55,6 +58,7 @@ public Optional getPlayerAccount() { } public EconomyResponse getResponse() { + return response; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/channel/BalanceHandler.java b/Core/src/net/tnemc/core/channel/BalanceHandler.java index 2880fc31..f29998e5 100644 --- a/Core/src/net/tnemc/core/channel/BalanceHandler.java +++ b/Core/src/net/tnemc/core/channel/BalanceHandler.java @@ -43,10 +43,12 @@ public class BalanceHandler extends ChannelMessageHandler { public BalanceHandler() { + super("balance"); } public static void send(final String identifier, final String name, String region, UUID currency, Identifier handler, BigDecimal amount) { + final ByteArrayDataOutput out = ByteStreams.newDataOutput(); out.writeUTF(PluginCore.instance().getServerID().toString()); out.writeUTF(identifier); diff --git a/Core/src/net/tnemc/core/channel/ConfigHandler.java b/Core/src/net/tnemc/core/channel/ConfigHandler.java index ba949cf1..1b711b57 100644 --- a/Core/src/net/tnemc/core/channel/ConfigHandler.java +++ b/Core/src/net/tnemc/core/channel/ConfigHandler.java @@ -40,7 +40,9 @@ * @since 0.1.2.0 */ public class ConfigHandler extends ChannelMessageHandler { + public ConfigHandler() { + super("config"); } diff --git a/Core/src/net/tnemc/core/channel/CreateHandler.java b/Core/src/net/tnemc/core/channel/CreateHandler.java index f5977d26..153e7688 100644 --- a/Core/src/net/tnemc/core/channel/CreateHandler.java +++ b/Core/src/net/tnemc/core/channel/CreateHandler.java @@ -36,10 +36,12 @@ public class CreateHandler extends ChannelMessageHandler { public CreateHandler() { + super("create"); } public static void send(final String identifier, final String name) { + final ByteArrayDataOutput out = ByteStreams.newDataOutput(); out.writeUTF(PluginCore.instance().getServerID().toString()); out.writeUTF(identifier); diff --git a/Core/src/net/tnemc/core/channel/MessageHandler.java b/Core/src/net/tnemc/core/channel/MessageHandler.java index 7aea7f12..ca4ee4dd 100644 --- a/Core/src/net/tnemc/core/channel/MessageHandler.java +++ b/Core/src/net/tnemc/core/channel/MessageHandler.java @@ -40,10 +40,12 @@ public class MessageHandler extends ChannelMessageHandler { public MessageHandler() { + super("message"); } public static void send(final UUID identifier, final Component component) { + final ByteArrayDataOutput out = ByteStreams.newDataOutput(); out.writeUTF(PluginCore.instance().getServerID().toString()); out.writeUTF(identifier.toString()); diff --git a/Core/src/net/tnemc/core/channel/SyncHandler.java b/Core/src/net/tnemc/core/channel/SyncHandler.java index b35a8dbe..dcd411f2 100644 --- a/Core/src/net/tnemc/core/channel/SyncHandler.java +++ b/Core/src/net/tnemc/core/channel/SyncHandler.java @@ -34,10 +34,12 @@ public class SyncHandler extends ChannelMessageHandler { public SyncHandler() { + super("sync"); } public static void send(String account) { + ByteArrayDataOutput out = ByteStreams.newDataOutput(); out.writeUTF(PluginCore.instance().getServerID().toString()); out.writeUTF(account); diff --git a/Core/src/net/tnemc/core/command/AdminCommand.java b/Core/src/net/tnemc/core/command/AdminCommand.java index 1f050dfa..2590d2e2 100644 --- a/Core/src/net/tnemc/core/command/AdminCommand.java +++ b/Core/src/net/tnemc/core/command/AdminCommand.java @@ -43,6 +43,7 @@ public class AdminCommand extends BaseCommand { public static void onMyEco(CmdSource sender) { + if(sender.player().isPresent()) { sender.player().get().inventory().openMenu(sender.player().get(), "my_eco"); @@ -50,6 +51,7 @@ public static void onMyEco(CmdSource sender) { } public static void onBackup(CmdSource sender) { + if(StorageManager.instance().backup()) { sender.message(new MessageData("Messages.Data.Backup")); @@ -127,10 +129,12 @@ public static void onExtract(CmdSource sender) { } public static void onPurge(CmdSource sender) { + TNECore.instance().storage().purge(); } public static void onReload(CmdSource sender, String type) { + String formattedType = type; switch(type.toLowerCase()) { case "config" -> { @@ -155,6 +159,7 @@ public static void onReload(CmdSource sender, String type) { } public static void onReset(CmdSource sender) { + StorageManager.instance().reset(); } @@ -166,6 +171,7 @@ public static void onRestore(CmdSource sender, int extraction) { } public static void onSave(CmdSource sender) { + StorageManager.instance().storeAll(); sender.message(new MessageData("Messages.Data.Save")); } @@ -183,6 +189,7 @@ public static void onStatus(CmdSource sender, Account account, AccountStatus } public static void onVersion(CmdSource sender) { + final MessageData data = new MessageData("Messages.General.Version"); data.addReplacement("$version", TNECore.version); data.addReplacement("$build", TNECore.build); diff --git a/Core/src/net/tnemc/core/command/BaseCommand.java b/Core/src/net/tnemc/core/command/BaseCommand.java index 6862f5d6..54762286 100644 --- a/Core/src/net/tnemc/core/command/BaseCommand.java +++ b/Core/src/net/tnemc/core/command/BaseCommand.java @@ -43,6 +43,7 @@ public static void help(CmdSource source, CommandHelp helpEntries, fi } public static Optional account(CmdSource sender, final String type) { + if(sender.identifier().isEmpty()) { return Optional.empty(); } @@ -50,6 +51,7 @@ public static Optional account(CmdSource sender, final String type) } public static Optional account(final UUID sender, final String type) { + if(sender == null) { return Optional.empty(); } @@ -58,9 +60,11 @@ public static Optional account(final UUID sender, final String type) { /** * Used to get the world for this command source. + * * @return The name of the world that this command source is in. */ public static String region(CmdSource sender) { + if(sender.player().isPresent()) { return TNECore.eco().region().getMode().region(sender.player().get()); } diff --git a/Core/src/net/tnemc/core/command/ModuleCommand.java b/Core/src/net/tnemc/core/command/ModuleCommand.java index fda8e9a6..f310f966 100644 --- a/Core/src/net/tnemc/core/command/ModuleCommand.java +++ b/Core/src/net/tnemc/core/command/ModuleCommand.java @@ -107,6 +107,7 @@ public static void onInfo(CmdSource sender, String moduleName) { } public static void onList(CmdSource sender) { + final StringBuilder modules = new StringBuilder(); PluginCore.loader().getModules().forEach((key, value)->{ if(!modules.isEmpty()) modules.append(", "); @@ -119,6 +120,7 @@ public static void onList(CmdSource sender) { } public static void onLoad(CmdSource sender, String moduleName) { + final boolean loaded = PluginCore.loader().load(moduleName); if(!loaded) { diff --git a/Core/src/net/tnemc/core/command/MoneyCommand.java b/Core/src/net/tnemc/core/command/MoneyCommand.java index 3660352c..14d75465 100644 --- a/Core/src/net/tnemc/core/command/MoneyCommand.java +++ b/Core/src/net/tnemc/core/command/MoneyCommand.java @@ -68,6 +68,7 @@ public class MoneyCommand extends BaseCommand { //ArgumentsParser: [currency] public static void onMyBal(CmdSource sender) { + if(sender.player().isPresent()) { sender.player().get().inventory().openMenu(sender.player().get(), "my_bal"); } @@ -162,13 +163,13 @@ public static void onConvert(CmdSource sender, PercentBigDecimal amount, Curr final UUID sourceID = (sender.identifier().isPresent())? sender.identifier().get() : TNECore.instance().getServerAccount(); final Transaction transaction = new Transaction("convert") - .from(account.get(), modifierFrom) - .to(account.get(), modifier) - .processor(EconomyManager.baseProcessor()) - .source(new PlayerSource(sourceID)); + .from(account.get(), modifierFrom) + .to(account.get(), modifier) + .processor(EconomyManager.baseProcessor()) + .source(new PlayerSource(sourceID)); final Optional receipt = processTransaction(sender, transaction, account.get().getName(), amount.value()); - if(receipt.isPresent()){ + if(receipt.isPresent()) { final MessageData data = new MessageData("Messages.Money.Converted"); data.addReplacement("$from_amount", amount.value().toPlainString()); data.addReplacement("$amount", CurrencyFormatter.format(account.get(), @@ -217,9 +218,9 @@ public static void onDeposit(CmdSource sender, PercentBigDecimal amount, Curr } final HoldingsModifier modifier = new HoldingsModifier(region, - currency.getUid(), - amount, - EconomyManager.VIRTUAL + currency.getUid(), + amount, + EconomyManager.VIRTUAL ); final UUID sourceID = (sender.identifier().isPresent())? sender.identifier().get() : TNECore.instance().getServerAccount(); @@ -233,7 +234,7 @@ public static void onDeposit(CmdSource sender, PercentBigDecimal amount, Curr if(receipt.isPresent()) { final MessageData data = new MessageData("Messages.Money.Deposit"); data.addReplacement("$amount", CurrencyFormatter.format(senderAccount.get(), - modifier.asEntry())); + modifier.asEntry())); sender.message(data); } } @@ -264,8 +265,8 @@ public static void onGive(CmdSource sender, Account account, PercentBigDecima final UUID sourceID = (sender.identifier().isPresent())? sender.identifier().get() : TNECore.instance().getServerAccount(); final Transaction transaction = new Transaction("give") - .to(account, modifier) - .source(new PlayerSource(sourceID)); + .to(account, modifier) + .source(new PlayerSource(sourceID)); final Optional receipt = processTransaction(sender, transaction, account.getName(), amount.value()); if(receipt.isPresent()) { @@ -318,7 +319,7 @@ public static void onGiveNote(CmdSource sender, Account acc, BigDecimal amoun final Collection> left = PluginCore.server().calculations().giveItems(Collections.singletonList(note.get().stack(currency.getIdentifier(), BaseCommand.region(sender), rounded)), provider.get().inventory().getInventory(false)); final MessageData entryMSG = new MessageData("Messages.Note.Given"); - entryMSG.addReplacement("$currency",currency.getIdentifier()); + entryMSG.addReplacement("$currency", currency.getIdentifier()); entryMSG.addReplacement("$amount", CurrencyFormatter.format(account, rounded)); provider.get().message(entryMSG); @@ -370,14 +371,14 @@ public static void onNote(CmdSource sender, PercentBigDecimal amount, Currenc final HoldingsModifier modifier = new HoldingsModifier(BaseCommand.region(sender), currency.getUid(), - amt + amt ); final UUID sourceID = (sender.identifier().isPresent())? sender.identifier().get() : TNECore.instance().getServerAccount(); final Transaction transaction = new Transaction("note") - .from(account.get(), modifier.counter()) - .processor(EconomyManager.baseProcessor()) - .source(new PlayerSource(sourceID)); + .from(account.get(), modifier.counter()) + .processor(EconomyManager.baseProcessor()) + .source(new PlayerSource(sourceID)); final Optional receipt = processTransaction(sender, transaction, account.get().getName(), amount.value()); @@ -385,7 +386,7 @@ public static void onNote(CmdSource sender, PercentBigDecimal amount, Currenc final Collection> left = PluginCore.server().calculations().giveItems(Collections.singletonList(note.get().stack(currency.getIdentifier(), BaseCommand.region(sender), rounded)), provider.get().inventory().getInventory(false)); final MessageData entryMSG = new MessageData("Messages.Note.Given"); - entryMSG.addReplacement("$currency",currency.getIdentifier()); + entryMSG.addReplacement("$currency", currency.getIdentifier()); entryMSG.addReplacement("$amount", CurrencyFormatter.format(account.get(), modifier.asEntry())); sender.message(entryMSG); @@ -443,6 +444,7 @@ public static void onOther(CmdSource sender, Account account, String region, } public static void printBalance(final CmdSource sender, final Account account, final String region, final Currency currency) { + final MessageData entryMSG = new MessageData("Messages.Money.HoldingsMultiSingle"); entryMSG.addReplacement("$currency", currency.getIdentifier()); @@ -525,7 +527,7 @@ public static void onPay(CmdSource sender, Account acc, PercentBigDecimal amo data.addReplacement("$distance", String.valueOf(MainConfig.yaml().getInt("Core.Commands.Pay.Radius"))); if(!(senderAccount.get() instanceof PlayerAccount) || !((PlayerAccount)senderAccount.get()).isOnline() - || !(account instanceof PlayerAccount) || !((PlayerAccount)account).isOnline()) { + || !(account instanceof PlayerAccount) || !((PlayerAccount)account).isOnline()) { sender.message(data); return; } @@ -533,7 +535,7 @@ public static void onPay(CmdSource sender, Account acc, PercentBigDecimal amo final Optional senderPlayer = ((PlayerAccount)senderAccount.get()).getPlayer(); final Optional playerPlayer = ((PlayerAccount)account).getPlayer(); if(senderPlayer.isEmpty() || playerPlayer.isEmpty() - || senderPlayer.get().getLocation().isEmpty() || playerPlayer.get().getLocation().isEmpty()) { + || senderPlayer.get().getLocation().isEmpty() || playerPlayer.get().getLocation().isEmpty()) { sender.message(data); return; } @@ -546,15 +548,15 @@ public static void onPay(CmdSource sender, Account acc, PercentBigDecimal amo final HoldingsModifier modifier = new HoldingsModifier(BaseCommand.region(sender), currency.getUid(), - amount + amount ); final UUID sourceID = (sender.identifier().isPresent())? sender.identifier().get() : TNECore.instance().getServerAccount(); final Transaction transaction = new Transaction("pay") - .to(account, modifier) - .from(senderAccount.get(), modifier.counter()) - .processor(EconomyManager.baseProcessor()) - .source(new PlayerSource(sourceID)); + .to(account, modifier) + .from(senderAccount.get(), modifier.counter()) + .processor(EconomyManager.baseProcessor()) + .source(new PlayerSource(sourceID)); final Optional receipt = processTransaction(sender, transaction, account.getName(), amount.value()); if(receipt.isPresent()) { @@ -639,14 +641,14 @@ public static void onSet(CmdSource sender, Account account, BigDecimal amount final HoldingsModifier modifier = new HoldingsModifier(region, currency.getUid(), - amount.setScale(currency.getDecimalPlaces(), RoundingMode.DOWN), + amount.setScale(currency.getDecimalPlaces(), RoundingMode.DOWN), HoldingsOperation.SET); final UUID sourceID = (sender.identifier().isPresent())? sender.identifier().get() : TNECore.instance().getServerAccount(); final Transaction transaction = new Transaction("set") - .to(account, modifier) - .processor(EconomyManager.baseProcessor()) - .source(new PlayerSource(sourceID)); + .to(account, modifier) + .processor(EconomyManager.baseProcessor()) + .source(new PlayerSource(sourceID)); final Optional receipt = processTransaction(sender, transaction, account.getName(), amount); @@ -656,7 +658,7 @@ public static void onSet(CmdSource sender, Account account, BigDecimal amount msg.addReplacement("$currency", currency.getIdentifier()); msg.addReplacement("$amount", CurrencyFormatter.format(account, modifier.asEntry()) - ); + ); sender.message(msg); } } @@ -683,15 +685,15 @@ public static void onSetAll(CmdSource sender, BigDecimal amount, String regio final HoldingsModifier modifier = new HoldingsModifier(region, currency.getUid(), - amount.setScale(currency.getDecimalPlaces(), RoundingMode.DOWN), + amount.setScale(currency.getDecimalPlaces(), RoundingMode.DOWN), HoldingsOperation.SET); final UUID sourceID = (sender.identifier().isPresent())? sender.identifier().get() : TNECore.instance().getServerAccount(); for(Account account : TNECore.eco().account().getAccounts().values()) { final Transaction transaction = new Transaction("set") - .to(account, modifier) - .processor(EconomyManager.baseProcessor()) - .source(new PlayerSource(sourceID)); + .to(account, modifier) + .processor(EconomyManager.baseProcessor()) + .source(new PlayerSource(sourceID)); final Optional receipt = processTransaction(sender, transaction, account.getName(), amount); @@ -701,11 +703,11 @@ public static void onSetAll(CmdSource sender, BigDecimal amount, String regio msg.addReplacement("$currency", currency.getIdentifier()); msg.addReplacement("$amount", CurrencyFormatter.format(account, modifier.asEntry()) - ); + ); - msg.addReplacements(new String[] { + msg.addReplacements(new String[]{ "" - }, new String[] { + }, new String[]{ }); sender.message(msg); @@ -715,6 +717,7 @@ public static void onSetAll(CmdSource sender, BigDecimal amount, String regio } public static void onSwitch(CmdSource sender, Account account) { + if(account instanceof SharedAccount shared) { if(sender.identifier().isEmpty()) { @@ -806,9 +809,9 @@ public static void onTake(CmdSource sender, Account account, PercentBigDecima final UUID sourceID = (sender.identifier().isPresent())? sender.identifier().get() : TNECore.instance().getServerAccount(); final Transaction transaction = new Transaction("take") - .to(account, modifier.counter()) - .processor(EconomyManager.baseProcessor()) - .source(new PlayerSource(sourceID)); + .to(account, modifier.counter()) + .processor(EconomyManager.baseProcessor()) + .source(new PlayerSource(sourceID)); final Optional receipt = processTransaction(sender, transaction, account.getName(), amount.value()); if(receipt.isPresent()) { @@ -865,7 +868,7 @@ public static void onTop(CmdSource sender, Integer page, Currency currency, B } if(refresh && !senderAccount.get().isPlayer() || refresh && senderAccount.get().isPlayer() && ((PlayerAccount)senderAccount.get()).getPlayer().isPresent() - && ((PlayerAccount)senderAccount.get()).getPlayer().get().hasPermission("tne.money.top.refresh")) { + && ((PlayerAccount)senderAccount.get()).getPlayer().get().hasPermission("tne.money.top.refresh")) { TopManager.instance().load(); } @@ -934,9 +937,9 @@ public static void onWithdraw(CmdSource sender, PercentBigDecimal amount, Cur } final HoldingsModifier modifier = new HoldingsModifier(BaseCommand.region(sender), - currency.getUid(), - amount, - EconomyManager.ITEM_ONLY + currency.getUid(), + amount, + EconomyManager.ITEM_ONLY ); final UUID sourceID = (sender.identifier().isPresent())? sender.identifier().get() : TNECore.instance().getServerAccount(); @@ -952,12 +955,13 @@ public static void onWithdraw(CmdSource sender, PercentBigDecimal amount, Cur final MessageData data = new MessageData("Messages.Money.Withdrawn"); data.addReplacement("$currency", currency.getIdentifier()); data.addReplacement("$amount", CurrencyFormatter.format(senderAccount.get(), - modifier.asEntry())); + modifier.asEntry())); sender.message(data); } } public static Optional processTransaction(CmdSource sender, Transaction transaction, final String modifiedAccount, final BigDecimal modifier) { + try { final TransactionResult result = transaction.process(); diff --git a/Core/src/net/tnemc/core/command/TransactionCommand.java b/Core/src/net/tnemc/core/command/TransactionCommand.java index adfed08d..a6ae21e4 100644 --- a/Core/src/net/tnemc/core/command/TransactionCommand.java +++ b/Core/src/net/tnemc/core/command/TransactionCommand.java @@ -43,6 +43,7 @@ public class TransactionCommand { //[page #] public static void away(CmdSource sender, int page) { + final Optional account = BaseCommand.account(sender, "away"); if(sender.player().isPresent() && MainConfig.yaml().getBoolean("Core.Commands.GUIAlternatives", true)) { @@ -81,6 +82,7 @@ public static void away(CmdSource sender, int page) { //[page:#] [world:name/all] [player:name] public static void history(CmdSource sender, int page, String region, Account account) { + if(sender.player().isPresent() && MainConfig.yaml().getBoolean("Core.Commands.GUIAlternatives", true)) { sender.player().get().inventory().openMenu(sender.player().get(), "transaction_menu"); return; @@ -105,17 +107,17 @@ public static void history(CmdSource sender, int page, String region, Account final Optional receipt = account.findReceipt(entry.getValue()); if(receipt.isPresent()) { - String from = "None"; - final Optional fromACC = receipt.get().getFrom().asAccount(); - if(fromACC.isPresent()) { - from = fromACC.get().getName(); - } + String from = "None"; + final Optional fromACC = receipt.get().getFrom().asAccount(); + if(fromACC.isPresent()) { + from = fromACC.get().getName(); + } - String to = "None"; - final Optional toACC = receipt.get().getTo().asAccount(); - if(toACC.isPresent()) { - to = toACC.get().getName(); - } + String to = "None"; + final Optional toACC = receipt.get().getTo().asAccount(); + if(toACC.isPresent()) { + to = toACC.get().getName(); + } final MessageData awayEntry = new MessageData("Messages.Transaction.HistoryEntry"); awayEntry.addReplacement("$id", entry.getValue().toString()); @@ -129,6 +131,7 @@ public static void history(CmdSource sender, int page, String region, Account // public static void info(CmdSource sender, UUID uuid) { + final Optional receipt = TransactionManager.receipts().getReceiptByUUID(uuid); if(receipt.isEmpty()) { @@ -146,6 +149,7 @@ public static void info(CmdSource sender, UUID uuid) { // public static void voidT(CmdSource sender, Account account, UUID uuid) { + final Optional receipt = account.findReceipt(uuid); if(receipt.isEmpty()) { diff --git a/Core/src/net/tnemc/core/command/parameters/PercentBigDecimal.java b/Core/src/net/tnemc/core/command/parameters/PercentBigDecimal.java index acc711b9..ddb25892 100644 --- a/Core/src/net/tnemc/core/command/parameters/PercentBigDecimal.java +++ b/Core/src/net/tnemc/core/command/parameters/PercentBigDecimal.java @@ -29,6 +29,7 @@ public record PercentBigDecimal(boolean isPercent, BigDecimal value) { public PercentBigDecimal negate() { + return new PercentBigDecimal(isPercent, value.negate()); } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/command/parameters/resolver/AccountResolver.java b/Core/src/net/tnemc/core/command/parameters/resolver/AccountResolver.java index 11077c97..28f208cc 100644 --- a/Core/src/net/tnemc/core/command/parameters/resolver/AccountResolver.java +++ b/Core/src/net/tnemc/core/command/parameters/resolver/AccountResolver.java @@ -36,6 +36,7 @@ public class AccountResolver implements ValueResolver { @Override public Account resolve(@NotNull ValueResolverContext context) throws Throwable { + String value = context.arguments().pop(); if(value.equalsIgnoreCase("SELF_ACCOUNT")) { diff --git a/Core/src/net/tnemc/core/command/parameters/resolver/BigDecimalResolver.java b/Core/src/net/tnemc/core/command/parameters/resolver/BigDecimalResolver.java index 46043220..04fe5a26 100644 --- a/Core/src/net/tnemc/core/command/parameters/resolver/BigDecimalResolver.java +++ b/Core/src/net/tnemc/core/command/parameters/resolver/BigDecimalResolver.java @@ -33,6 +33,7 @@ public class BigDecimalResolver implements ValueResolver { @Override public BigDecimal resolve(@NotNull ValueResolverContext context) { + final String value = context.arguments().pop(); return new BigDecimal(PercentDecimalResolver.replaceDecimals(value)); diff --git a/Core/src/net/tnemc/core/command/parameters/resolver/CurrencyResolver.java b/Core/src/net/tnemc/core/command/parameters/resolver/CurrencyResolver.java index 2d1fe4a0..ee68440a 100644 --- a/Core/src/net/tnemc/core/command/parameters/resolver/CurrencyResolver.java +++ b/Core/src/net/tnemc/core/command/parameters/resolver/CurrencyResolver.java @@ -35,6 +35,7 @@ public class CurrencyResolver implements ValueResolver { @Override public Currency resolve(@NotNull ValueResolverContext context) { + final String value = context.arguments().pop(); final Optional currency = TNECore.eco().currency().findCurrency(value); diff --git a/Core/src/net/tnemc/core/command/parameters/resolver/DebugResolver.java b/Core/src/net/tnemc/core/command/parameters/resolver/DebugResolver.java index d0ac531f..7129f2a5 100644 --- a/Core/src/net/tnemc/core/command/parameters/resolver/DebugResolver.java +++ b/Core/src/net/tnemc/core/command/parameters/resolver/DebugResolver.java @@ -32,6 +32,7 @@ public class DebugResolver implements ValueResolver { @Override public DebugLevel resolve(@NotNull ValueResolverContext context) throws Throwable { + final String value = context.arguments().pop(); return DebugLevel.fromID(value); diff --git a/Core/src/net/tnemc/core/command/parameters/resolver/PercentDecimalResolver.java b/Core/src/net/tnemc/core/command/parameters/resolver/PercentDecimalResolver.java index c82da3ca..86f3e592 100644 --- a/Core/src/net/tnemc/core/command/parameters/resolver/PercentDecimalResolver.java +++ b/Core/src/net/tnemc/core/command/parameters/resolver/PercentDecimalResolver.java @@ -36,6 +36,7 @@ public class PercentDecimalResolver implements ValueResolver @Override public PercentBigDecimal resolve(@NotNull ValueResolverContext context) { + final String value = context.arguments().pop(); final boolean percent = value.contains("%"); diff --git a/Core/src/net/tnemc/core/command/parameters/resolver/StatusResolver.java b/Core/src/net/tnemc/core/command/parameters/resolver/StatusResolver.java index 629af892..5cf3fea5 100644 --- a/Core/src/net/tnemc/core/command/parameters/resolver/StatusResolver.java +++ b/Core/src/net/tnemc/core/command/parameters/resolver/StatusResolver.java @@ -36,6 +36,7 @@ public class StatusResolver implements ValueResolver { @Override public AccountStatus resolve(@NotNull ValueResolverContext context) throws Throwable { + final String value = context.arguments().pop(); final Optional status = Optional.ofNullable(TNECore.eco().account().getStatuses().get(value)); diff --git a/Core/src/net/tnemc/core/command/parameters/suggestion/AccountSuggestion.java b/Core/src/net/tnemc/core/command/parameters/suggestion/AccountSuggestion.java index cb4a0e3c..e8d7178a 100644 --- a/Core/src/net/tnemc/core/command/parameters/suggestion/AccountSuggestion.java +++ b/Core/src/net/tnemc/core/command/parameters/suggestion/AccountSuggestion.java @@ -39,6 +39,7 @@ public class AccountSuggestion implements SuggestionProvider { @Override public @NotNull Collection getSuggestions(@NotNull List list, @NotNull CommandActor commandActor, @NotNull ExecutableCommand executableCommand) throws Throwable { + return TNECore.eco().account().getAccounts().values().stream().map(Account::getName).collect(Collectors.toList()); } } diff --git a/Core/src/net/tnemc/core/command/parameters/suggestion/CurrencySuggestion.java b/Core/src/net/tnemc/core/command/parameters/suggestion/CurrencySuggestion.java index bf042970..5ea3902e 100644 --- a/Core/src/net/tnemc/core/command/parameters/suggestion/CurrencySuggestion.java +++ b/Core/src/net/tnemc/core/command/parameters/suggestion/CurrencySuggestion.java @@ -39,6 +39,7 @@ public class CurrencySuggestion implements SuggestionProvider { @Override public @NotNull Collection getSuggestions(@NotNull List list, @NotNull CommandActor commandActor, @NotNull ExecutableCommand executableCommand) throws Throwable { + return TNECore.eco().currency().currencies().stream().map(Currency::getIdentifier).collect(Collectors.toList()); } } diff --git a/Core/src/net/tnemc/core/command/parameters/suggestion/DebugSuggestion.java b/Core/src/net/tnemc/core/command/parameters/suggestion/DebugSuggestion.java index 03369e94..60ed1131 100644 --- a/Core/src/net/tnemc/core/command/parameters/suggestion/DebugSuggestion.java +++ b/Core/src/net/tnemc/core/command/parameters/suggestion/DebugSuggestion.java @@ -39,6 +39,7 @@ public class DebugSuggestion implements SuggestionProvider { @Override public @NotNull Collection getSuggestions(@NotNull List list, @NotNull CommandActor commandActor, @NotNull ExecutableCommand executableCommand) throws Throwable { + return Arrays.stream(DebugLevel.values()).map(DebugLevel::getIdentifier).collect(Collectors.toList()); } } diff --git a/Core/src/net/tnemc/core/command/parameters/suggestion/RegionSuggestion.java b/Core/src/net/tnemc/core/command/parameters/suggestion/RegionSuggestion.java index 27e16a80..1ee796ae 100644 --- a/Core/src/net/tnemc/core/command/parameters/suggestion/RegionSuggestion.java +++ b/Core/src/net/tnemc/core/command/parameters/suggestion/RegionSuggestion.java @@ -37,6 +37,7 @@ public class RegionSuggestion implements SuggestionProvider { @Override public @NotNull Collection getSuggestions(@NotNull List list, @NotNull CommandActor commandActor, @NotNull ExecutableCommand executableCommand) throws Throwable { + return TNECore.eco().region().getRegions().keySet().stream().toList(); } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/command/parameters/suggestion/StatusSuggestion.java b/Core/src/net/tnemc/core/command/parameters/suggestion/StatusSuggestion.java index e9e19a7f..06fefb88 100644 --- a/Core/src/net/tnemc/core/command/parameters/suggestion/StatusSuggestion.java +++ b/Core/src/net/tnemc/core/command/parameters/suggestion/StatusSuggestion.java @@ -39,6 +39,7 @@ public class StatusSuggestion implements SuggestionProvider { @Override public @NotNull Collection getSuggestions(@NotNull List list, @NotNull CommandActor commandActor, @NotNull ExecutableCommand executableCommand) throws Throwable { + return TNECore.eco().account().getStatuses().values().stream().map(AccountStatus::identifier).collect(Collectors.toList()); } } diff --git a/Core/src/net/tnemc/core/config/DataConfig.java b/Core/src/net/tnemc/core/config/DataConfig.java index a8c082c5..bbe895a2 100644 --- a/Core/src/net/tnemc/core/config/DataConfig.java +++ b/Core/src/net/tnemc/core/config/DataConfig.java @@ -37,14 +37,16 @@ public class DataConfig extends Config { private static DataConfig instance; public DataConfig() { + super("data.yml", "data.yml", Collections.singletonList("Data"), - LoaderSettings.builder().setAutoUpdate(true).build(), - UpdaterSettings.builder().setAutoSave(true).setVersioning(new BasicVersioning("Data.config-version")).build()); + LoaderSettings.builder().setAutoUpdate(true).build(), + UpdaterSettings.builder().setAutoSave(true).setVersioning(new BasicVersioning("Data.config-version")).build()); instance = this; } public static YamlDocument yaml() { + return instance.getYaml(); } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/config/MainConfig.java b/Core/src/net/tnemc/core/config/MainConfig.java index ec64e5e5..04f320ff 100644 --- a/Core/src/net/tnemc/core/config/MainConfig.java +++ b/Core/src/net/tnemc/core/config/MainConfig.java @@ -35,15 +35,18 @@ public class MainConfig extends Config { private static MainConfig instance; + public MainConfig() { + super("config.yml", "config.yml", Collections.singletonList("Core"), - LoaderSettings.builder().setAutoUpdate(true).build(), - UpdaterSettings.builder().setAutoSave(true).setVersioning(new BasicVersioning("Core.config-version")).build()); + LoaderSettings.builder().setAutoUpdate(true).build(), + UpdaterSettings.builder().setAutoSave(true).setVersioning(new BasicVersioning("Core.config-version")).build()); instance = this; } public static YamlDocument yaml() { + return instance.getYaml(); } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/config/MessageConfig.java b/Core/src/net/tnemc/core/config/MessageConfig.java index cb310b7a..e76b2891 100644 --- a/Core/src/net/tnemc/core/config/MessageConfig.java +++ b/Core/src/net/tnemc/core/config/MessageConfig.java @@ -49,18 +49,21 @@ public class MessageConfig extends Config { private final Map languages = new HashMap<>(); public MessageConfig() { + super("messages.yml", "messages.yml", Collections.singletonList("Messages"), - LoaderSettings.builder().setAutoUpdate(true).build(), - UpdaterSettings.builder().setAutoSave(true).setVersioning(new BasicVersioning("Messages.config-version")).build()); + LoaderSettings.builder().setAutoUpdate(true).build(), + UpdaterSettings.builder().setAutoSave(true).setVersioning(new BasicVersioning("Messages.config-version")).build()); instance = this; } public static YamlDocument yaml() { + return instance.getYaml(); } public String getString(final String node, final UUID player) { + final Optional account = TNECore.eco().account().findAccount(player); if(account.isPresent() && account.get() instanceof PlayerAccount) { @@ -75,6 +78,7 @@ public String getString(final String node, final UUID player) { } public String getString(final String node, final String lang) { + if(languages.containsKey(lang) && languages.get(lang).hasTranslation(node)) { return languages.get(lang).getTranslation(node); } @@ -87,17 +91,18 @@ public String getString(final String node, final String lang) { } public void loadLanguages() { - final File directory = new File(PluginCore.directory(), "languages"); + + final File directory = new File(PluginCore.directory(), "languages"); if(!directory.exists()) { directory.mkdir(); return; } - final File[] langFiles = directory.listFiles((dir, name) -> name.endsWith(".yml")); + final File[] langFiles = directory.listFiles((dir, name)->name.endsWith(".yml")); if(langFiles != null) { - for (File langFile : langFiles) { + for(File langFile : langFiles) { final String name = langFile.getName().replace(".yml", ""); diff --git a/Core/src/net/tnemc/core/currency/Currency.java b/Core/src/net/tnemc/core/currency/Currency.java index 95081049..a866468f 100644 --- a/Core/src/net/tnemc/core/currency/Currency.java +++ b/Core/src/net/tnemc/core/currency/Currency.java @@ -85,6 +85,7 @@ public class Currency { private Note note; public Currency(final String identifier) { + this.file = identifier + ".yml"; //Currency Info Configurations @@ -121,23 +122,28 @@ public Currency(final String identifier) { } public Denomination getDenominationByWeight(final BigDecimal weight) { + return denominations.get(weight); } public boolean isNotable() { + return note != null; } public Optional getNote() { + return Optional.ofNullable(note); } public CurrencyType type() { + final Optional type = TNECore.eco().currency().findType(this.type); return type.orElseGet(()->TNECore.eco().currency().findType("virtual").get()); } public Optional convertValue(final String currency, final BigDecimal amount) { + if(conversion.containsKey(currency)) { return Optional.of(amount.multiply(BigDecimal.valueOf(conversion.get(currency)))); } @@ -145,203 +151,253 @@ public Optional convertValue(final String currency, final BigDecimal } public Map getConversion() { + return conversion; } public BigDecimal getStartingHoldings() { + return startingHoldings; } public void setStartingHoldings(BigDecimal startingHoldings) { + this.startingHoldings = startingHoldings; } public BigDecimal getMaxBalance() { + return maxBalance; } public void setMaxBalance(BigDecimal maxBalance) { + this.maxBalance = maxBalance; } public BigDecimal getMinBalance() { + return minBalance; } public void setMinBalance(BigDecimal minBalance) { + this.minBalance = minBalance; } public String getFile() { + return file; } public void setFile(String file) { + this.file = file; } public UUID getUid() { + return uid; } public void setUid(UUID uid) { + this.uid = uid; } public String getIdentifier() { + return identifier; } public void setIdentifier(String identifier) { + this.identifier = identifier; this.file = identifier + ".yml"; } public String getIconMaterial() { + return iconMaterial; } public void setIconMaterial(String iconMaterial) { + this.iconMaterial = iconMaterial; } public String getType() { + return type; } public void setType(String type) { + this.type = type; } public String getFormat() { + return format; } public void setFormat(String format) { + this.format = format; } public String getSymbol() { + return symbol; } public void setSymbol(String symbol) { + this.symbol = symbol; } public String getPrefixes() { + return prefixes; } public void setPrefixes(String prefixes) { + this.prefixes = prefixes; } public String getPrefixesj() { + return prefixesj; } public void setPrefixesj(String prefixesj) { + this.prefixesj = prefixesj; } public String getDecimal() { + return decimal; } public void setDecimal(String decimal) { + this.decimal = decimal; } public boolean isBalanceShow() { + return balanceShow; } public void setBalanceShow(boolean balanceShow) { + this.balanceShow = balanceShow; } public String getDisplay() { + return display; } public void setDisplay(String display) { + this.display = display; } public String getDisplayPlural() { + return displayPlural; } public void setDisplayPlural(String displayPlural) { + this.displayPlural = displayPlural; } public String getDisplayMinor() { + return displayMinor; } public void setDisplayMinor(String displayMinor) { + this.displayMinor = displayMinor; } public String getDisplayMinorPlural() { + return displayMinorPlural; } public void setDisplayMinorPlural(String displayMinorPlural) { + this.displayMinorPlural = displayMinorPlural; } public boolean isSeparateMajor() { + return separateMajor; } public void setSeparateMajor(boolean separateMajor) { + this.separateMajor = separateMajor; } public String getMajorSeparator() { + return majorSeparator; } public void setMajorSeparator(String majorSeparator) { + this.majorSeparator = majorSeparator; } public int getDecimalPlaces() { + return decimalPlaces; } public void setDecimalPlaces(int decimalPlaces) { + this.decimalPlaces = decimalPlaces; } public int getMinorWeight() { + return minorWeight; } public void setMinorWeight(int minorWeight) { + this.minorWeight = minorWeight; } public boolean negativeSupport() { + return negativeSupport; } public void setNote(Note note) { + this.note = note; } public TreeMap getDenominations() { + return denominations; } public boolean isGlobal() { + return (regions.containsKey("global") && regions.get("global").isEnabled()); } public boolean isGlobalDefault() { + if(isGlobal()) { return regions.get("global").isDefault(); } @@ -349,10 +405,12 @@ public boolean isGlobalDefault() { } public boolean regionEnabled(final String region) { - return isGlobal() || (regions.containsKey(region) && regions.get(region).isEnabled()); + + return isGlobal() || (regions.containsKey(region) && regions.get(region).isEnabled()); } public boolean isRegionDefault(final String region) { + if(regions.containsKey(region)) { return regions.get(region).isDefault(); } @@ -360,10 +418,12 @@ public boolean isRegionDefault(final String region) { } public Map getRegions() { + return regions; } public static Currency clone(final Currency original, final boolean item) { + Currency cloned = (item)? new ItemCurrency(original.identifier) : new Currency(original.identifier); cloned.file = original.file; @@ -405,7 +465,7 @@ public static Currency clone(final Currency original, final boolean item) { } cloned.conversion.putAll(original.conversion); - original.regions.forEach((key, value) -> cloned.regions.put(key, new CurrencyRegion(value.region(), value.isEnabled(), value.isDefault()))); + original.regions.forEach((key, value)->cloned.regions.put(key, new CurrencyRegion(value.region(), value.isEnabled(), value.isDefault()))); return cloned; } diff --git a/Core/src/net/tnemc/core/currency/CurrencyLoader.java b/Core/src/net/tnemc/core/currency/CurrencyLoader.java index 55eb70a2..c978ef5b 100644 --- a/Core/src/net/tnemc/core/currency/CurrencyLoader.java +++ b/Core/src/net/tnemc/core/currency/CurrencyLoader.java @@ -25,37 +25,42 @@ /** * Used to load currencies. * - * @see Currency * @author creatorfromhell + * @see Currency * @since 0.1.2.0 */ public interface CurrencyLoader { /** * Loads all currencies. + * * @param directory The directory to load the currencies from. + * * @throws NoValidCurrenciesException When no valid currencies can be loaded. */ void loadCurrencies(final File directory) throws NoValidCurrenciesException; /** * Loads a specific currency. + * * @param directory The directory to load the currency from. - * @param name The name of the currency to load. + * @param name The name of the currency to load. */ boolean loadCurrency(final File directory, final String name); /** * Loads a specific currency. - * @param directory The directory to load the currency from. + * + * @param directory The directory to load the currency from. * @param curDirectory The file of the currency */ boolean loadCurrency(final File directory, final File curDirectory); /** * Loads all denominations for a currency. + * * @param directory The directory to load the denominations from. - * @param currency The currency of the denomination. + * @param currency The currency of the denomination. */ boolean loadDenominations(final File directory, Currency currency); @@ -63,15 +68,15 @@ public interface CurrencyLoader { * Loads all denominations for a currency. * * @param directory The directory to load the denomination from. - * @param currency The currency of the denomination. - * @param name The name of the denomination to load. + * @param currency The currency of the denomination. + * @param name The name of the denomination to load. */ boolean loadDenomination(final File directory, Currency currency, final String name); /** * Loads all denominations for a currency. * - * @param currency The currency of the denomination. + * @param currency The currency of the denomination. * @param denomFile The file of the denomination to load. */ boolean loadDenomination(Currency currency, final File denomFile); diff --git a/Core/src/net/tnemc/core/currency/CurrencyRegion.java b/Core/src/net/tnemc/core/currency/CurrencyRegion.java index dfb80f58..4bc03f09 100644 --- a/Core/src/net/tnemc/core/currency/CurrencyRegion.java +++ b/Core/src/net/tnemc/core/currency/CurrencyRegion.java @@ -31,20 +31,24 @@ public class CurrencyRegion { private final boolean regionDefault; public CurrencyRegion(String region, boolean enabled, boolean regionDefault) { + this.region = region; this.enabled = enabled; this.regionDefault = regionDefault; } public String region() { + return region; } public boolean isEnabled() { + return enabled; } public boolean isDefault() { + return regionDefault; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/currency/CurrencySaver.java b/Core/src/net/tnemc/core/currency/CurrencySaver.java index cbd433be..361ec4d4 100644 --- a/Core/src/net/tnemc/core/currency/CurrencySaver.java +++ b/Core/src/net/tnemc/core/currency/CurrencySaver.java @@ -28,40 +28,45 @@ /** * Used to load currencies. * - * @see Currency * @author creatorfromhell + * @see Currency * @since 0.1.2.0 */ public interface CurrencySaver { /** * Saves all currencies. + * * @param directory The directory used for saving. */ void saveCurrencies(final File directory); /** * Saves all currency UUIDs only. + * * @param directory The directory used for saving. */ void saveCurrenciesUUID(final File directory); /** * Saves a specific currency + * * @param directory The directory used for saving. - * @param currency The currency to save. + * @param currency The currency to save. */ void saveCurrency(final File directory, Currency currency); /** * Saves a specific currency denomination - * @param directory The directory used for saving. - * @param currency The currency of the denomination. + * + * @param directory The directory used for saving. + * @param currency The currency of the denomination. * @param denomination The denomination to save. */ void saveDenomination(final File directory, Currency currency, Denomination denomination); default void backupCurrency(final File directory) { + try { final File currencyBackupFolder = new File(PluginCore.directory(), "currency-backups"); currencyBackupFolder.mkdir(); @@ -71,7 +76,7 @@ default void backupCurrency(final File directory) { zipFolder(directory, zipFilePath); PluginCore.log().inform("Currency folder backed up to: " + currencyBackupFolder.getPath()); - } catch (IOException e) { + } catch(IOException e) { e.printStackTrace(); } } diff --git a/Core/src/net/tnemc/core/currency/CurrencyType.java b/Core/src/net/tnemc/core/currency/CurrencyType.java index 22594c74..127d4823 100644 --- a/Core/src/net/tnemc/core/currency/CurrencyType.java +++ b/Core/src/net/tnemc/core/currency/CurrencyType.java @@ -36,8 +36,8 @@ /** * Represents a type of currency. * - * @see Currency * @author creatorfromhell + * @see Currency * @since 0.1.2.0 */ public interface CurrencyType { @@ -53,6 +53,7 @@ public interface CurrencyType { * @return True if this currency type supports offline players, otherwise false. */ default boolean offline() { + return true; } @@ -61,6 +62,7 @@ default boolean offline() { * should be true for currency types like item currency. */ default boolean loginCalculation() { + return false; } @@ -69,10 +71,12 @@ default boolean loginCalculation() { * your own data handling. */ default boolean database() { + return true; } default boolean supportsVirtual() { + return true; } @@ -80,6 +84,7 @@ default boolean supportsVirtual() { * @return True if this currency type is based on physical items. */ default boolean supportsItems() { + return (this instanceof ItemType); } @@ -87,6 +92,7 @@ default boolean supportsItems() { * @return The {@link Identifier} of the default handler. */ default Identifier defaultHandler() { + return VIRTUAL; } @@ -95,17 +101,19 @@ default Identifier defaultHandler() { * from items to/from virtual. */ default boolean supportsExchange() { + return false; } /** * Used to get the holdings for a specific account from this currency type. * - * @param account The uuid of the account. - * @param region The name of the region involved. This is usually a world, but could be something - * else such as a world guard region name/identifier. + * @param account The uuid of the account. + * @param region The name of the region involved. This is usually a world, but could be + * something else such as a world guard region name/identifier. * @param currency The instance of the currency to use. - * @param type The {@link Identifier} of the holdings handler to use. + * @param type The {@link Identifier} of the holdings handler to use. + * * @return The holdings for the specific account. */ default List getHoldings(Account account, String region, Currency currency, Identifier type) { @@ -120,7 +128,7 @@ default List getHoldings(Account account, String region, Currency } else if(type.equals(EconomyManager.ITEM_ONLY)) { final Optional curType = EconomyManager.instance().currency().findType("item"); - curType.ifPresent(currencyType -> handlers.addAll(EconomyManager.instance().getFor(account, currencyType))); + curType.ifPresent(currencyType->handlers.addAll(EconomyManager.instance().getFor(account, currencyType))); } else { @@ -137,12 +145,12 @@ default List getHoldings(Account account, String region, Currency /** * Used to set the holdings for a specific account. * - * @param account The uuid of the account. - * @param region The name of the region involved. This is usually a world, but could be something - * else such as a world guard region name/identifier. + * @param account The uuid of the account. + * @param region The name of the region involved. This is usually a world, but could be + * something else such as a world guard region name/identifier. * @param currency The instance of the currency to use. - * @param type The {@link Identifier} of the holdings handler to use. - * @param amount The amount to set the player's holdings to. + * @param type The {@link Identifier} of the holdings handler to use. + * @param amount The amount to set the player's holdings to. * * @return True if the holdings have been set, otherwise false. */ @@ -173,6 +181,7 @@ default boolean setHoldings(Account account, String region, Currency currency, I } default void addDatabase(Account account, String region, Currency currency, Identifier type, BigDecimal amount) { + final HoldingsEntry entry = new HoldingsEntry(region, currency.getUid(), amount, type); account.getWallet().setHoldings(entry); diff --git a/Core/src/net/tnemc/core/currency/Denomination.java b/Core/src/net/tnemc/core/currency/Denomination.java index 62b64b4f..348f737d 100644 --- a/Core/src/net/tnemc/core/currency/Denomination.java +++ b/Core/src/net/tnemc/core/currency/Denomination.java @@ -26,8 +26,8 @@ /** * Represents a denomination for an {@link Currency currency}. * - * @see Currency * @author creatorfromhell + * @see Currency * @since 0.1.2.0 */ public class Denomination { @@ -37,12 +37,14 @@ public class Denomination { private BigDecimal weight; public Denomination(BigDecimal weight) { + this.weight = weight; this.single = "Singular"; this.plural = "Plural"; } public static Denomination clone(final Denomination original, boolean item) { + Denomination cloned = (item)? new ItemDenomination(original.weight()) : new Denomination(original.weight()); cloned.setSingle(original.singular()); @@ -65,30 +67,37 @@ public static Denomination clone(final Denomination original, boolean item) { } public boolean isItem() { + return (this instanceof ItemDenomination); } public void setSingle(String single) { + this.single = single; } public void setPlural(String plural) { + this.plural = plural; } public String singular() { + return single; } public String plural() { + return plural; } public BigDecimal weight() { + return weight; } public void setWeight(BigDecimal weight) { + this.weight = weight; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/currency/Note.java b/Core/src/net/tnemc/core/currency/Note.java index b2fb3a53..99bda4ac 100644 --- a/Core/src/net/tnemc/core/currency/Note.java +++ b/Core/src/net/tnemc/core/currency/Note.java @@ -33,8 +33,8 @@ * Represents a currency note object, which is a way to make virtual balances into a physical note * to be traded or stored in a chest. * - * @since 0.1.2.0 * @author creatorfromhell + * @since 0.1.2.0 */ public class Note { @@ -50,6 +50,7 @@ public class Note { final TaxEntry fee; public Note(String material, BigDecimal minimum, String fee) { + this.material = material; this.minimum = minimum; @@ -61,28 +62,34 @@ public Note(String material, BigDecimal minimum, String fee) { } public Note(String material, BigDecimal minimum, TaxEntry fee) { + this.material = material; this.minimum = minimum; this.fee = fee; } public BigDecimal getMinimum() { + return minimum; } public void setMinimum(BigDecimal minimum) { + this.minimum = minimum; } public TaxEntry getFee() { + return fee; } public List getFlags() { + return flags; } public void setFlags(List flags) { + this.flags.clear(); for(String str : flags) { if(!str.isEmpty()) { @@ -92,10 +99,12 @@ public void setFlags(List flags) { } public List getEnchantments() { + return enchantments; } public void setEnchantments(List enchantments) { + this.enchantments.clear(); for(String str : enchantments) { if(!str.isEmpty()) { @@ -105,30 +114,37 @@ public void setEnchantments(List enchantments) { } public String getMaterial() { + return material; } public void setMaterial(String material) { + this.material = material; } public int getCustomModelData() { + return customModelData; } public void setCustomModelData(int customModelData) { + this.customModelData = customModelData; } public String getTexture() { + return texture; } public void setTexture(String texture) { + this.texture = texture; } public AbstractItemStack stack(final String currency, final String region, final BigDecimal amount) { + final LinkedList lore = new LinkedList<>(); lore.add(Component.text(MessageConfig.yaml().getString("Messages.Note.Currency").replace("$currency", currency))); lore.add(Component.text(MessageConfig.yaml().getString("Messages.Note.Region").replace("$region", region))); @@ -136,10 +152,10 @@ public AbstractItemStack stack(final String currency, final String regio lore.add(Component.text(MessageConfig.yaml().getString("Messages.Note.Action"))); return (AbstractItemStack)PluginCore.server().stackBuilder().of(material, 1) - .display(Component.text(MessageConfig.yaml().getString("Messages.Note.Name"))) - .enchant(enchantments) - .flags(flags) - .modelData(customModelData) - .lore(lore); + .display(Component.text(MessageConfig.yaml().getString("Messages.Note.Name"))) + .enchant(enchantments) + .flags(flags) + .modelData(customModelData) + .lore(lore); } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/currency/calculations/CalculationData.java b/Core/src/net/tnemc/core/currency/calculations/CalculationData.java index 56809b80..96b12b2b 100644 --- a/Core/src/net/tnemc/core/currency/calculations/CalculationData.java +++ b/Core/src/net/tnemc/core/currency/calculations/CalculationData.java @@ -39,8 +39,9 @@ import java.util.UUID; /** - * CalculationData is used to take the information for an {@link net.tnemc.core.currency.item.ItemCurrency} - * and break it down in order to perform Item-based calculations. + * CalculationData is used to take the information for an + * {@link net.tnemc.core.currency.item.ItemCurrency} and break it down in order to perform + * Item-based calculations. * * @author creatorfromhell * @since 0.1.2.0 @@ -59,6 +60,7 @@ public class CalculationData { private boolean failedDrop = false; public CalculationData(final ItemCurrency currency, I inventory, final UUID player) { + this.currency = currency; this.inventory = inventory; this.player = player; @@ -67,22 +69,27 @@ public CalculationData(final ItemCurrency currency, I inventory, final UUID play } public Map getInventoryMaterials() { + return inventoryMaterials; } public TreeMap getDenominations() { + return currency.getDenominations(); } public MonetaryCalculation getCalculator() { + return calculator; } public ItemCurrency getCurrency() { + return currency; } public void inventoryCounts() { + for(Map.Entry entry : currency.getDenominations().entrySet()) { if(entry.getValue() instanceof final ItemDenomination denomination) { @@ -116,6 +123,7 @@ public void removeMaterials(Denomination denomination, Integer amount) { } public void provideMaterials(final Denomination denomination, Integer amount) { + int contains = (inventoryMaterials.getOrDefault(denomination.weight(), amount)); final AbstractItemStack stack = TNECore.instance().denominationToStack((ItemDenomination)denomination).amount(amount); @@ -152,6 +160,7 @@ public void provideMaterials(final Denomination denomination, Integer amount) { } public void drop(final Collection> toDrop, PlayerAccount account) { + final CurrencyDropCallback currencyDrop = new CurrencyDropCallback(player, currency, toDrop); if(PluginCore.callbacks().call(currencyDrop)) { PluginCore.log().error("Cancelled currency drop through callback.", DebugLevel.STANDARD); @@ -168,10 +177,12 @@ public void drop(final Collection> toDrop, PlayerAccou } public boolean isDropped() { + return dropped; } public boolean isFailedDrop() { + return failedDrop; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/currency/calculations/ItemCalculations.java b/Core/src/net/tnemc/core/currency/calculations/ItemCalculations.java index 71144503..4c7165d3 100644 --- a/Core/src/net/tnemc/core/currency/calculations/ItemCalculations.java +++ b/Core/src/net/tnemc/core/currency/calculations/ItemCalculations.java @@ -33,9 +33,11 @@ public class ItemCalculations { /** * Used to calculate the holdings of the inventory materials present. + * * @return The {@link BigDecimal} representation of the inventory materials balance value. */ public BigDecimal calculateHoldings(CalculationData data) { + BigDecimal holdings = BigDecimal.ZERO; for(Map.Entry entry : data.getDenominations().entrySet()) { @@ -49,6 +51,7 @@ public BigDecimal calculateHoldings(CalculationData data) { } public void setItems(CalculationData data, BigDecimal amount) { + final BigDecimal holdings = calculateHoldings(data); if(holdings.compareTo(amount) == 0) return; @@ -88,8 +91,8 @@ public BigDecimal calculation(CalculationData data, BigDecimal change) { } /** - * Used to exchange an amount to inventory items. This is mostly used for when a larger denomination - * needs to be broken into smaller denominations for calculation purposes. + * Used to exchange an amount to inventory items. This is mostly used for when a larger + * denomination needs to be broken into smaller denominations for calculation purposes. * * @param amount The amount that the items should add up to. */ @@ -107,10 +110,12 @@ public void provideMaterials(CalculationData data, BigDecimal amount) { /** * Used to remove tiers from the {@link CalculationData} being worked with. - * @param denom The denom name in String form. + * + * @param denom The denom name in String form. * @param amount The amount of the material to remove from working materials. */ public void removeMaterials(CalculationData data, Denomination denom, Integer amount) { + data.removeMaterials(denom, amount); } } diff --git a/Core/src/net/tnemc/core/currency/calculations/MonetaryCalculation.java b/Core/src/net/tnemc/core/currency/calculations/MonetaryCalculation.java index 578baa3c..4023bf4b 100644 --- a/Core/src/net/tnemc/core/currency/calculations/MonetaryCalculation.java +++ b/Core/src/net/tnemc/core/currency/calculations/MonetaryCalculation.java @@ -48,6 +48,7 @@ public class MonetaryCalculation { int attempt = 1; public void initialize(Currency currency, Map inventoryMaterials) { + reset(); denominationTypes.addAll(currency.getDenominations().keySet()); @@ -55,6 +56,7 @@ public void initialize(Currency currency, Map inventoryMate } private void reset() { + attempt = 1; denominationTypes.clear(); inventoryMaterials.clear(); @@ -64,13 +66,14 @@ private void reset() { /** * Calculates the amount of denominations needed to pay for a given amount. This method has the - * possibility of running twice. After the first attempt, if the amount can't be paid for then - * it will break down a larger denomination and sort through everything after the change is added + * possibility of running twice. After the first attempt, if the amount can't be paid for then it + * will break down a larger denomination and sort through everything after the change is added * into the mix. * * @param amount The amount to attempt to pay for. */ public void calculateDenominationCounts(BigDecimal amount) { + Map result = new HashMap<>(); BigDecimal workingAmount = amount; @@ -81,14 +84,14 @@ public void calculateDenominationCounts(BigDecimal amount) { final SortedMap lowerThanAmount = counts.headMap(amount, true); // Iterate over denominations in descending order - for (Map.Entry entry : new TreeMap<>(lowerThanAmount).descendingMap().entrySet()) { + for(Map.Entry entry : new TreeMap<>(lowerThanAmount).descendingMap().entrySet()) { final BigDecimal denomination = entry.getKey(); // Calculate the maximum number of this denomination that can be used int maxCount = lowerThanAmount.get(denomination); int count = workingAmount.divide(denomination, 0, RoundingMode.DOWN).intValue(); - if (count > maxCount) { + if(count > maxCount) { count = maxCount; } @@ -104,7 +107,7 @@ public void calculateDenominationCounts(BigDecimal amount) { PluginCore.log().debug("Working 2: " + workingAmount.toPlainString(), DebugLevel.DEVELOPER); // Update the result map - if (count > 0) { + if(count > 0) { result.put(denomination, count); } @@ -120,7 +123,7 @@ public void calculateDenominationCounts(BigDecimal amount) { PluginCore.log().debug("Calculate comparison:" + workingAmount.compareTo(BigDecimal.ZERO), DebugLevel.DEVELOPER); // If there is any amount left over, it was not possible to pay for the full amount - if (workingAmount.compareTo(BigDecimal.ZERO) > 0) { + if(workingAmount.compareTo(BigDecimal.ZERO) > 0) { if(attempt <= 1) { @@ -143,6 +146,7 @@ public void calculateDenominationCounts(BigDecimal amount) { public Map calculateBreakdowns(BigDecimal amount) { + PluginCore.log().debug("calculateBreakdowns Amount:" + amount.toPlainString(), DebugLevel.DEVELOPER); @@ -173,13 +177,13 @@ public Map calculateBreakdowns(BigDecimal amount) { } /** - * Calculates the number of each denomination required to make up a given - * monetary amount, using a currency's denomination values. + * Calculates the number of each denomination required to make up a given monetary amount, using a + * currency's denomination values. * * @param amount the monetary amount to break down into denominations * - * @return a map of BigDecimal denominations and the number of each - * denomination required to make up the amount + * @return a map of BigDecimal denominations and the number of each denomination required to make + * up the amount */ public Map breakdown(BigDecimal amount) { @@ -210,8 +214,8 @@ public Map breakdown(BigDecimal amount) { } /** - * Combines two maps of BigDecimal keys and Integer values, adding the values - * of matching keys and adding new key-value pairs as necessary. + * Combines two maps of BigDecimal keys and Integer values, adding the values of matching keys and + * adding new key-value pairs as necessary. * * @param exist the map to add values to * @param toAdd the map containing the values to add @@ -237,10 +241,12 @@ private void combineMaps(Map exist, Map getToAdd() { + return toAdd; } public TreeMap getToRemove() { + return toRemove; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/currency/format/CurrencyFormatter.java b/Core/src/net/tnemc/core/currency/format/CurrencyFormatter.java index 2d612080..8383a72c 100644 --- a/Core/src/net/tnemc/core/currency/format/CurrencyFormatter.java +++ b/Core/src/net/tnemc/core/currency/format/CurrencyFormatter.java @@ -66,14 +66,17 @@ public class CurrencyFormatter { } public static void addRule(FormatRule rule) { + rulesMap.put(rule.name(), rule); } public static String format(@Nullable Account account, final BigDecimal amount) { + return format(account, new HoldingsEntry(PluginCore.server().defaultWorld(), TNECore.eco().currency().getDefaultCurrency().getUid(), amount, EconomyManager.NORMAL)); } public static String format(@Nullable Account account, HoldingsEntry entry) { + String format = ""; final Optional currency = TNECore.eco().currency().findCurrency(entry.getCurrency()); @@ -90,6 +93,7 @@ public static String format(@Nullable Account account, HoldingsEntry entry) { } public static LinkedHashMap rules() { + return rulesMap; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/currency/format/FormatRule.java b/Core/src/net/tnemc/core/currency/format/FormatRule.java index b033cb12..67876ee1 100644 --- a/Core/src/net/tnemc/core/currency/format/FormatRule.java +++ b/Core/src/net/tnemc/core/currency/format/FormatRule.java @@ -32,6 +32,7 @@ public interface FormatRule { /** * The identifier for this rule. + * * @return The human-friendly identifier for this rule. */ String name(); @@ -42,24 +43,28 @@ public interface FormatRule { * @return The description of the format rule as a String. */ default String description() { + return ""; } /** - * Determines whether this format rule should be included in the menu. - * By default, it is set to true. + * Determines whether this format rule should be included in the menu. By default, it is set to + * true. * * @return true if this format rule should be included in the menu, false otherwise. */ default boolean includeInMenu() { + return true; } /** * Used to format a TNE format string based on the provided holdings and account information. + * * @param account The account to use for this formatting. - * @param entry The holdings entry to use for formatting. - * @param format The format string that these should be provided for. + * @param entry The holdings entry to use for formatting. + * @param format The format string that these should be provided for. + * * @return The formatted string. */ String format(@Nullable Account account, HoldingsEntry entry, String format); diff --git a/Core/src/net/tnemc/core/currency/format/impl/DecimalRule.java b/Core/src/net/tnemc/core/currency/format/impl/DecimalRule.java index 844a410b..7d627354 100644 --- a/Core/src/net/tnemc/core/currency/format/impl/DecimalRule.java +++ b/Core/src/net/tnemc/core/currency/format/impl/DecimalRule.java @@ -24,13 +24,16 @@ import org.jetbrains.annotations.Nullable; public class DecimalRule implements FormatRule { + @Override public String name() { + return ""; } @Override public String format(@Nullable Account account, HoldingsEntry entry, String format) { + if(entry.currency().isPresent()) { if(entry.asMonetary().scale() == 0) { return format.replace("", ""); diff --git a/Core/src/net/tnemc/core/currency/format/impl/MajorAmountRule.java b/Core/src/net/tnemc/core/currency/format/impl/MajorAmountRule.java index 8377e519..c71b9821 100644 --- a/Core/src/net/tnemc/core/currency/format/impl/MajorAmountRule.java +++ b/Core/src/net/tnemc/core/currency/format/impl/MajorAmountRule.java @@ -27,8 +27,10 @@ import java.util.Locale; public class MajorAmountRule implements FormatRule { + @Override public String name() { + return ""; } @@ -44,7 +46,7 @@ public String format(@Nullable Account account, HoldingsEntry entry, String form "%,d", monetary.major()).replace(",", entry.currency() - .get().getMajorSeparator()); + .get().getMajorSeparator()); } return format.replace("", replacement); } diff --git a/Core/src/net/tnemc/core/currency/format/impl/MajorNameRule.java b/Core/src/net/tnemc/core/currency/format/impl/MajorNameRule.java index 951bb01b..f92a77a7 100644 --- a/Core/src/net/tnemc/core/currency/format/impl/MajorNameRule.java +++ b/Core/src/net/tnemc/core/currency/format/impl/MajorNameRule.java @@ -29,8 +29,10 @@ import java.util.Optional; public class MajorNameRule implements FormatRule { + @Override public String name() { + return ""; } @@ -42,7 +44,7 @@ public String format(@Nullable Account account, HoldingsEntry entry, String form final Optional currency = entry.currency(); return currency.map(value->format.replace("", ((monetary.major().compareTo(BigInteger.ONE) == 0)? - value.getDisplay() : - value.getDisplayPlural()))).orElse(format); + value.getDisplay() : + value.getDisplayPlural()))).orElse(format); } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/currency/format/impl/MajorRule.java b/Core/src/net/tnemc/core/currency/format/impl/MajorRule.java index 7f293160..634644d2 100644 --- a/Core/src/net/tnemc/core/currency/format/impl/MajorRule.java +++ b/Core/src/net/tnemc/core/currency/format/impl/MajorRule.java @@ -28,19 +28,22 @@ import java.util.Optional; public class MajorRule implements FormatRule { + @Override public String name() { + return ""; } @Override public String format(@Nullable Account account, HoldingsEntry entry, String format) { + final BigInteger major = entry.asMonetary().major(); final Optional currency = entry.currency(); return currency.map(value->format.replace("", major.toString() - + " " + ((major.compareTo(BigInteger.ONE) == 0)? - value.getDisplay() : - value.getDisplayPlural()))).orElse(format); + + " " + ((major.compareTo(BigInteger.ONE) == 0)? + value.getDisplay() : + value.getDisplayPlural()))).orElse(format); } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/currency/format/impl/MaterialRule.java b/Core/src/net/tnemc/core/currency/format/impl/MaterialRule.java index f1a4aef1..a4c76922 100644 --- a/Core/src/net/tnemc/core/currency/format/impl/MaterialRule.java +++ b/Core/src/net/tnemc/core/currency/format/impl/MaterialRule.java @@ -35,8 +35,10 @@ import java.util.Optional; public class MaterialRule implements FormatRule { + @Override public String name() { + return "material"; } @@ -48,11 +50,13 @@ public String name() { */ @Override public boolean includeInMenu() { + return false; } @Override public String format(@Nullable Account account, HoldingsEntry entry, String format) { + String formatted = format; diff --git a/Core/src/net/tnemc/core/currency/format/impl/MinorAmountRule.java b/Core/src/net/tnemc/core/currency/format/impl/MinorAmountRule.java index d54936bb..97b32a51 100644 --- a/Core/src/net/tnemc/core/currency/format/impl/MinorAmountRule.java +++ b/Core/src/net/tnemc/core/currency/format/impl/MinorAmountRule.java @@ -24,13 +24,16 @@ import org.jetbrains.annotations.Nullable; public class MinorAmountRule implements FormatRule { + @Override public String name() { + return ""; } @Override public String format(@Nullable Account account, HoldingsEntry entry, String format) { + if(entry.asMonetary().scale() == 0) { return format.replace("", ""); } diff --git a/Core/src/net/tnemc/core/currency/format/impl/MinorNameRule.java b/Core/src/net/tnemc/core/currency/format/impl/MinorNameRule.java index 0bac641e..97ba8c93 100644 --- a/Core/src/net/tnemc/core/currency/format/impl/MinorNameRule.java +++ b/Core/src/net/tnemc/core/currency/format/impl/MinorNameRule.java @@ -29,8 +29,10 @@ import java.util.Optional; public class MinorNameRule implements FormatRule { + @Override public String name() { + return ""; } @@ -53,7 +55,7 @@ public String format(@Nullable Account account, HoldingsEntry entry, String form final Optional currency = entry.currency(); return currency.map(value->format.replace("", (monetary.minorAsInt().compareTo(BigInteger.ONE) == 0)? - value.getDisplayMinor() : - value.getDisplayMinorPlural())).orElse(format); + value.getDisplayMinor() : + value.getDisplayMinorPlural())).orElse(format); } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/currency/format/impl/MinorRule.java b/Core/src/net/tnemc/core/currency/format/impl/MinorRule.java index 24cdec1b..51f3cce2 100644 --- a/Core/src/net/tnemc/core/currency/format/impl/MinorRule.java +++ b/Core/src/net/tnemc/core/currency/format/impl/MinorRule.java @@ -29,19 +29,22 @@ import java.util.Optional; public class MinorRule implements FormatRule { + @Override public String name() { + return ""; } @Override public String format(@Nullable Account account, HoldingsEntry entry, String format) { + final Monetary monetary = entry.asMonetary(); final Optional currency = entry.currency(); return currency.map(value->format.replace("", monetary.minor() - + " " + ((monetary.minorAsInt().compareTo(BigInteger.ONE) == 0)? - value.getDisplayMinor() : - value.getDisplayMinorPlural()))).orElse(format); + + " " + ((monetary.minorAsInt().compareTo(BigInteger.ONE) == 0)? + value.getDisplayMinor() : + value.getDisplayMinorPlural()))).orElse(format); } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/currency/format/impl/ShortenJRule.java b/Core/src/net/tnemc/core/currency/format/impl/ShortenJRule.java index 943e57af..23e69089 100644 --- a/Core/src/net/tnemc/core/currency/format/impl/ShortenJRule.java +++ b/Core/src/net/tnemc/core/currency/format/impl/ShortenJRule.java @@ -39,6 +39,7 @@ public class ShortenJRule implements FormatRule { @Override public String name() { + return ""; } @@ -53,6 +54,7 @@ public String name() { */ @Override public String format(@Nullable Account account, HoldingsEntry entry, String format) { + final Monetary monetary = entry.asMonetary(); if(format.contains("")) { @@ -79,6 +81,7 @@ public String format(@Nullable Account account, HoldingsEntry entry, String form } private String build(final Currency currency, String working, final StringBuilder builder) { + final int strLength = working.length() - 1; final int multiple = (strLength / 4) * 4; final int majorKeep = strLength % 4; diff --git a/Core/src/net/tnemc/core/currency/format/impl/ShortenRule.java b/Core/src/net/tnemc/core/currency/format/impl/ShortenRule.java index 794e13b4..cbbf8171 100644 --- a/Core/src/net/tnemc/core/currency/format/impl/ShortenRule.java +++ b/Core/src/net/tnemc/core/currency/format/impl/ShortenRule.java @@ -29,8 +29,10 @@ import java.util.Optional; public class ShortenRule implements FormatRule { + @Override public String name() { + return ""; } @@ -51,7 +53,7 @@ public String format(@Nullable Account account, HoldingsEntry entry, String form final String whole = monetary.major().toString(); final int pos = ((whole.length() - 1) / 3) - 1; - final int posInclude = ((whole.length() % 3) == 0) ? 3 : whole.length() % 3; + final int posInclude = ((whole.length() % 3) == 0)? 3 : whole.length() % 3; String wholeSub = whole.substring(0, posInclude); if(whole.length() > 3) { diff --git a/Core/src/net/tnemc/core/currency/format/impl/SymbolRule.java b/Core/src/net/tnemc/core/currency/format/impl/SymbolRule.java index 6ab8d111..c7f7be38 100644 --- a/Core/src/net/tnemc/core/currency/format/impl/SymbolRule.java +++ b/Core/src/net/tnemc/core/currency/format/impl/SymbolRule.java @@ -27,8 +27,10 @@ import java.util.Optional; public class SymbolRule implements FormatRule { + @Override public String name() { + return ""; } diff --git a/Core/src/net/tnemc/core/currency/item/ItemCurrency.java b/Core/src/net/tnemc/core/currency/item/ItemCurrency.java index a0b374b5..19569e0a 100644 --- a/Core/src/net/tnemc/core/currency/item/ItemCurrency.java +++ b/Core/src/net/tnemc/core/currency/item/ItemCurrency.java @@ -26,8 +26,8 @@ /** * Represents a {@link Currency currency} that is represented by physical items in game. * - * @see Currency * @author creatorfromhell + * @see Currency * @since 0.1.2.0 */ public class ItemCurrency extends Currency { @@ -37,6 +37,7 @@ public class ItemCurrency extends Currency { protected boolean importItem; public ItemCurrency(String identifier) { + super(identifier); this.enderChest = true; @@ -45,6 +46,7 @@ public ItemCurrency(String identifier) { } public Optional getDenominationByMaterial(final String material) { + for(Denomination denom : getDenominations().values()) { final ItemDenomination item = (ItemDenomination)denom; @@ -56,26 +58,32 @@ public Optional getDenominationByMaterial(final String materia } public boolean canEnderChest() { + return enderChest; } public void setEnderChest(boolean enderChest) { + this.enderChest = enderChest; } public boolean isEnderFill() { + return enderFill; } public void setEnderFill(boolean enderFill) { + this.enderFill = enderFill; } public boolean isImportItem() { + return importItem; } public void setImportItem(boolean importItem) { + this.importItem = importItem; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/currency/item/ItemDenomination.java b/Core/src/net/tnemc/core/currency/item/ItemDenomination.java index c4d7a1c5..d152bdd8 100644 --- a/Core/src/net/tnemc/core/currency/item/ItemDenomination.java +++ b/Core/src/net/tnemc/core/currency/item/ItemDenomination.java @@ -30,8 +30,8 @@ /** * Represents a denomination for an {@link ItemCurrency currency}. * - * @see ItemCurrency * @author creatorfromhell + * @see ItemCurrency * @since 0.1.2.0 */ public class ItemDenomination extends Denomination { @@ -47,66 +47,81 @@ public class ItemDenomination extends Denomination { private String texture = ""; public ItemDenomination(BigDecimal weight, String material) { + this(weight, material, (short)0); } public ItemDenomination(BigDecimal weight, String material, short damage) { + super(weight); this.material = material; this.damage = damage; } public ItemDenomination(BigDecimal weight) { + super(weight); } public List getEnchantments() { + return enchantments; } public void setEnchantments(List enchantments) { + this.enchantments.clear(); this.enchantments.addAll(enchantments); } public List getFlags() { + return flags; } public void setFlags(List flags) { + this.flags.clear(); this.flags.addAll(flags); } public String getMaterial() { + return material; } public void setMaterial(String material) { + this.material = material; } public short getDamage() { + return damage; } public void setDamage(short damage) { + this.damage = damage; } public String getName() { + return name; } public void setName(String name) { + this.name = name; } public List getLore() { + return lore; } public LinkedList getLoreAsString() { + final LinkedList loreAsString = new LinkedList<>(); for(Component component : lore) { loreAsString.add(MiniMessage.miniMessage().serialize(component)); @@ -115,23 +130,28 @@ public LinkedList getLoreAsString() { } public void setLore(List lore) { + this.lore.clear(); this.lore.addAll(lore); } public int getCustomModel() { + return customModel; } public void setCustomModel(int customModel) { + this.customModel = customModel; } public String getTexture() { + return texture; } public void setTexture(String texture) { + this.texture = texture; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/currency/loader/DefaultCurrencyLoader.java b/Core/src/net/tnemc/core/currency/loader/DefaultCurrencyLoader.java index 8072ffcd..16bc47a0 100644 --- a/Core/src/net/tnemc/core/currency/loader/DefaultCurrencyLoader.java +++ b/Core/src/net/tnemc/core/currency/loader/DefaultCurrencyLoader.java @@ -62,7 +62,9 @@ public class DefaultCurrencyLoader implements CurrencyLoader { /** * Loads all currencies. + * * @param directory The directory to load the currencies from. + * * @throws NoValidCurrenciesException When no valid currencies can be loaded. */ @Override @@ -91,17 +93,18 @@ public void loadCurrencies(final File directory) throws NoValidCurrenciesExcepti * Loads a specific currency. * * @param directory The directory to load the currency from. - * @param name The name of the currency to load. + * @param name The name of the currency to load. */ @Override public boolean loadCurrency(final File directory, String name) { + return loadCurrency(directory, new File(directory, name + ".yml")); } /** * Loads a specific currency. * - * @param directory The directory to load the currency from. + * @param directory The directory to load the currency from. * @param curDirectory The file of the currency */ @Override @@ -281,8 +284,9 @@ public boolean loadCurrency(final File directory, File curDirectory) { /** * Loads all denominations for a currency. + * * @param directory The directory to load the denominations from. - * @param currency The currency of the denomination. + * @param currency The currency of the denomination. */ @Override public boolean loadDenominations(final File directory, Currency currency) { @@ -291,7 +295,7 @@ public boolean loadDenominations(final File directory, Currency currency) { final File[] denominations = IOUtil.getYAMLs(directory); if(denominations.length > 0) { - for (File denomination : denominations) { + for(File denomination : denominations) { final boolean loaded = loadDenomination(currency, denomination); @@ -312,22 +316,24 @@ public boolean loadDenominations(final File directory, Currency currency) { * Loads all denominations for a currency. * * @param directory The directory to load the denomination from. - * @param currency The currency of the denomination. - * @param name The name of the denomination to load. + * @param currency The currency of the denomination. + * @param name The name of the denomination to load. */ @Override public boolean loadDenomination(final File directory, Currency currency, String name) { + return loadDenomination(currency, new File(directory, name + ".yml")); } /** * Loads all denominations for a currency. * - * @param currency The currency of the denomination. + * @param currency The currency of the denomination. * @param denomFile The file of the denomination to load. */ @Override public boolean loadDenomination(Currency currency, File denomFile) { + YamlDocument denom = null; try { denom = YamlDocument.create(denomFile); @@ -349,7 +355,7 @@ public boolean loadDenomination(Currency currency, File denomFile) { final String material = denom.getString("Options.Material", "PAPER"); Denomination denomination = (currency instanceof ItemCurrency)? - new ItemDenomination(weight, material) : new Denomination(weight); + new ItemDenomination(weight, material) : new Denomination(weight); denomination.setSingle(single); denomination.setPlural(plural); diff --git a/Core/src/net/tnemc/core/currency/saver/DefaultCurrencySaver.java b/Core/src/net/tnemc/core/currency/saver/DefaultCurrencySaver.java index fd522fde..bc6dd87a 100644 --- a/Core/src/net/tnemc/core/currency/saver/DefaultCurrencySaver.java +++ b/Core/src/net/tnemc/core/currency/saver/DefaultCurrencySaver.java @@ -47,6 +47,7 @@ public class DefaultCurrencySaver implements CurrencySaver { /** * Saves all currencies. + * * @param directory The directory used for saving. */ @Override @@ -64,6 +65,7 @@ public void saveCurrencies(final File directory) { */ @Override public void saveCurrenciesUUID(File directory) { + for(final Currency currency : TNECore.eco().currency().currencies()) { saveID(directory, currency); } @@ -73,7 +75,7 @@ public void saveCurrenciesUUID(File directory) { * Saves a specific currency * * @param directory The directory used for saving. - * @param currency The currency to save. + * @param currency The currency to save. */ @Override public void saveCurrency(final File directory, Currency currency) { @@ -293,12 +295,13 @@ public void saveID(final File directory, Currency currency) { /** * Saves a specific currency denomination * - * @param directory The directory used for saving. + * @param directory The directory used for saving. * @param currency The currency of the denomination. * @param denomination The denomination to save. */ @Override public void saveDenomination(final File directory, Currency currency, Denomination denomination) { + YamlDocument denom = null; try { diff --git a/Core/src/net/tnemc/core/currency/type/ExperienceLevelType.java b/Core/src/net/tnemc/core/currency/type/ExperienceLevelType.java index afb2e6c1..f3ba6925 100644 --- a/Core/src/net/tnemc/core/currency/type/ExperienceLevelType.java +++ b/Core/src/net/tnemc/core/currency/type/ExperienceLevelType.java @@ -29,26 +29,31 @@ * @since 0.1.2.0 */ public class ExperienceLevelType implements CurrencyType { + /** * @return The name of this currency type. Examples: Virtual, Item */ @Override public String name() { + return "experience-level"; } @Override public String description() { + return "A simple currency based on experience levels. Not the most accurate..."; } @Override public boolean supportsVirtual() { + return false; } @Override public Identifier defaultHandler() { + return EconomyManager.EXPERIENCE_LEVEL; } } diff --git a/Core/src/net/tnemc/core/currency/type/ExperienceType.java b/Core/src/net/tnemc/core/currency/type/ExperienceType.java index 6f6fc389..98f1eab3 100644 --- a/Core/src/net/tnemc/core/currency/type/ExperienceType.java +++ b/Core/src/net/tnemc/core/currency/type/ExperienceType.java @@ -29,26 +29,31 @@ * @since 0.1.2.0 */ public class ExperienceType implements CurrencyType { + /** * @return The name of this currency type. Examples: Virtual, Item */ @Override public String name() { + return "experience"; } @Override public String description() { + return "A simple currency based on experience. Not the most accurate..."; } @Override public boolean supportsVirtual() { + return false; } @Override public Identifier defaultHandler() { + return EconomyManager.EXPERIENCE; } } diff --git a/Core/src/net/tnemc/core/currency/type/ItemType.java b/Core/src/net/tnemc/core/currency/type/ItemType.java index 7d3d0c9a..5e63dd7d 100644 --- a/Core/src/net/tnemc/core/currency/type/ItemType.java +++ b/Core/src/net/tnemc/core/currency/type/ItemType.java @@ -34,16 +34,19 @@ * @since 0.1.2.0 */ public class ItemType extends VirtualType { + /** * @return The name of this currency type. Examples: Virtual, Item */ @Override public String name() { + return "item"; } @Override public String description() { + return "A currency based solely on physical items."; } @@ -52,16 +55,19 @@ public String description() { */ @Override public boolean supportsItems() { + return true; } @Override public boolean supportsVirtual() { + return false; } @Override public Identifier defaultHandler() { + return INVENTORY_ONLY; } @@ -69,16 +75,17 @@ public Identifier defaultHandler() { * Used to set the holdings for a specific account. * * @param account The Account to set the holdings for. - * @param region The name of the region involved. This is usually a world, but could be something - * else such as a world guard region name/identifier. + * @param region The name of the region involved. This is usually a world, but could be + * something else such as a world guard region name/identifier. * @param currency The instance of the currency to use. - * @param type The {@link Identifier} of the holdings handler to use. + * @param type The {@link Identifier} of the holdings handler to use. * @param amount The amount to set the player's holdings to. * * @return True if the holdings have been set, otherwise false. */ @Override public boolean setHoldings(Account account, String region, Currency currency, Identifier type, BigDecimal amount) { + if(type.equals(EconomyManager.NORMAL)) type = INVENTORY_ONLY; return super.setHoldings(account, region, currency, type, amount); diff --git a/Core/src/net/tnemc/core/currency/type/MixedType.java b/Core/src/net/tnemc/core/currency/type/MixedType.java index 8b43a54d..b3844bbd 100644 --- a/Core/src/net/tnemc/core/currency/type/MixedType.java +++ b/Core/src/net/tnemc/core/currency/type/MixedType.java @@ -32,21 +32,25 @@ * @since 0.1.2.0 */ public class MixedType extends ItemType { + /** * @return The name of this currency type. Examples: Virtual, Item */ @Override public String name() { + return "mixed"; } @Override public String description() { + return "A currency that is a mixture of item and virtual types."; } @Override public boolean supportsVirtual() { + return true; } @@ -56,6 +60,7 @@ public boolean supportsVirtual() { */ @Override public boolean supportsExchange() { + return true; } @@ -63,10 +68,10 @@ public boolean supportsExchange() { * Used to set the holdings for a specific account. * * @param account The Account to set the holdings for. - * @param region The name of the region involved. This is usually a world, but could be something - * else such as a world guard region name/identifier. + * @param region The name of the region involved. This is usually a world, but could be + * something else such as a world guard region name/identifier. * @param currency The instance of the currency to use. - * @param type The {@link Identifier} of the holdings handler to use. + * @param type The {@link Identifier} of the holdings handler to use. * @param amount The amount to set the player's holdings to. * * @return True if the holdings have been set, otherwise false. diff --git a/Core/src/net/tnemc/core/currency/type/VirtualType.java b/Core/src/net/tnemc/core/currency/type/VirtualType.java index ded5ed55..100a1b88 100644 --- a/Core/src/net/tnemc/core/currency/type/VirtualType.java +++ b/Core/src/net/tnemc/core/currency/type/VirtualType.java @@ -34,24 +34,28 @@ * @since 0.1.2.0 */ public class VirtualType implements CurrencyType { + /** * @return The name of this currency type. Examples: Virtual, Item */ @Override public String name() { + return "virtual"; } @Override public String description() { + return "A simple currency type that is strictly virtual, which is imaginary money used in commands."; } protected HoldingsEntry virtual(Account account, String region, Currency currency) { + final Optional holdings = account.getWallet().getHoldings(region, currency.getUid(), EconomyManager.VIRTUAL - ); + ); if(holdings.isPresent()) { diff --git a/Core/src/net/tnemc/core/handlers/entity/EntityDropItemHandler.java b/Core/src/net/tnemc/core/handlers/entity/EntityDropItemHandler.java index 362b841e..f6c5b611 100644 --- a/Core/src/net/tnemc/core/handlers/entity/EntityDropItemHandler.java +++ b/Core/src/net/tnemc/core/handlers/entity/EntityDropItemHandler.java @@ -34,7 +34,7 @@ public HandlerResponse handle(final String material) { //This only matters if the config is enabled. if(MainConfig.yaml().getBoolean("Core.Server.MobDrop") && - TNECore.eco().currency().findCurrencyByMaterial(material).isPresent()) { + TNECore.eco().currency().findCurrencyByMaterial(material).isPresent()) { return new HandlerResponse("Can't do that starfox.", true); } diff --git a/Core/src/net/tnemc/core/handlers/player/PlayerCloseEChestHandler.java b/Core/src/net/tnemc/core/handlers/player/PlayerCloseEChestHandler.java index 552a658c..afbe320c 100644 --- a/Core/src/net/tnemc/core/handlers/player/PlayerCloseEChestHandler.java +++ b/Core/src/net/tnemc/core/handlers/player/PlayerCloseEChestHandler.java @@ -32,14 +32,17 @@ /** * Represents an event where a player is closing an ender chest. * - * @since 0.1.2 * @author creatorfromhell + * @since 0.1.2 */ public class PlayerCloseEChestHandler { /** - * Used to handle a Player closing an ender chest using the specified {@link PlayerProvider} class. + * Used to handle a Player closing an ender chest using the specified {@link PlayerProvider} + * class. + * * @param provider The {@link PlayerProvider} associated with the platform event. + * * @return True if the event should be cancelled, otherwise false. */ public HandlerResponse handle(PlayerProvider provider) { diff --git a/Core/src/net/tnemc/core/handlers/player/PlayerInteractHandler.java b/Core/src/net/tnemc/core/handlers/player/PlayerInteractHandler.java index 3dd0403d..84eeb735 100644 --- a/Core/src/net/tnemc/core/handlers/player/PlayerInteractHandler.java +++ b/Core/src/net/tnemc/core/handlers/player/PlayerInteractHandler.java @@ -50,15 +50,18 @@ public class PlayerInteractHandler { /** * Used to handle a PlayerInteractEvent using the specified {@link PlayerProvider} class. + * * @param provider The {@link PlayerProvider} associated with the platform event. + * * @return True if the event should be cancelled, otherwise false. */ public HandlerResponse handle(PlayerProvider provider, final AbstractItemStack item) { + final HandlerResponse response = new HandlerResponse("", false); final Optional account = TNECore.eco().account().findAccount(provider.identifier()); if(account.isPresent() && (account.get() instanceof PlayerAccount) && item.display() != null - && Component.EQUALS.test(item.display(), Component.text(MessageConfig.yaml().getString("Messages.Note.Name")))) { + && Component.EQUALS.test(item.display(), Component.text(MessageConfig.yaml().getString("Messages.Note.Name")))) { String currency = null; String region = null; @@ -96,9 +99,9 @@ public HandlerResponse handle(PlayerProvider provider, final AbstractItemStack acc = (apiResponse == null)? account : - apiResponse.getAccount(); + apiResponse.getAccount(); final UUID id = provider.identifier(); if(acc.isPresent()) { @@ -120,9 +123,9 @@ public HandlerResponse handle(PlayerProvider provider) { if(firstJoin) { acc.get().setHoldings(new HoldingsEntry(region, - currency.getUid(), - currency.getStartingHoldings(), - EconomyManager.NORMAL + currency.getUid(), + currency.getStartingHoldings(), + EconomyManager.NORMAL )); } } @@ -148,9 +151,9 @@ public HandlerResponse handle(PlayerProvider provider) { TNECore.eco().account().getImporting().remove(id); } else { acc.get().setHoldings(new HoldingsEntry(region, - currency.getUid(), - currency.getStartingHoldings(), - EconomyManager.NORMAL + currency.getUid(), + currency.getStartingHoldings(), + EconomyManager.NORMAL )); } } else { diff --git a/Core/src/net/tnemc/core/handlers/player/PlayerLeaveHandler.java b/Core/src/net/tnemc/core/handlers/player/PlayerLeaveHandler.java index c562c6d3..7830b20f 100644 --- a/Core/src/net/tnemc/core/handlers/player/PlayerLeaveHandler.java +++ b/Core/src/net/tnemc/core/handlers/player/PlayerLeaveHandler.java @@ -40,10 +40,13 @@ public class PlayerLeaveHandler { /** * Used to handle a PlayerLeaveEvent using the specified {@link PlayerProvider} class. + * * @param provider The {@link PlayerProvider} associated with the platform event. + * * @return True if the event should be cancelled, otherwise false. */ public HandlerResponse handle(PlayerProvider provider) { + final HandlerResponse response = new HandlerResponse("", false); final Optional account = TNECore.eco().account().findAccount(provider.identifier()); diff --git a/Core/src/net/tnemc/core/handlers/region/RegionLoadHandler.java b/Core/src/net/tnemc/core/handlers/region/RegionLoadHandler.java index 8433e4f7..7acc6677 100644 --- a/Core/src/net/tnemc/core/handlers/region/RegionLoadHandler.java +++ b/Core/src/net/tnemc/core/handlers/region/RegionLoadHandler.java @@ -32,6 +32,7 @@ public class RegionLoadHandler { public HandlerResponse handle(final String region, final RegionType type) { + TNECore.eco().region().initializeRegion(region, type); return new HandlerResponse("", false); diff --git a/Core/src/net/tnemc/core/handlers/server/ChannelHandler.java b/Core/src/net/tnemc/core/handlers/server/ChannelHandler.java index fab355a6..b1828e28 100644 --- a/Core/src/net/tnemc/core/handlers/server/ChannelHandler.java +++ b/Core/src/net/tnemc/core/handlers/server/ChannelHandler.java @@ -29,6 +29,7 @@ public class ChannelHandler { public void handler(final String channel, final byte[] bytes) { + if(channel.startsWith("tne:")) { PluginCore.instance().getChannelMessageManager().handle(channel, bytes); } diff --git a/Core/src/net/tnemc/core/hook/tnk/CampAccount.java b/Core/src/net/tnemc/core/hook/tnk/CampAccount.java index f8e39d00..552a56e2 100644 --- a/Core/src/net/tnemc/core/hook/tnk/CampAccount.java +++ b/Core/src/net/tnemc/core/hook/tnk/CampAccount.java @@ -31,6 +31,7 @@ public class CampAccount extends NonPlayerAccount { public CampAccount(UUID identifier, String name) { + super(identifier, name); //this.owner = Objects.requireNonNull(TownyAPI.getInstance().getNation(name)).getKing().getUUID(); } @@ -42,11 +43,13 @@ public CampAccount(UUID identifier, String name) { */ @Override public String type() { + return "camp"; } @Override public UUID generateIdentifier(String name) { + return super.generateIdentifier(name); } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/hook/tnk/CampCheck.java b/Core/src/net/tnemc/core/hook/tnk/CampCheck.java index eb2b6b78..ab831bf7 100644 --- a/Core/src/net/tnemc/core/hook/tnk/CampCheck.java +++ b/Core/src/net/tnemc/core/hook/tnk/CampCheck.java @@ -29,16 +29,18 @@ * @since 0.1.2.0 */ public class CampCheck implements AccountTypeCheck { + /** - * Returns our check function that should be used to check if a given String identifier, usually name, - * is valid for this account type. + * Returns our check function that should be used to check if a given String identifier, usually + * name, is valid for this account type. * * @return Our function that should be used to check if a given String identifier, usually name, * is valid for this account type. */ @Override public Function check() { - return value -> { + + return value->{ try { return value.contains("camp"); } catch(Exception e) { diff --git a/Core/src/net/tnemc/core/hook/tnk/KingdomAccount.java b/Core/src/net/tnemc/core/hook/tnk/KingdomAccount.java index 94bb83d0..3fd02c75 100644 --- a/Core/src/net/tnemc/core/hook/tnk/KingdomAccount.java +++ b/Core/src/net/tnemc/core/hook/tnk/KingdomAccount.java @@ -31,6 +31,7 @@ public class KingdomAccount extends NonPlayerAccount { public KingdomAccount(UUID identifier, String name) { + super(identifier, name); //this.owner = Objects.requireNonNull(TownyAPI.getInstance().getNation(name)).getKing().getUUID(); } @@ -42,11 +43,13 @@ public KingdomAccount(UUID identifier, String name) { */ @Override public String type() { + return "kingdom"; } @Override public UUID generateIdentifier(String name) { + return super.generateIdentifier(name); } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/hook/tnk/KingdomCheck.java b/Core/src/net/tnemc/core/hook/tnk/KingdomCheck.java index 01a2a30e..b0628975 100644 --- a/Core/src/net/tnemc/core/hook/tnk/KingdomCheck.java +++ b/Core/src/net/tnemc/core/hook/tnk/KingdomCheck.java @@ -29,16 +29,18 @@ * @since 0.1.2.0 */ public class KingdomCheck implements AccountTypeCheck { + /** - * Returns our check function that should be used to check if a given String identifier, usually name, - * is valid for this account type. + * Returns our check function that should be used to check if a given String identifier, usually + * name, is valid for this account type. * * @return Our function that should be used to check if a given String identifier, usually name, * is valid for this account type. */ @Override public Function check() { - return value -> { + + return value->{ try { return value.contains("kingdom"); } catch(Exception e) { diff --git a/Core/src/net/tnemc/core/hook/tnk/PactAccount.java b/Core/src/net/tnemc/core/hook/tnk/PactAccount.java index aed4b34a..3df1ee9c 100644 --- a/Core/src/net/tnemc/core/hook/tnk/PactAccount.java +++ b/Core/src/net/tnemc/core/hook/tnk/PactAccount.java @@ -31,6 +31,7 @@ public class PactAccount extends NonPlayerAccount { public PactAccount(UUID identifier, String name) { + super(identifier, name); //this.owner = Objects.requireNonNull(TownyAPI.getInstance().getNation(name)).getKing().getUUID(); } @@ -42,11 +43,13 @@ public PactAccount(UUID identifier, String name) { */ @Override public String type() { + return "pact"; } @Override public UUID generateIdentifier(String name) { + return super.generateIdentifier(name); } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/hook/tnk/PactCheck.java b/Core/src/net/tnemc/core/hook/tnk/PactCheck.java index c7208278..04cb242a 100644 --- a/Core/src/net/tnemc/core/hook/tnk/PactCheck.java +++ b/Core/src/net/tnemc/core/hook/tnk/PactCheck.java @@ -29,16 +29,18 @@ * @since 0.1.2.0 */ public class PactCheck implements AccountTypeCheck { + /** - * Returns our check function that should be used to check if a given String identifier, usually name, - * is valid for this account type. + * Returns our check function that should be used to check if a given String identifier, usually + * name, is valid for this account type. * * @return Our function that should be used to check if a given String identifier, usually name, * is valid for this account type. */ @Override public Function check() { - return value -> { + + return value->{ try { return value.contains("pact"); } catch(Exception e) { diff --git a/Core/src/net/tnemc/core/hook/tnk/TNKHandler.java b/Core/src/net/tnemc/core/hook/tnk/TNKHandler.java index bd6fdc5c..b76dacc4 100644 --- a/Core/src/net/tnemc/core/hook/tnk/TNKHandler.java +++ b/Core/src/net/tnemc/core/hook/tnk/TNKHandler.java @@ -29,6 +29,7 @@ public class TNKHandler { public static void addTypes() { + TNECore.eco().account().addAccountType(PactAccount.class, new PactCheck().check()); TNECore.eco().account().addAccountType(KingdomAccount.class, new KingdomCheck().check()); TNECore.eco().account().addAccountType(VillageAccount.class, new VillageCheck().check()); diff --git a/Core/src/net/tnemc/core/hook/tnk/VillageAccount.java b/Core/src/net/tnemc/core/hook/tnk/VillageAccount.java index 49af9d25..f6209c3c 100644 --- a/Core/src/net/tnemc/core/hook/tnk/VillageAccount.java +++ b/Core/src/net/tnemc/core/hook/tnk/VillageAccount.java @@ -31,6 +31,7 @@ public class VillageAccount extends NonPlayerAccount { public VillageAccount(UUID identifier, String name) { + super(identifier, name); //this.owner = Objects.requireNonNull(TownyAPI.getInstance().getTown(name)).getMayor().getUUID(); } @@ -42,11 +43,13 @@ public VillageAccount(UUID identifier, String name) { */ @Override public String type() { + return "town"; } @Override public UUID generateIdentifier(String name) { + return super.generateIdentifier(name); } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/hook/tnk/VillageCheck.java b/Core/src/net/tnemc/core/hook/tnk/VillageCheck.java index fa8bac91..7d818bf7 100644 --- a/Core/src/net/tnemc/core/hook/tnk/VillageCheck.java +++ b/Core/src/net/tnemc/core/hook/tnk/VillageCheck.java @@ -31,15 +31,16 @@ public class VillageCheck implements AccountTypeCheck { /** - * Returns our check function that should be used to check if a given String identifier, usually name, - * is valid for this account type. + * Returns our check function that should be used to check if a given String identifier, usually + * name, is valid for this account type. * * @return Our function that should be used to check if a given String identifier, usually name, * is valid for this account type. */ @Override public Function check() { - return value -> { + + return value->{ try { return value.contains("town"); } catch(Exception e) { diff --git a/Core/src/net/tnemc/core/io/maps/MultiTreeMap.java b/Core/src/net/tnemc/core/io/maps/MultiTreeMap.java index b9c7a1e2..7df781b9 100644 --- a/Core/src/net/tnemc/core/io/maps/MultiTreeMap.java +++ b/Core/src/net/tnemc/core/io/maps/MultiTreeMap.java @@ -43,14 +43,17 @@ public class MultiTreeMap { private final int perPage; public MultiTreeMap(int perPage) { + this.perPage = perPage; } public void put(final BigDecimal key, final V value) { + map.computeIfAbsent(key, k->new ArrayList<>()).add(value); } public List get(final BigDecimal key) { + if(map.containsKey(key)) { return map.get(key); } @@ -58,10 +61,12 @@ public List get(final BigDecimal key) { } public void removeValues(final BigDecimal key) { + map.remove(key); } public boolean containsKey(final BigDecimal key) { + return map.containsKey(key); } @@ -96,6 +101,7 @@ public void sort() { } public int position(V search) { + for(TopPage page : pageMap.values()) { if(page.getValues().containsKey(search)) { return (((page.getPage() - 1) * perPage) + new LinkedList<>(page.getValues().keySet()).indexOf(search)); @@ -112,6 +118,7 @@ public TopPage getValues(int page) { } public int pages() { + return pageMap.size(); } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/io/maps/comparators/receipt/ReceiptTimeComparator.java b/Core/src/net/tnemc/core/io/maps/comparators/receipt/ReceiptTimeComparator.java index b9d4468c..ae523f22 100644 --- a/Core/src/net/tnemc/core/io/maps/comparators/receipt/ReceiptTimeComparator.java +++ b/Core/src/net/tnemc/core/io/maps/comparators/receipt/ReceiptTimeComparator.java @@ -32,6 +32,7 @@ public class ReceiptTimeComparator implements Comparator { @Override public int compare(Receipt firstReceipt, Receipt secondReceipt) { + return Long.compare(firstReceipt.getTime(), secondReceipt.getTime()); } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/io/maps/comparators/receipt/ReceiptVoidComparator.java b/Core/src/net/tnemc/core/io/maps/comparators/receipt/ReceiptVoidComparator.java index 971e0637..9e45c662 100644 --- a/Core/src/net/tnemc/core/io/maps/comparators/receipt/ReceiptVoidComparator.java +++ b/Core/src/net/tnemc/core/io/maps/comparators/receipt/ReceiptVoidComparator.java @@ -32,6 +32,7 @@ public class ReceiptVoidComparator implements Comparator { @Override public int compare(Receipt firstReceipt, Receipt secondReceipt) { + return Boolean.compare(firstReceipt.isVoided(), secondReceipt.isVoided()); } } diff --git a/Core/src/net/tnemc/core/io/message/BaseTranslationProvider.java b/Core/src/net/tnemc/core/io/message/BaseTranslationProvider.java index b44d1860..6da5d136 100644 --- a/Core/src/net/tnemc/core/io/message/BaseTranslationProvider.java +++ b/Core/src/net/tnemc/core/io/message/BaseTranslationProvider.java @@ -37,6 +37,7 @@ * @since 0.1.2.0 */ public class BaseTranslationProvider implements TranslationProvider { + /** * Used to get the language of a player with the associated identifier. * @@ -60,13 +61,14 @@ public String getLang(UUID identifier) { * specified language doesn't exist. * * @param messageData The message data to utilize for this translation. - * @param language The language to translate the node to. + * @param language The language to translate the node to. * * @return The translated message represented by the node, or the default for if the node doesn't * exist. */ @Override public String translateNode(final MessageData messageData, String language) { + String string = TNECore.instance().message().getString(messageData.getNode(), language); for(Map.Entry replacement : messageData.getReplacements().entrySet()) { diff --git a/Core/src/net/tnemc/core/io/serialization/impl/SerialAccount.java b/Core/src/net/tnemc/core/io/serialization/impl/SerialAccount.java index 27a8156f..95074677 100644 --- a/Core/src/net/tnemc/core/io/serialization/impl/SerialAccount.java +++ b/Core/src/net/tnemc/core/io/serialization/impl/SerialAccount.java @@ -52,6 +52,7 @@ public class SerialAccount implements JSONAble { */ @Override public JSONObject toJSON(Account account) { + final JSONObject json = new JSONObject(); json.put("identifier", account.getIdentifier()); @@ -62,7 +63,7 @@ public JSONObject toJSON(Account account) { json.put("type", account.type()); final JSONArray holdingsArray = new JSONArray(); - for (HoldingsEntry entry : account.getWallet().entryList()) { + for(HoldingsEntry entry : account.getWallet().entryList()) { holdingsArray.add(new SerialHoldings().toJSON(entry)); } json.put("holdings", holdingsArray); @@ -71,7 +72,7 @@ public JSONObject toJSON(Account account) { json.put("owner", shared.getOwner()); final JSONArray membersArray = new JSONArray(); - for (Member member : shared.getMembers().values()) { + for(Member member : shared.getMembers().values()) { membersArray.add(new SerialMember().toJSON(member)); } json.put("members", membersArray); @@ -94,6 +95,7 @@ public JSONObject toJSON(Account account) { */ @Override public Account fromJSON(String serialized) { + try { final JSONParser parser = new JSONParser(); final JSONObject json = (JSONObject)parser.parse(serialized); @@ -103,9 +105,9 @@ public Account fromJSON(String serialized) { final String type = (String)json.get("type"); final AccountAPIResponse response = TNECore.eco().account().createAccount(identifier, - name, - !(type.equalsIgnoreCase("player") || - type.equalsIgnoreCase("bedrock"))); + name, + !(type.equalsIgnoreCase("player") || + type.equalsIgnoreCase("bedrock"))); if(response.getResponse().success()) { final Optional account = response.getAccount(); @@ -116,7 +118,7 @@ public Account fromJSON(String serialized) { account.get().setCreationDate((Long)json.get("creationDate")); account.get().setStatus(TNECore.eco().account().findStatus((String)json.get("status"))); - final JSONArray holdingsArray = (JSONArray) json.get("holdings"); + final JSONArray holdingsArray = (JSONArray)json.get("holdings"); final Wallet wallet = new Wallet(); for(Object entryObj : holdingsArray) { final JSONObject entryJson = (JSONObject)entryObj; @@ -131,10 +133,10 @@ public Account fromJSON(String serialized) { if(json.containsKey("members")) { - final JSONArray membersArray = (JSONArray) json.get("members"); + final JSONArray membersArray = (JSONArray)json.get("members"); for(Object memberObj : membersArray) { - final JSONObject memberJson = (JSONObject) memberObj; + final JSONObject memberJson = (JSONObject)memberObj; final Member member = new SerialMember().fromJSON(memberJson.toJSONString()); shared.getMembers().put(member.getId(), member); } @@ -150,7 +152,7 @@ public Account fromJSON(String serialized) { return account.get(); } } - } catch (ParseException | NumberFormatException | ClassCastException e) { + } catch(ParseException | NumberFormatException | ClassCastException e) { e.printStackTrace(); return null; } diff --git a/Core/src/net/tnemc/core/io/serialization/impl/SerialCurrency.java b/Core/src/net/tnemc/core/io/serialization/impl/SerialCurrency.java index 051ea6d9..76cc2baa 100644 --- a/Core/src/net/tnemc/core/io/serialization/impl/SerialCurrency.java +++ b/Core/src/net/tnemc/core/io/serialization/impl/SerialCurrency.java @@ -38,6 +38,7 @@ * @since 0.1.2.0 */ public class SerialCurrency implements JSONAble { + /** * Used to serialize this object to a JSON-valid string. * @@ -47,6 +48,7 @@ public class SerialCurrency implements JSONAble { */ @Override public JSONObject toJSON(Currency currency) { + final JSONObject json = new JSONObject(); json.put("startingHoldings", currency.getStartingHoldings().toString()); @@ -113,10 +115,11 @@ public JSONObject toJSON(Currency currency) { */ @Override public Currency fromJSON(String serialized) { + final JSONParser parser = new JSONParser(); try { - final JSONObject jsonObject = (JSONObject) parser.parse(serialized); + final JSONObject jsonObject = (JSONObject)parser.parse(serialized); final Currency currency = (jsonObject.containsKey("ender"))? new ItemCurrency("USD") : new Currency("USD"); @@ -175,7 +178,7 @@ public Currency fromJSON(String serialized) { } return currency; - } catch (ParseException e) { + } catch(ParseException e) { e.printStackTrace(); return null; diff --git a/Core/src/net/tnemc/core/io/serialization/impl/SerialDenomination.java b/Core/src/net/tnemc/core/io/serialization/impl/SerialDenomination.java index 686fbc27..cdaecdc5 100644 --- a/Core/src/net/tnemc/core/io/serialization/impl/SerialDenomination.java +++ b/Core/src/net/tnemc/core/io/serialization/impl/SerialDenomination.java @@ -41,10 +41,12 @@ public class SerialDenomination implements JSONAble { * Used to serialize this object to a JSON-valid string. * * @param denom The object to serialize. + * * @return The {@link JSONObject} associated with the JSON-valid String. */ @Override public JSONObject toJSON(Denomination denom) { + final JSONObject json = new JSONObject(); json.put("single", denom.singular()); json.put("plural", denom.plural()); @@ -66,35 +68,38 @@ public JSONObject toJSON(Denomination denom) { /** * Used to generate information for this object from + * * @param serialized The JSON-valid String that we are going to deserialize. + * * @return The object that was deserialized from the JSON string. */ @Override public Denomination fromJSON(String serialized) { + final JSONParser parser = new JSONParser(); JSONObject jsonObject = null; try { - jsonObject = (JSONObject) parser.parse(serialized); + jsonObject = (JSONObject)parser.parse(serialized); final BigDecimal weight = new BigDecimal(jsonObject.get("weight").toString()); final Denomination denomination = (jsonObject.containsKey("item"))? - new ItemDenomination(weight) : - new Denomination(weight); + new ItemDenomination(weight) : + new Denomination(weight); denomination.setSingle((String)jsonObject.get("single")); denomination.setPlural((String)jsonObject.get("plural")); if(denomination instanceof ItemDenomination itemDenomination) { - itemDenomination.setEnchantments((List) jsonObject.get("enchantments")); - itemDenomination.setFlags((List) jsonObject.get("flags")); - itemDenomination.setLore((List) jsonObject.get("lore")); - itemDenomination.setMaterial((String) jsonObject.get("material")); - itemDenomination.setDamage(((Long) jsonObject.get("damage")).shortValue()); - itemDenomination.setName((String) jsonObject.get("name")); - itemDenomination.setCustomModel((Integer) jsonObject.get("customModel")); - itemDenomination.setTexture((String) jsonObject.get("texture")); + itemDenomination.setEnchantments((List)jsonObject.get("enchantments")); + itemDenomination.setFlags((List)jsonObject.get("flags")); + itemDenomination.setLore((List)jsonObject.get("lore")); + itemDenomination.setMaterial((String)jsonObject.get("material")); + itemDenomination.setDamage(((Long)jsonObject.get("damage")).shortValue()); + itemDenomination.setName((String)jsonObject.get("name")); + itemDenomination.setCustomModel((Integer)jsonObject.get("customModel")); + itemDenomination.setTexture((String)jsonObject.get("texture")); return itemDenomination; } diff --git a/Core/src/net/tnemc/core/io/serialization/impl/SerialHoldings.java b/Core/src/net/tnemc/core/io/serialization/impl/SerialHoldings.java index b96821e8..24f5d1f8 100644 --- a/Core/src/net/tnemc/core/io/serialization/impl/SerialHoldings.java +++ b/Core/src/net/tnemc/core/io/serialization/impl/SerialHoldings.java @@ -45,6 +45,7 @@ public class SerialHoldings implements JSONAble { */ @Override public JSONObject toJSON(HoldingsEntry holdings) { + final JSONObject json = new JSONObject(); json.put("region", holdings.getRegion()); @@ -63,15 +64,16 @@ public JSONObject toJSON(HoldingsEntry holdings) { */ @Override public HoldingsEntry fromJSON(String serialized) { + try { final JSONParser parser = new JSONParser(); final JSONObject json = (JSONObject)parser.parse(serialized); return new HoldingsEntry((String)json.get("region"), - UUID.fromString((String)json.get("currency")), - new BigDecimal((String)json.get("amount")), - Identifier.fromID((String)json.get("handler"))); - } catch (ParseException | NumberFormatException | ClassCastException e) { + UUID.fromString((String)json.get("currency")), + new BigDecimal((String)json.get("amount")), + Identifier.fromID((String)json.get("handler"))); + } catch(ParseException | NumberFormatException | ClassCastException e) { e.printStackTrace(); return null; } diff --git a/Core/src/net/tnemc/core/io/serialization/impl/SerialMember.java b/Core/src/net/tnemc/core/io/serialization/impl/SerialMember.java index 04d7bf5a..a8dddfed 100644 --- a/Core/src/net/tnemc/core/io/serialization/impl/SerialMember.java +++ b/Core/src/net/tnemc/core/io/serialization/impl/SerialMember.java @@ -43,11 +43,12 @@ public class SerialMember implements JSONAble { */ @Override public JSONObject toJSON(Member member) { + final JSONObject json = new JSONObject(); json.put("id", member.getId().toString()); JSONObject permissionsJson = new JSONObject(); - member.getPermissions().forEach((permission, value) -> permissionsJson.put(permission, value)); + member.getPermissions().forEach((permission, value)->permissionsJson.put(permission, value)); json.put("permissions", permissionsJson); return json; @@ -62,21 +63,22 @@ public JSONObject toJSON(Member member) { */ @Override public Member fromJSON(String serialized) { + try { final JSONParser parser = new JSONParser(); final JSONObject json = (JSONObject)parser.parse(serialized); final Member member = new Member(UUID.fromString((String)json.get("id"))); - final JSONObject permissionsJson = (JSONObject) json.get("permissions"); - permissionsJson.forEach((permission, value) -> { + final JSONObject permissionsJson = (JSONObject)json.get("permissions"); + permissionsJson.forEach((permission, value)->{ if(value instanceof Boolean) { - member.addPermission((String) permission, (Boolean) value); + member.addPermission((String)permission, (Boolean)value); } }); return member; - } catch (ParseException | NumberFormatException | ClassCastException e) { + } catch(ParseException | NumberFormatException | ClassCastException e) { e.printStackTrace(); return null; } diff --git a/Core/src/net/tnemc/core/io/serialization/impl/SerialNote.java b/Core/src/net/tnemc/core/io/serialization/impl/SerialNote.java index 4a022170..67348511 100644 --- a/Core/src/net/tnemc/core/io/serialization/impl/SerialNote.java +++ b/Core/src/net/tnemc/core/io/serialization/impl/SerialNote.java @@ -46,6 +46,7 @@ public class SerialNote implements JSONAble { */ @Override public JSONObject toJSON(Note note) { + final JSONObject json = new JSONObject(); json.put("material", note.getMaterial()); json.put("minimum", note.getMinimum().toPlainString()); @@ -74,6 +75,7 @@ public JSONObject toJSON(Note note) { */ @Override public Note fromJSON(String serialized) { + final JSONParser parser = new JSONParser(); try { diff --git a/Core/src/net/tnemc/core/io/serialization/impl/SerialTaxEntry.java b/Core/src/net/tnemc/core/io/serialization/impl/SerialTaxEntry.java index d75980c4..f808fd99 100644 --- a/Core/src/net/tnemc/core/io/serialization/impl/SerialTaxEntry.java +++ b/Core/src/net/tnemc/core/io/serialization/impl/SerialTaxEntry.java @@ -41,6 +41,7 @@ public class SerialTaxEntry implements JSONAble { */ @Override public JSONObject toJSON(TaxEntry entry) { + final JSONObject json = new JSONObject(); json.put("type", entry.type()); json.put("amount", entry.amount()); @@ -56,6 +57,7 @@ public JSONObject toJSON(TaxEntry entry) { */ @Override public TaxEntry fromJSON(String serialized) { + final JSONParser parser = new JSONParser(); try { diff --git a/Core/src/net/tnemc/core/io/storage/datables/sql/standard/SQLAccount.java b/Core/src/net/tnemc/core/io/storage/datables/sql/standard/SQLAccount.java index bd6652e2..b920ca6a 100644 --- a/Core/src/net/tnemc/core/io/storage/datables/sql/standard/SQLAccount.java +++ b/Core/src/net/tnemc/core/io/storage/datables/sql/standard/SQLAccount.java @@ -62,6 +62,7 @@ public class SQLAccount implements Datable { */ @Override public Class clazz() { + return Account.class; } @@ -72,11 +73,12 @@ public Class clazz() { */ @Override public void purge(StorageConnector connector) { + if(connector instanceof SQLConnector sql && sql.dialect() instanceof TNEDialect tne) { sql.executeUpdate(tne.accountPurge( - DataConfig.yaml().getInt("Data.Purge.Accounts.Days") - ), - new Object[] {}); + DataConfig.yaml().getInt("Data.Purge.Accounts.Days") + ), + new Object[]{}); } } @@ -84,27 +86,28 @@ public void purge(StorageConnector connector) { * Used to store this object. * * @param connector The storage connector to use for this transaction. - * @param account The object to be stored. + * @param account The object to be stored. */ @Override public void store(StorageConnector connector, @NotNull Account account, @Nullable String identifier) { + if(connector instanceof SQLConnector sql && sql.dialect() instanceof TNEDialect tne) { PluginCore.log().debug("Saving Account with ID: " + identifier + " Name: " + account.getName(), DebugLevel.STANDARD); //store the basic account information(accounts table) final int test = sql.executeUpdate(tne.saveAccount(), - new Object[] { - account.getIdentifier().toString(), - account.getName(), - (account.type()), - new java.sql.Timestamp(account.getCreationDate()), - account.getPin(), - account.getStatus().identifier(), - account.getName(), - account.getPin(), - account.getStatus().identifier(), - }); + new Object[]{ + account.getIdentifier().toString(), + account.getName(), + (account.type()), + new java.sql.Timestamp(account.getCreationDate()), + account.getPin(), + account.getStatus().identifier(), + account.getName(), + account.getPin(), + account.getStatus().identifier(), + }); PluginCore.log().debug("Account Insert Executed correctly: " + test + " - " + identifier, DebugLevel.DETAILED); @@ -112,11 +115,11 @@ public void store(StorageConnector connector, @NotNull Account account, @Null //Player account storage.(players_accounts table) final int test2 = sql.executeUpdate(tne.savePlayer(), - new Object[]{ + new Object[]{ account.getIdentifier().toString(), new java.sql.Timestamp(playerAccount.getLastOnline()), new java.sql.Timestamp(playerAccount.getLastOnline()) - }); + }); PluginCore.log().debug("Player Account Insert Executed correctly: " + test2 + " - " + identifier, DebugLevel.DETAILED); } @@ -125,26 +128,26 @@ public void store(StorageConnector connector, @NotNull Account account, @Null //Non-player accounts.(non_players_accounts table) final String owner = (shared.getOwner() == null)? account.getIdentifier().toString() : - shared.getOwner().toString(); + shared.getOwner().toString(); sql.executeUpdate(tne.saveNonPlayer(), - new Object[]{ - account.getIdentifier().toString(), - owner, - owner - }); + new Object[]{ + account.getIdentifier().toString(), + owner, + owner + }); //Account members(account_members table) for(Member member : shared.getMembers().values()) { for(Map.Entry entry : member.getPermissions().entrySet()) { sql.executeUpdate(tne.saveMembers(), - new Object[]{ - member.getId().toString(), - account.getIdentifier().toString(), - entry.getKey(), - entry.getValue(), - entry.getValue() - } - ); + new Object[]{ + member.getId().toString(), + account.getIdentifier().toString(), + entry.getKey(), + entry.getValue(), + entry.getValue() + } + ); } } } @@ -163,6 +166,7 @@ public void store(StorageConnector connector, @NotNull Account account, @Null */ @Override public void storeAll(StorageConnector connector, @Nullable String identifier) { + if(connector instanceof SQLConnector) { for(Account account : TNECore.eco().account().getAccounts().values()) { store(connector, account, account.getIdentifier().toString()); @@ -180,15 +184,16 @@ public void storeAll(StorageConnector connector, @Nullable String identifier) */ @Override public Optional load(StorageConnector connector, @NotNull String identifier) { + if(connector instanceof SQLConnector sql && sql.dialect() instanceof TNEDialect tne) { Account account = null; //Loading/creating our account object. try(ResultSet result = sql.executeQuery(tne.loadAccount(), - new Object[] { - identifier - })) { + new Object[]{ + identifier + })) { if(result.next()) { final String type = result.getString("account_type"); @@ -196,7 +201,7 @@ public Optional load(StorageConnector connector, @NotNull String ide final AccountAPIResponse response = TNECore.eco().account().createAccount(identifier, result.getString("username"), !(type.equalsIgnoreCase("player") || - type.equalsIgnoreCase("bedrock"))); + type.equalsIgnoreCase("bedrock"))); if(response.getResponse().success()) { //load our basic account information @@ -219,9 +224,9 @@ public Optional load(StorageConnector connector, @NotNull String ide //Load our player account info if(account instanceof PlayerAccount playerAccount) { try(ResultSet result = sql.executeQuery(tne.loadPlayer(), - new Object[] { - identifier - })) { + new Object[]{ + identifier + })) { if(result.next()) { playerAccount.setLastOnline(result.getTimestamp("last_online").getTime()); } @@ -233,9 +238,9 @@ public Optional load(StorageConnector connector, @NotNull String ide //load our shared account info if(account instanceof SharedAccount shared) { try(ResultSet result = sql.executeQuery(tne.loadNonPlayer(), - new Object[] { - identifier - })) { + new Object[]{ + identifier + })) { if(result.next()) { shared.setOwner(UUID.fromString(result.getString("owner"))); } @@ -245,14 +250,14 @@ public Optional load(StorageConnector connector, @NotNull String ide //Load our members for shared accounts try(ResultSet result = sql.executeQuery(tne.loadMembers(), - new Object[] { - identifier - })) { + new Object[]{ + identifier + })) { while(result.next()) { shared.addPermission(UUID.fromString(result.getString("uid")), - result.getString("perm"), - result.getBoolean("perm_value") - ); + result.getString("perm"), + result.getBoolean("perm_value") + ); } } catch(SQLException e) { e.printStackTrace(); @@ -283,13 +288,14 @@ public Optional load(StorageConnector connector, @NotNull String ide */ @Override public Collection loadAll(StorageConnector connector, @Nullable String identifier) { + final Collection accounts = new ArrayList<>(); // is this required? Not entirely sure it is - seems maybe a waste if(connector instanceof SQLConnector sql && sql.dialect() instanceof TNEDialect tne) { final List ids = new ArrayList<>(); try(ResultSet result = sql.executeQuery(tne.loadAccounts(), - new Object[]{})) { + new Object[]{})) { while(result.next()) { ids.add(result.getString("uid")); } diff --git a/Core/src/net/tnemc/core/io/storage/datables/sql/standard/SQLHoldings.java b/Core/src/net/tnemc/core/io/storage/datables/sql/standard/SQLHoldings.java index 4f11cee7..38cd9bde 100644 --- a/Core/src/net/tnemc/core/io/storage/datables/sql/standard/SQLHoldings.java +++ b/Core/src/net/tnemc/core/io/storage/datables/sql/standard/SQLHoldings.java @@ -57,6 +57,7 @@ public class SQLHoldings implements Datable { */ @Override public Class clazz() { + return HoldingsEntry.class; } @@ -78,20 +79,21 @@ public void purge(StorageConnector connector) { */ @Override public void store(StorageConnector connector, @NotNull HoldingsEntry object, @Nullable String identifier) { + if(connector instanceof SQLConnector sql && sql.dialect() instanceof TNEDialect tne && identifier != null) { PluginCore.log().debug("Storing holdings for Identifier: " + identifier); sql.executeUpdate(tne.saveHoldings(), - new Object[] { - identifier, - MainConfig.yaml().getString("Core.Server.Name"), - object.getRegion(), - object.getCurrency().toString(), - object.getHandler().asID(), - object.getAmount(), - object.getAmount() - }); + new Object[]{ + identifier, + MainConfig.yaml().getString("Core.Server.Name"), + object.getRegion(), + object.getCurrency().toString(), + object.getHandler().asID(), + object.getAmount(), + object.getAmount() + }); } } @@ -102,6 +104,7 @@ public void store(StorageConnector connector, @NotNull HoldingsEntry object, */ @Override public void storeAll(StorageConnector connector, @Nullable String identifier) { + if(connector instanceof SQLConnector sql && identifier != null) { final Optional account = TNECore.eco().account().findAccount(identifier); @@ -124,11 +127,13 @@ public void storeAll(StorageConnector connector, @Nullable String identifier) * @param connector The storage connector to use for this transaction. * @param identifier The identifier used to identify the object to load. * - * @throws UnsupportedOperationException as this method is not valid for holdings. * @return The object to load. + * + * @throws UnsupportedOperationException as this method is not valid for holdings. */ @Override public Optional load(StorageConnector connector, @NotNull String identifier) { + throw new UnsupportedOperationException("load for HoldingsEntry is not a supported operation."); } @@ -141,15 +146,16 @@ public Optional load(StorageConnector connector, @NotNull Stri */ @Override public Collection loadAll(StorageConnector connector, @Nullable String identifier) { + final Collection holdings = new ArrayList<>(); if(connector instanceof SQLConnector sql && sql.dialect() instanceof TNEDialect tne && identifier != null) { PluginCore.log().debug("SQLHoldings-loadAll-Account ID:" + identifier, DebugLevel.DEVELOPER); try(ResultSet result = sql.executeQuery(tne.loadHoldings(), - new Object[] { - identifier, - MainConfig.yaml().getString("Core.Server.Name") - })) { + new Object[]{ + identifier, + MainConfig.yaml().getString("Core.Server.Name") + })) { while(result.next()) { final String currency = result.getString("currency"); diff --git a/Core/src/net/tnemc/core/io/storage/datables/sql/standard/SQLReceipt.java b/Core/src/net/tnemc/core/io/storage/datables/sql/standard/SQLReceipt.java index 83519007..56ec9201 100644 --- a/Core/src/net/tnemc/core/io/storage/datables/sql/standard/SQLReceipt.java +++ b/Core/src/net/tnemc/core/io/storage/datables/sql/standard/SQLReceipt.java @@ -49,6 +49,7 @@ * */ public class SQLReceipt implements Datable { + /** * The class that is represented by the O parameter. * @@ -56,6 +57,7 @@ public class SQLReceipt implements Datable { */ @Override public Class clazz() { + return Receipt.class; } @@ -66,9 +68,10 @@ public Class clazz() { */ @Override public void purge(StorageConnector connector) { + if(connector instanceof SQLConnector sql && sql.dialect() instanceof TNEDialect tne) { sql.executeUpdate(tne.receiptPurge(DataConfig.yaml().getInt("Data.Purge.Transaction.Days")), - new Object[] {}); + new Object[]{}); } } @@ -76,25 +79,26 @@ public void purge(StorageConnector connector) { * Used to store this object. * * @param connector The storage connector to use for this transaction. - * @param receipt The object to be stored. + * @param receipt The object to be stored. */ @Override public void store(StorageConnector connector, @NotNull Receipt receipt, @Nullable String identifier) { + if(connector instanceof SQLConnector sql && sql.dialect() instanceof TNEDialect tne) { //Store the receipt info sql.executeUpdate(tne.saveReceipt(), - new Object[]{ - receipt.getId().toString(), - new java.sql.Timestamp(receipt.getTime()), - receipt.getType(), - receipt.getSource().name(), - receipt.getSource().type(), - receipt.isArchive(), - receipt.isVoided(), - receipt.isArchive(), - receipt.isVoided() - }); + new Object[]{ + receipt.getId().toString(), + new java.sql.Timestamp(receipt.getTime()), + receipt.getType(), + receipt.getSource().name(), + receipt.getSource().type(), + receipt.isArchive(), + receipt.isVoided(), + receipt.isArchive(), + receipt.isVoided() + }); storeParticipant(connector, receipt.getFrom(), receipt.getModifierFrom(), "from", receipt.getId().toString()); storeParticipant(connector, receipt.getTo(), receipt.getModifierTo(), "to", receipt.getId().toString()); @@ -105,16 +109,16 @@ private void storeParticipant(StorageConnector connector, @Nullable Transacti @Nullable HoldingsModifier modifier, final String type, @NotNull String identifier) { if(connector instanceof SQLConnector sql && sql.dialect() instanceof TNEDialect tne - && participant != null && modifier != null) { + && participant != null && modifier != null) { //store participant info sql.executeUpdate(tne.saveParticipant(), - new Object[]{ - identifier, - participant.getId(), - type, - participant.getTax() - }); + new Object[]{ + identifier, + participant.getId(), + type, + participant.getTax() + }); //store holdings for(HoldingsEntry entry : participant.getStartingBalances()) { @@ -127,15 +131,15 @@ private void storeParticipant(StorageConnector connector, @Nullable Transacti //store modifier sql.executeUpdate(tne.saveModifier(), - new Object[]{ - identifier, - participant.getId(), - type, - modifier.getOperation().name(), - modifier.getRegion(), - modifier.getCurrency().toString(), - modifier.getModifier() - }); + new Object[]{ + identifier, + participant.getId(), + type, + modifier.getOperation().name(), + modifier.getRegion(), + modifier.getCurrency().toString(), + modifier.getModifier() + }); } } @@ -144,16 +148,16 @@ private void storeReceiptHolding(StorageConnector connector, @NotNull Holding if(connector instanceof SQLConnector sql && sql.dialect() instanceof TNEDialect tne) { sql.executeUpdate(tne.saveReceiptHolding(), - new Object[]{ - receipt, - participant, - ending, - MainConfig.yaml().getString("Core.Server.Name"), - entry.getRegion(), - entry.getCurrency().toString(), - entry.getHandler().asID(), - entry.getAmount() - }); + new Object[]{ + receipt, + participant, + ending, + MainConfig.yaml().getString("Core.Server.Name"), + entry.getRegion(), + entry.getCurrency().toString(), + entry.getHandler().asID(), + entry.getAmount() + }); } } @@ -162,8 +166,9 @@ private void storeReceiptHolding(StorageConnector connector, @NotNull Holding * * @param connector The storage connector to use for this transaction. */ - @Override + @Override public void storeAll(StorageConnector connector, @Nullable String identifier) { + if(connector instanceof SQLConnector && identifier != null) { for(Receipt receipt : TransactionManager.receipts().getReceipts().values()) { @@ -191,7 +196,10 @@ public Optional load(StorageConnector connector, @NotNull String ide * Loads a Receipt object from a ResultSet. * * @param result The ResultSet containing the data to load into a Receipt object. - * @return An Optional containing the loaded Receipt object. Returns an empty Optional if the ResultSet is empty. + * + * @return An Optional containing the loaded Receipt object. Returns an empty Optional if the + * ResultSet is empty. + * * @throws SQLException if an error occurs while accessing the ResultSet data. */ public Receipt load(ResultSet result, SQLConnector sql, TNEDialect dialect) throws SQLException { @@ -210,8 +218,9 @@ public Receipt load(ResultSet result, SQLConnector sql, TNEDialect dialect) thro } public void loadParticipants(Receipt receipt, SQLConnector sql, TNEDialect dialect) { + try(ResultSet result = sql.executeQuery(dialect.loadParticipants(), new Object[]{ - receipt.getId().toString()})) { + receipt.getId().toString() })) { while(result.next()) { final String type = result.getString("participant_type").toLowerCase(Locale.ROOT); @@ -233,15 +242,15 @@ public void loadParticipants(Receipt receipt, SQLConnector sql, TNEDialect diale modifier.ifPresent(receipt::setModifierTo); } } - } catch(Exception ignore) {} + } catch(Exception ignore) { } } public Optional loadModifier(final UUID receiptID, final UUID participant, - final String type, SQLConnector sql, TNEDialect dialect) { + final String type, SQLConnector sql, TNEDialect dialect) { HoldingsModifier modifier = null; //participant, participant_type, operation, region, currency AS currency, modifier - uid/participant - try(ResultSet result = sql.executeQuery(dialect.loadReceiptHolding(), new Object[] { + try(ResultSet result = sql.executeQuery(dialect.loadReceiptHolding(), new Object[]{ receiptID.toString(), participant, type })) { if(result.next()) { @@ -252,7 +261,7 @@ public Optional loadModifier(final UUID receiptID, final UUID result.getBigDecimal("modifier"), HoldingsOperation.valueOf(result.getString("operation"))); } - } catch(Exception ignore) {} + } catch(Exception ignore) { } return Optional.ofNullable(modifier); } @@ -262,7 +271,7 @@ public List loadHoldings(final UUID receiptID, final UUID partici final List holdings = new ArrayList<>(); //participant, ending, server, region, currency AS currency, holdings_type, holdings - uid/participant - try(ResultSet result = sql.executeQuery(dialect.loadReceiptHolding(), new Object[] { + try(ResultSet result = sql.executeQuery(dialect.loadReceiptHolding(), new Object[]{ receiptID.toString(), participant, ending })) { while(result.next()) { @@ -275,7 +284,7 @@ public List loadHoldings(final UUID receiptID, final UUID partici ); holdings.add(entry); } - } catch(Exception ignore) {} + } catch(Exception ignore) { } return holdings; } @@ -289,6 +298,7 @@ public List loadHoldings(final UUID receiptID, final UUID partici */ @Override public Collection loadAll(StorageConnector connector, @Nullable String identifier) { + final Collection receipts = new ArrayList<>(); // is this required? Not entirely sure it is - seems maybe a waste if(connector instanceof SQLConnector sql && sql.dialect() instanceof TNEDialect tne) { @@ -299,7 +309,7 @@ public Collection loadAll(StorageConnector connector, @Nullable Stri receipts.add(load(result, sql, tne)); } - } catch(Exception ignore) {} + } catch(Exception ignore) { } } return receipts; } diff --git a/Core/src/net/tnemc/core/io/storage/datables/yaml/YAMLAccount.java b/Core/src/net/tnemc/core/io/storage/datables/yaml/YAMLAccount.java index 42f2f1ae..645e2fa4 100644 --- a/Core/src/net/tnemc/core/io/storage/datables/yaml/YAMLAccount.java +++ b/Core/src/net/tnemc/core/io/storage/datables/yaml/YAMLAccount.java @@ -61,6 +61,7 @@ public class YAMLAccount implements Datable { */ @Override public Class clazz() { + return Account.class; } @@ -78,7 +79,7 @@ public void purge(StorageConnector connector) { * Used to store this object. * * @param connector The storage connector to use for this transaction. - * @param account The object to be stored. + * @param account The object to be stored. */ @Override public void store(StorageConnector connector, @NotNull Account account, @Nullable String identifier) { @@ -132,7 +133,7 @@ public void store(StorageConnector connector, @NotNull Account account, @Null if(account instanceof SharedAccount shared) { final String owner = (shared.getOwner() == null)? account.getIdentifier().toString() : - shared.getOwner().toString(); + shared.getOwner().toString(); yaml.set("Info.Owner", owner); @@ -166,6 +167,7 @@ public void store(StorageConnector connector, @NotNull Account account, @Null */ @Override public void storeAll(StorageConnector connector, @Nullable String identifier) { + for(Account account : TNECore.eco().account().getAccounts().values()) { store(connector, account, account.getIdentifier().toString()); } @@ -191,6 +193,7 @@ public Optional load(StorageConnector connector, @NotNull String ide } public Optional load(File accFile, final String identifier) { + if(accFile == null) { PluginCore.log().error("Null account file passed to YAMLAccount.load. Account: " + identifier, DebugLevel.OFF); @@ -223,7 +226,7 @@ public Optional load(File accFile, final String identifier) { final AccountAPIResponse response = TNECore.eco().account().createAccount(identifier, yaml.getString("Info.Name"), !(type.equalsIgnoreCase("player") || - type.equalsIgnoreCase("bedrock"))); + type.equalsIgnoreCase("bedrock"))); if(response.getResponse().success() && response.getAccount().isPresent()) { //load our basic account information @@ -250,8 +253,8 @@ public Optional load(File accFile, final String identifier) { final String permission = (String)permissionObj; shared.addPermission(UUID.fromString(member), permission, - yaml.getBoolean("Members." + member + - "." + permission)); + yaml.getBoolean("Members." + member + + "." + permission)); } } } @@ -279,6 +282,7 @@ public Optional load(File accFile, final String identifier) { */ @Override public Collection loadAll(StorageConnector connector, @Nullable String identifier) { + final Collection accounts = new ArrayList<>(); for(File file : IOUtil.getYAMLs(new File(PluginCore.directory(), "accounts"))) { diff --git a/Core/src/net/tnemc/core/io/storage/datables/yaml/YAMLHoldings.java b/Core/src/net/tnemc/core/io/storage/datables/yaml/YAMLHoldings.java index f05874f8..144c2191 100644 --- a/Core/src/net/tnemc/core/io/storage/datables/yaml/YAMLHoldings.java +++ b/Core/src/net/tnemc/core/io/storage/datables/yaml/YAMLHoldings.java @@ -58,6 +58,7 @@ public class YAMLHoldings implements Datable { */ @Override public Class clazz() { + return HoldingsEntry.class; } @@ -113,8 +114,8 @@ public void store(StorageConnector connector, @NotNull HoldingsEntry object, } yaml.set("Holdings." + MainConfig.yaml().getString("Core.Server.Name") - + "." + object.getRegion() + "." + object.getCurrency().toString() + "." - + object.getHandler().asID(), object.getAmount().toPlainString()); + + "." + object.getRegion() + "." + object.getCurrency().toString() + "." + + object.getHandler().asID(), object.getAmount().toPlainString()); PluginCore.log().debug("YAMLHoldings-store-Entry ID:" + identifier, DebugLevel.DEVELOPER); PluginCore.log().debug("YAMLHoldings-store-Entry Currency:" + object.getCurrency().toString(), DebugLevel.DEVELOPER); @@ -176,8 +177,8 @@ public void storeAll(StorageConnector connector, @Nullable String identifier) for(HoldingsEntry entry : currency.getHoldings().values()) { yaml.set("Holdings." + MainConfig.yaml().getString("Core.Server.Name") - + "." + entry.getRegion() + "." + entry.getCurrency().toString() + "." - + entry.getHandler().asID(), entry.getAmount().toPlainString()); + + "." + entry.getRegion() + "." + entry.getCurrency().toString() + "." + + entry.getHandler().asID(), entry.getAmount().toPlainString()); } } } @@ -200,10 +201,12 @@ public void storeAll(StorageConnector connector, @Nullable String identifier) * @param identifier The identifier used to identify the object to load. * * @return The object to load. + * * @throws UnsupportedOperationException as this method is not valid for holdings. */ @Override public Optional load(StorageConnector connector, @NotNull String identifier) { + throw new UnsupportedOperationException("load for HoldingsEntry is not a supported operation."); } @@ -216,6 +219,7 @@ public Optional load(StorageConnector connector, @NotNull Stri */ @Override public Collection loadAll(StorageConnector connector, @Nullable String identifier) { + final Collection holdings = new ArrayList<>(); if(identifier != null) { @@ -276,9 +280,9 @@ public Collection loadAll(StorageConnector connector, @Nullabl //region, currency, amount, type final HoldingsEntry entry = new HoldingsEntry(region, - UUID.fromString(currency), - new BigDecimal(amount), - Identifier.fromID(handler) + UUID.fromString(currency), + new BigDecimal(amount), + Identifier.fromID(handler) ); PluginCore.log().debug("YAMLHoldings-loadAll-Entry ID:" + entry.getHandler(), DebugLevel.DEVELOPER); diff --git a/Core/src/net/tnemc/core/io/storage/datables/yaml/YAMLReceipt.java b/Core/src/net/tnemc/core/io/storage/datables/yaml/YAMLReceipt.java index 21188dff..1ce7d389 100644 --- a/Core/src/net/tnemc/core/io/storage/datables/yaml/YAMLReceipt.java +++ b/Core/src/net/tnemc/core/io/storage/datables/yaml/YAMLReceipt.java @@ -53,6 +53,7 @@ * @since 0.1.2.0 */ public class YAMLReceipt implements Datable { + /** * The class that is represented by the O parameter. * @@ -60,6 +61,7 @@ public class YAMLReceipt implements Datable { */ @Override public Class clazz() { + return Receipt.class; } @@ -76,10 +78,10 @@ public void purge(StorageConnector connector) { /** * Used to store this object. * - * @param connector The storage connector to use for this transaction. - * @param receipt The object to be stored. + * @param connector The storage connector to use for this transaction. + * @param receipt The object to be stored. * @param identifier An optional identifier for loading this object. Note: some Datables may - * require this identifier. + * require this identifier. */ @Override public void store(StorageConnector connector, @NotNull Receipt receipt, @Nullable String identifier) { @@ -170,9 +172,9 @@ public void store(StorageConnector connector, @NotNull Receipt receipt, @Null /** * Used to store all objects of this type. * - * @param connector The storage connector to use for this transaction. + * @param connector The storage connector to use for this transaction. * @param identifier The identifier used to load objects, if they relate to a specific identifier, - * otherwise this will be null. + * otherwise this will be null. */ @Override public void storeAll(StorageConnector connector, @Nullable String identifier) { @@ -185,7 +187,7 @@ public void storeAll(StorageConnector connector, @Nullable String identifier) /** * Used to load this object. * - * @param connector The storage connector to use for this transaction. + * @param connector The storage connector to use for this transaction. * @param identifier The identifier used to identify the object to load. * * @return The object to load. @@ -203,6 +205,7 @@ public Optional load(StorageConnector connector, @NotNull String ide } public Optional load(File file, final String identifier) { + if(file == null) { PluginCore.log().error("Null account file passed to YAMLReceipt.load. Receipt: " + identifier); @@ -262,16 +265,18 @@ public void loadParticipant(YamlDocument yaml, Receipt receipt, String type) { receipt.setModifierTo(loadModifier(yaml, type)); } } + public HoldingsModifier loadModifier(YamlDocument yaml, String type) { return new HoldingsModifier(yaml.getString(type + ".modifier.region"), - UUID.fromString(yaml.getString(type + ".modifier.currency")), - new BigDecimal(yaml.getString(type + ".modifier.modifier")), - HoldingsOperation.valueOf(yaml.getString(type + ".modifier.operation"))); + UUID.fromString(yaml.getString(type + ".modifier.currency")), + new BigDecimal(yaml.getString(type + ".modifier.modifier")), + HoldingsOperation.valueOf(yaml.getString(type + ".modifier.operation"))); } public List loadHoldings(YamlDocument yaml, String type, String holdingsType) { + final List holdings = new ArrayList<>(); @@ -309,14 +314,15 @@ public List loadHoldings(YamlDocument yaml, String type, String h /** * Used to load all objects of this type. * - * @param connector The storage connector to use for this transaction. + * @param connector The storage connector to use for this transaction. * @param identifier The identifier used to load objects, if they relate to a specific identifier, - * otherwise this will be null. + * otherwise this will be null. * * @return A collection containing the objects loaded. */ @Override public Collection loadAll(StorageConnector connector, @Nullable String identifier) { + final Collection receipts = new ArrayList<>(); for(File file : IOUtil.getYAMLs(new File(PluginCore.directory(), "transactions"))) { diff --git a/Core/src/net/tnemc/core/io/storage/dialect/TNEDialect.java b/Core/src/net/tnemc/core/io/storage/dialect/TNEDialect.java index e4048a80..cdb33312 100644 --- a/Core/src/net/tnemc/core/io/storage/dialect/TNEDialect.java +++ b/Core/src/net/tnemc/core/io/storage/dialect/TNEDialect.java @@ -29,85 +29,116 @@ */ public interface TNEDialect extends Dialect { - @Language("SQL") String accountsTable(); + @Language("SQL") + String accountsTable(); - @Language("SQL") String accountsNonPlayerTable(); + @Language("SQL") + String accountsNonPlayerTable(); - @Language("SQL") String accountsPlayerTable(); + @Language("SQL") + String accountsPlayerTable(); - @Language("SQL") String accountMembersTable(); + @Language("SQL") + String accountMembersTable(); - @Language("SQL") String holdingsTable(); + @Language("SQL") + String holdingsTable(); - @Language("SQL") String receiptsTable(); + @Language("SQL") + String receiptsTable(); - @Language("SQL") String receiptsHoldingsTable(); + @Language("SQL") + String receiptsHoldingsTable(); - @Language("SQL") String receiptsParticipantsTable(); + @Language("SQL") + String receiptsParticipantsTable(); - @Language("SQL") String receiptsModifiersTable(); + @Language("SQL") + String receiptsModifiersTable(); - @Language("SQL") String accountPurge(final int days); + @Language("SQL") + String accountPurge(final int days); - @Language("SQL") String receiptPurge(final int days); + @Language("SQL") + String receiptPurge(final int days); //player name save - @Language("SQL") String saveName(); + @Language("SQL") + String saveName(); //load accounts - @Language("SQL") String loadAccounts(); + @Language("SQL") + String loadAccounts(); //account load - @Language("SQL") String loadAccount(); + @Language("SQL") + String loadAccount(); //account save - @Language("SQL") String saveAccount(); + @Language("SQL") + String saveAccount(); //non player load - @Language("SQL") String loadNonPlayer(); + @Language("SQL") + String loadNonPlayer(); //non player save - @Language("SQL") String saveNonPlayer(); + @Language("SQL") + String saveNonPlayer(); //player load - @Language("SQL") String loadPlayer(); + @Language("SQL") + String loadPlayer(); //player save - @Language("SQL") String savePlayer(); + @Language("SQL") + String savePlayer(); //members load - @Language("SQL") String loadMembers(); + @Language("SQL") + String loadMembers(); //members save - @Language("SQL") String saveMembers(); + @Language("SQL") + String saveMembers(); //holdings load - @Language("SQL") String loadHoldings(); + @Language("SQL") + String loadHoldings(); //holdings save - @Language("SQL") String saveHoldings(); + @Language("SQL") + String saveHoldings(); //receipts load - @Language("SQL") String loadReceipts(); + @Language("SQL") + String loadReceipts(); //receipt save - @Language("SQL") String saveReceipt(); + @Language("SQL") + String saveReceipt(); //receipts load - @Language("SQL") String loadReceiptHolding(); + @Language("SQL") + String loadReceiptHolding(); //receipt holding save - @Language("SQL") String saveReceiptHolding(); + @Language("SQL") + String saveReceiptHolding(); //receipt participants load - @Language("SQL") String loadParticipants(); + @Language("SQL") + String loadParticipants(); //receipt participant save - @Language("SQL") String saveParticipant(); + @Language("SQL") + String saveParticipant(); //receipt modifiers load - @Language("SQL") String loadModifiers(); + @Language("SQL") + String loadModifiers(); //receipt modifier save - @Language("SQL") String saveModifier(); + @Language("SQL") + String saveModifier(); } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/io/storage/dialect/impl/MariaDialect.java b/Core/src/net/tnemc/core/io/storage/dialect/impl/MariaDialect.java index f4228b5b..444135fa 100644 --- a/Core/src/net/tnemc/core/io/storage/dialect/impl/MariaDialect.java +++ b/Core/src/net/tnemc/core/io/storage/dialect/impl/MariaDialect.java @@ -95,6 +95,7 @@ public class MariaDialect implements TNEDialect { protected final String prefix; public MariaDialect(final String prefix) { + this.prefix = prefix; this.saveName = "INSERT INTO " + prefix + "player_names (uid, username) VALUES (?, ?) ON DUPLICATE KEY UPDATE username = ?"; @@ -104,298 +105,331 @@ public MariaDialect(final String prefix) { this.loadAccount = "SELECT username, account_type, created, pin, status FROM " + prefix + "accounts WHERE uid = ?"; this.saveAccount = "INSERT INTO " + prefix + "accounts (uid, username, account_type, created, pin, status)" + - "VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE username = ?, pin = ?, status = ?"; + "VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE username = ?, pin = ?, status = ?"; this.loadNonPlayer = "SELECT owner AS owner FROM " + prefix + "non_players_accounts WHERE uid = ?"; this.saveNonPlayer = "INSERT INTO " + prefix + "non_players_accounts (uid, owner) VALUES (?, ?) " + - "ON DUPLICATE KEY UPDATE owner = ?"; + "ON DUPLICATE KEY UPDATE owner = ?"; this.loadPlayer = "SELECT last_online FROM " + prefix + "players_accounts WHERE uid = ?"; this.savePlayer = "INSERT INTO " + prefix + "players_accounts (uid, last_online) VALUES (?, ?) " + - "ON DUPLICATE KEY UPDATE last_online = ?"; + "ON DUPLICATE KEY UPDATE last_online = ?"; this.loadMembers = "SELECT uid AS uid, perm, perm_value FROM " + prefix + "account_members WHERE account = ?"; this.saveMember = "INSERT INTO " + prefix + "account_members (uid, account, perm, perm_value) VALUES (?, ?, ?, ?) " + - "ON DUPLICATE KEY UPDATE perm_value = ?"; + "ON DUPLICATE KEY UPDATE perm_value = ?"; this.loadHoldings = "SELECT region, currency AS currency, holdings_type, holdings FROM " + prefix + - "holdings WHERE uid = ? AND server = ?"; + "holdings WHERE uid = ? AND server = ?"; this.saveHolding = "INSERT INTO " + prefix + "holdings (uid, server, region, currency, holdings_type, holdings) " + - "VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE holdings = ?"; + "VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE holdings = ?"; this.loadReceipts = "SELECT uid AS uid, performed, receipt_type, receipt_source, receipt_source_type, archive, voided FROM " + - prefix + "receipts"; + prefix + "receipts"; this.saveReceipt = "INSERT INTO " + prefix + "receipts (uid, performed, receipt_type, receipt_source, " + - "receipt_source_type, archive, voided) " + - "VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE archive = ?, voided = ?"; + "receipt_source_type, archive, voided) " + + "VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE archive = ?, voided = ?"; this.loadReceiptHolding = "SELECT participant AS participant, ending, server, region, " + - "currency AS currency, holdings_type, holdings FROM " + - prefix + "receipts_holdings WHERE uid = ? AND participant = ? AND ending = ?"; + "currency AS currency, holdings_type, holdings FROM " + + prefix + "receipts_holdings WHERE uid = ? AND participant = ? AND ending = ?"; this.saveReceiptHolding = "INSERT INTO " + prefix + "receipts_holdings (uid, participant, ending, " + - "server, region, currency, holdings_type, holdings) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE uid=uid"; + "server, region, currency, holdings_type, holdings) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE uid=uid"; this.loadParticipants = "SELECT participant AS participant, participant_type, tax FROM " + - prefix + "receipts_participants WHERE uid = ?"; + prefix + "receipts_participants WHERE uid = ?"; this.saveParticipant = "INSERT INTO " + prefix + "receipts_participants (uid, participant, participant_type, tax) " + - "VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE uid=uid"; + "VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE uid=uid"; this.loadModifiers = "SELECT participant AS participant, participant_type, operation, region, " + - "currency AS currency, modifier FROM " + prefix + "receipts_modifiers WHERE uid = ? AND participant = ? AND participant_type = ?"; + "currency AS currency, modifier FROM " + prefix + "receipts_modifiers WHERE uid = ? AND participant = ? AND participant_type = ?"; this.saveModifier = "INSERT INTO " + prefix + "receipts_modifiers (uid, participant, participant_type, operation, region, currency, modifier) " + - "VALUES (?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE uid = uid"; + "VALUES (?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE uid = uid"; } @Override public String accountsTable() { + return "CREATE TABLE IF NOT EXISTS " + prefix + "accounts (\n" + - " uid UUID NOT NULL PRIMARY KEY,\n" + - " username VARCHAR(50) NOT NULL UNIQUE,\n" + - " account_type VARCHAR(30) NOT NULL,\n" + - " created DATETIME NOT NULL,\n" + - " pin VARCHAR(16),\n" + - " status VARCHAR(36)\n" + - " );"; + " uid UUID NOT NULL PRIMARY KEY,\n" + + " username VARCHAR(50) NOT NULL UNIQUE,\n" + + " account_type VARCHAR(30) NOT NULL,\n" + + " created DATETIME NOT NULL,\n" + + " pin VARCHAR(16),\n" + + " status VARCHAR(36)\n" + + " );"; } @Override public String accountsNonPlayerTable() { + return "CREATE TABLE IF NOT EXISTS " + prefix + "non_players_accounts (\n" + - " uid UUID NOT NULL UNIQUE,\n" + - " owner UUID NOT NULL,\n" + - " FOREIGN KEY(uid) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE,\n" + - " FOREIGN KEY(owner) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE\n" + - " );"; + " uid UUID NOT NULL UNIQUE,\n" + + " owner UUID NOT NULL,\n" + + " FOREIGN KEY(uid) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE,\n" + + " FOREIGN KEY(owner) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE\n" + + " );"; } @Override public String accountsPlayerTable() { + return "CREATE TABLE IF NOT EXISTS " + prefix + "players_accounts (\n" + - " uid UUID NOT NULL UNIQUE,\n" + - " last_online DATETIME NOT NULL,\n" + - " FOREIGN KEY(uid) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE\n" + - " );"; + " uid UUID NOT NULL UNIQUE,\n" + + " last_online DATETIME NOT NULL,\n" + + " FOREIGN KEY(uid) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE\n" + + " );"; } @Override public String accountMembersTable() { + return "CREATE TABLE IF NOT EXISTS " + prefix + "account_members (\n" + - " uid UUID NOT NULL,\n" + - " account UUID NOT NULL,\n" + - " perm VARCHAR(36) NOT NULL,\n" + - " perm_value TINYINT(1) NOT NULL,\n" + - " FOREIGN KEY(uid) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE,\n" + - " FOREIGN KEY(account) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE\n" + - " );"; + " uid UUID NOT NULL,\n" + + " account UUID NOT NULL,\n" + + " perm VARCHAR(36) NOT NULL,\n" + + " perm_value TINYINT(1) NOT NULL,\n" + + " FOREIGN KEY(uid) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE,\n" + + " FOREIGN KEY(account) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE\n" + + " );"; } @Override public String holdingsTable() { + return "CREATE TABLE IF NOT EXISTS " + prefix + "holdings (\n" + - " uid UUID NOT NULL,\n" + - " server VARCHAR(40) NOT NULL,\n" + - " region VARCHAR(40) NOT NULL,\n" + - " currency UUID NOT NULL,\n" + - " holdings_type VARCHAR(30) NOT NULL,\n" + - " holdings DECIMAL(49, 4) NOT NULL,\n" + - " UNIQUE(`uid`, `server`, `region`, `currency`, `holdings_type`),\n" + - " FOREIGN KEY(uid) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE\n" + - " );"; + " uid UUID NOT NULL,\n" + + " server VARCHAR(40) NOT NULL,\n" + + " region VARCHAR(40) NOT NULL,\n" + + " currency UUID NOT NULL,\n" + + " holdings_type VARCHAR(30) NOT NULL,\n" + + " holdings DECIMAL(49, 4) NOT NULL,\n" + + " UNIQUE(`uid`, `server`, `region`, `currency`, `holdings_type`),\n" + + " FOREIGN KEY(uid) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE\n" + + " );"; } @Override public String receiptsTable() { + return "CREATE TABLE IF NOT EXISTS " + prefix + "receipts (\n" + - " uid UUID NOT NULL UNIQUE,\n" + - " performed DATETIME NOT NULL,\n" + - " receipt_type VARCHAR(30) NOT NULL,\n" + - " receipt_source VARCHAR(60) NOT NULL,\n" + - " receipt_source_type VARCHAR(30) NOT NULL,\n" + - " archive TINYINT(1) NOT NULL,\n" + - " voided TINYINT(1) NOT NULL\n" + - " );"; + " uid UUID NOT NULL UNIQUE,\n" + + " performed DATETIME NOT NULL,\n" + + " receipt_type VARCHAR(30) NOT NULL,\n" + + " receipt_source VARCHAR(60) NOT NULL,\n" + + " receipt_source_type VARCHAR(30) NOT NULL,\n" + + " archive TINYINT(1) NOT NULL,\n" + + " voided TINYINT(1) NOT NULL\n" + + " );"; } @Override public String receiptsHoldingsTable() { + return "CREATE TABLE IF NOT EXISTS " + prefix + "receipts_holdings (\n" + - " uid UUID NOT NULL UNIQUE,\n" + - " participant UUID NOT NULL,\n" + - " ending TINYINT(1) NOT NULL,\n" + - " server VARCHAR(40) NOT NULL,\n" + - " region VARCHAR(40) NOT NULL,\n" + - " currency UUID NOT NULL,\n" + - " holdings_type VARCHAR(30) NOT NULL,\n" + - " holdings DECIMAL(49, 4) NOT NULL,\n" + - " FOREIGN KEY(uid) REFERENCES " + prefix + "receipts(uid) ON DELETE CASCADE\n" + - " );"; + " uid UUID NOT NULL UNIQUE,\n" + + " participant UUID NOT NULL,\n" + + " ending TINYINT(1) NOT NULL,\n" + + " server VARCHAR(40) NOT NULL,\n" + + " region VARCHAR(40) NOT NULL,\n" + + " currency UUID NOT NULL,\n" + + " holdings_type VARCHAR(30) NOT NULL,\n" + + " holdings DECIMAL(49, 4) NOT NULL,\n" + + " FOREIGN KEY(uid) REFERENCES " + prefix + "receipts(uid) ON DELETE CASCADE\n" + + " );"; } @Override public String receiptsParticipantsTable() { + return "CREATE TABLE IF NOT EXISTS " + prefix + "receipts_participants (\n" + - " uid UUID NOT NULL PRIMARY KEY,\n" + - " participant UUID NOT NULL,\n" + - " participant_type VARCHAR(10) NOT NULL,\n" + - " tax DECIMAL(49, 4) NOT NULL,\n" + - " FOREIGN KEY(uid) REFERENCES " + prefix + "receipts(uid) ON DELETE CASCADE\n" + - " );"; + " uid UUID NOT NULL PRIMARY KEY,\n" + + " participant UUID NOT NULL,\n" + + " participant_type VARCHAR(10) NOT NULL,\n" + + " tax DECIMAL(49, 4) NOT NULL,\n" + + " FOREIGN KEY(uid) REFERENCES " + prefix + "receipts(uid) ON DELETE CASCADE\n" + + " );"; } @Override public String receiptsModifiersTable() { + return "CREATE TABLE IF NOT EXISTS " + prefix + "receipts_modifiers (\n" + - " uid UUID NOT NULL PRIMARY KEY,\n" + - " participant UUID NOT NULL,\n" + - " participant_type VARCHAR(10) NOT NULL,\n" + - " operation VARCHAR(10) NOT NULL,\n" + - " region VARCHAR(40) NOT NULL,\n" + - " currency UUID NOT NULL,\n" + - " modifier DECIMAL(49, 4) NOT NULL," + - " FOREIGN KEY(uid) REFERENCES " + prefix + "receipts(uid) ON DELETE CASCADE" + - " );"; + " uid UUID NOT NULL PRIMARY KEY,\n" + + " participant UUID NOT NULL,\n" + + " participant_type VARCHAR(10) NOT NULL,\n" + + " operation VARCHAR(10) NOT NULL,\n" + + " region VARCHAR(40) NOT NULL,\n" + + " currency UUID NOT NULL,\n" + + " modifier DECIMAL(49, 4) NOT NULL," + + " FOREIGN KEY(uid) REFERENCES " + prefix + "receipts(uid) ON DELETE CASCADE" + + " );"; } @Override public @Language("SQL") String accountPurge(final int days) { + final String acc = prefix + "accounts"; final String players = prefix + "players_accounts"; return "DELETE FROM " + acc + - "WHERE uid IN (" + - " SELECT uid FROM " + players + - " WHERE EXISTS (" + - " SELECT *" + - " FROM " + acc + - " WHERE " + acc + ".uid = " + players + ".uid" + - " AND DATEDIFF(DAY, " + players + ".last_online, NOW()) >= " + days + - " )" + - ");"; + "WHERE uid IN (" + + " SELECT uid FROM " + players + + " WHERE EXISTS (" + + " SELECT *" + + " FROM " + acc + + " WHERE " + acc + ".uid = " + players + ".uid" + + " AND DATEDIFF(DAY, " + players + ".last_online, NOW()) >= " + days + + " )" + + ");"; } @Override public @Language("SQL") String receiptPurge(final int days) { + return "DELETE FROM " + prefix + "receipts WHERE archived = false" + - "AND DATEDIFF(CURDATE(), performed) >= " + days; + "AND DATEDIFF(CURDATE(), performed) >= " + days; } @Override public @Language("SQL") String saveName() { + return saveName; } @Override public @Language("SQL") String loadAccounts() { + return loadAccounts; } @Override public @Language("SQL") String loadAccount() { + return loadAccount; } @Override public @Language("SQL") String saveAccount() { + return saveAccount; } @Override public @Language("SQL") String loadNonPlayer() { + return loadNonPlayer; } @Override public @Language("SQL") String saveNonPlayer() { + return saveNonPlayer; } @Override public @Language("SQL") String loadPlayer() { + return loadPlayer; } @Override public @Language("SQL") String savePlayer() { + return savePlayer; } @Override public @Language("SQL") String loadMembers() { + return loadMembers; } @Override public @Language("SQL") String saveMembers() { + return saveMember; } @Override public @Language("SQL") String loadHoldings() { + return loadHoldings; } @Override public @Language("SQL") String saveHoldings() { + return saveHolding; } @Override public @Language("SQL") String loadReceipts() { + return loadReceipts; } @Override public @Language("SQL") String saveReceipt() { + return saveReceipt; } @Override public @Language("SQL") String loadReceiptHolding() { + return loadReceiptHolding; } @Override public @Language("SQL") String saveReceiptHolding() { + return saveReceiptHolding; } @Override public @Language("SQL") String loadParticipants() { + return loadParticipants; } @Override public @Language("SQL") String saveParticipant() { + return saveParticipant; } @Override public @Language("SQL") String loadModifiers() { + return loadModifiers; } @Override public @Language("SQL") String saveModifier() { + return saveModifier; } @Override public String parseVersion(String version) { + return version.split("-")[1]; } @Override public String requirement() { + return requirement; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/io/storage/dialect/impl/MariaOutdatedDialect.java b/Core/src/net/tnemc/core/io/storage/dialect/impl/MariaOutdatedDialect.java index 52b132d7..de948834 100644 --- a/Core/src/net/tnemc/core/io/storage/dialect/impl/MariaOutdatedDialect.java +++ b/Core/src/net/tnemc/core/io/storage/dialect/impl/MariaOutdatedDialect.java @@ -95,6 +95,7 @@ public class MariaOutdatedDialect implements TNEDialect { protected final String prefix; public MariaOutdatedDialect(final String prefix) { + this.prefix = prefix; this.saveName = "INSERT INTO " + prefix + "player_names (uid, username) VALUES (?, ?) ON DUPLICATE KEY UPDATE username = ?"; @@ -104,298 +105,331 @@ public MariaOutdatedDialect(final String prefix) { this.loadAccount = "SELECT username, account_type, created, pin, status FROM " + prefix + "accounts WHERE uid = ?"; this.saveAccount = "INSERT INTO " + prefix + "accounts (uid, username, account_type, created, pin, status)" + - "VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE username = ?, pin = ?, status = ?"; + "VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE username = ?, pin = ?, status = ?"; this.loadNonPlayer = "SELECT owner AS owner FROM " + prefix + "non_players_accounts WHERE uid = ?"; this.saveNonPlayer = "INSERT INTO " + prefix + "non_players_accounts (uid, owner) VALUES (?, ?) " + - "ON DUPLICATE KEY UPDATE owner = ?"; + "ON DUPLICATE KEY UPDATE owner = ?"; this.loadPlayer = "SELECT last_online FROM " + prefix + "players_accounts WHERE uid = ?"; this.savePlayer = "INSERT INTO " + prefix + "players_accounts (uid, last_online) VALUES (?, ?) " + - "ON DUPLICATE KEY UPDATE last_online = ?"; + "ON DUPLICATE KEY UPDATE last_online = ?"; this.loadMembers = "SELECT uid AS uid, perm, perm_value FROM " + prefix + "account_members WHERE account = ?"; this.saveMember = "INSERT INTO " + prefix + "account_members (uid, account, perm, perm_value) VALUES (?, ?, ?, ?) " + - "ON DUPLICATE KEY UPDATE perm_value = ?"; + "ON DUPLICATE KEY UPDATE perm_value = ?"; this.loadHoldings = "SELECT region, currency AS currency, holdings_type, holdings FROM " + prefix + - "holdings WHERE uid = ? AND server = ?"; + "holdings WHERE uid = ? AND server = ?"; this.saveHolding = "INSERT INTO " + prefix + "holdings (uid, server, region, currency, holdings_type, holdings) " + - "VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE holdings = ?"; + "VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE holdings = ?"; this.loadReceipts = "SELECT uid AS uid, performed, receipt_type, receipt_source, receipt_source_type, archive, voided FROM " + - prefix + "receipts"; + prefix + "receipts"; this.saveReceipt = "INSERT INTO " + prefix + "receipts (uid, performed, receipt_type, receipt_source, " + - "receipt_source_type, archive, voided) " + - "VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE archive = ?, voided = ?"; + "receipt_source_type, archive, voided) " + + "VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE archive = ?, voided = ?"; this.loadReceiptHolding = "SELECT participant AS participant, ending, server, region, " + - "currency AS currency, holdings_type, holdings FROM " + - prefix + "receipts_holdings WHERE uid = ? AND participant = ? AND ending = ?"; + "currency AS currency, holdings_type, holdings FROM " + + prefix + "receipts_holdings WHERE uid = ? AND participant = ? AND ending = ?"; this.saveReceiptHolding = "INSERT INTO " + prefix + "receipts_holdings (uid, participant, ending, " + - "server, region, currency, holdings_type, holdings) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE uid=uid"; + "server, region, currency, holdings_type, holdings) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE uid=uid"; this.loadParticipants = "SELECT participant AS participant, participant_type, tax FROM " + - prefix + "receipts_participants WHERE uid = ?"; + prefix + "receipts_participants WHERE uid = ?"; this.saveParticipant = "INSERT INTO " + prefix + "receipts_participants (uid, participant, participant_type, tax) " + - "VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE uid=uid"; + "VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE uid=uid"; this.loadModifiers = "SELECT participant AS participant, participant_type, operation, region, " + - "currency AS currency, modifier FROM " + prefix + "receipts_modifiers WHERE uid = ? AND participant = ? AND participant_type = ?"; + "currency AS currency, modifier FROM " + prefix + "receipts_modifiers WHERE uid = ? AND participant = ? AND participant_type = ?"; this.saveModifier = "INSERT INTO " + prefix + "receipts_modifiers (uid, participant, participant_type, operation, region, currency, modifier) " + - "VALUES (?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE uid = uid"; + "VALUES (?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE uid = uid"; } @Override public String accountsTable() { + return "CREATE TABLE IF NOT EXISTS " + prefix + "accounts (\n" + - " uid VARCHAR(36) NOT NULL PRIMARY KEY,\n" + - " username VARCHAR(50) NOT NULL UNIQUE,\n" + - " account_type VARCHAR(30) NOT NULL,\n" + - " created DATETIME NOT NULL,\n" + - " pin VARCHAR(16),\n" + - " status VARCHAR(36)\n" + - " );"; + " uid VARCHAR(36) NOT NULL PRIMARY KEY,\n" + + " username VARCHAR(50) NOT NULL UNIQUE,\n" + + " account_type VARCHAR(30) NOT NULL,\n" + + " created DATETIME NOT NULL,\n" + + " pin VARCHAR(16),\n" + + " status VARCHAR(36)\n" + + " );"; } @Override public String accountsNonPlayerTable() { + return "CREATE TABLE IF NOT EXISTS " + prefix + "non_players_accounts (\n" + - " uid VARCHAR(36) NOT NULL UNIQUE,\n" + - " owner VARCHAR(36) NOT NULL,\n" + - " FOREIGN KEY(uid) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE,\n" + - " FOREIGN KEY(owner) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE\n" + - " );"; + " uid VARCHAR(36) NOT NULL UNIQUE,\n" + + " owner VARCHAR(36) NOT NULL,\n" + + " FOREIGN KEY(uid) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE,\n" + + " FOREIGN KEY(owner) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE\n" + + " );"; } @Override public String accountsPlayerTable() { + return "CREATE TABLE IF NOT EXISTS " + prefix + "players_accounts (\n" + - " uid VARCHAR(36) NOT NULL UNIQUE,\n" + - " last_online DATETIME NOT NULL,\n" + - " FOREIGN KEY(uid) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE\n" + - " );"; + " uid VARCHAR(36) NOT NULL UNIQUE,\n" + + " last_online DATETIME NOT NULL,\n" + + " FOREIGN KEY(uid) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE\n" + + " );"; } @Override public String accountMembersTable() { + return "CREATE TABLE IF NOT EXISTS " + prefix + "account_members (\n" + - " uid VARCHAR(36) NOT NULL,\n" + - " account VARCHAR(36) NOT NULL,\n" + - " perm VARCHAR(36) NOT NULL,\n" + - " perm_value TINYINT(1) NOT NULL,\n" + - " FOREIGN KEY(uid) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE,\n" + - " FOREIGN KEY(account) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE\n" + - " );"; + " uid VARCHAR(36) NOT NULL,\n" + + " account VARCHAR(36) NOT NULL,\n" + + " perm VARCHAR(36) NOT NULL,\n" + + " perm_value TINYINT(1) NOT NULL,\n" + + " FOREIGN KEY(uid) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE,\n" + + " FOREIGN KEY(account) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE\n" + + " );"; } @Override public String holdingsTable() { + return "CREATE TABLE IF NOT EXISTS " + prefix + "holdings (\n" + - " uid VARCHAR(36) NOT NULL,\n" + - " server VARCHAR(40) NOT NULL,\n" + - " region VARCHAR(40) NOT NULL,\n" + - " currency VARCHAR(36) NOT NULL,\n" + - " holdings_type VARCHAR(30) NOT NULL,\n" + - " holdings DECIMAL(49, 4) NOT NULL,\n" + - " UNIQUE(`uid`, `server`, `region`, `currency`, `holdings_type`),\n" + - " FOREIGN KEY(uid) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE\n" + - " );"; + " uid VARCHAR(36) NOT NULL,\n" + + " server VARCHAR(40) NOT NULL,\n" + + " region VARCHAR(40) NOT NULL,\n" + + " currency VARCHAR(36) NOT NULL,\n" + + " holdings_type VARCHAR(30) NOT NULL,\n" + + " holdings DECIMAL(49, 4) NOT NULL,\n" + + " UNIQUE(`uid`, `server`, `region`, `currency`, `holdings_type`),\n" + + " FOREIGN KEY(uid) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE\n" + + " );"; } @Override public String receiptsTable() { + return "CREATE TABLE IF NOT EXISTS " + prefix + "receipts (\n" + - " uid VARCHAR(36) NOT NULL UNIQUE,\n" + - " performed DATETIME NOT NULL,\n" + - " receipt_type VARCHAR(30) NOT NULL,\n" + - " receipt_source VARCHAR(60) NOT NULL,\n" + - " receipt_source_type VARCHAR(30) NOT NULL,\n" + - " archive TINYINT(1) NOT NULL,\n" + - " voided TINYINT(1) NOT NULL\n" + - " );"; + " uid VARCHAR(36) NOT NULL UNIQUE,\n" + + " performed DATETIME NOT NULL,\n" + + " receipt_type VARCHAR(30) NOT NULL,\n" + + " receipt_source VARCHAR(60) NOT NULL,\n" + + " receipt_source_type VARCHAR(30) NOT NULL,\n" + + " archive TINYINT(1) NOT NULL,\n" + + " voided TINYINT(1) NOT NULL\n" + + " );"; } @Override public String receiptsHoldingsTable() { + return "CREATE TABLE IF NOT EXISTS " + prefix + "receipts_holdings (\n" + - " uid VARCHAR(36) NOT NULL UNIQUE,\n" + - " participant VARCHAR(36) NOT NULL,\n" + - " ending TINYINT(1) NOT NULL,\n" + - " server VARCHAR(40) NOT NULL,\n" + - " region VARCHAR(40) NOT NULL,\n" + - " currency VARCHAR(36) NOT NULL,\n" + - " holdings_type VARCHAR(30) NOT NULL,\n" + - " holdings DECIMAL(49, 4) NOT NULL,\n" + - " FOREIGN KEY(uid) REFERENCES " + prefix + "receipts(uid) ON DELETE CASCADE\n" + - " );"; + " uid VARCHAR(36) NOT NULL UNIQUE,\n" + + " participant VARCHAR(36) NOT NULL,\n" + + " ending TINYINT(1) NOT NULL,\n" + + " server VARCHAR(40) NOT NULL,\n" + + " region VARCHAR(40) NOT NULL,\n" + + " currency VARCHAR(36) NOT NULL,\n" + + " holdings_type VARCHAR(30) NOT NULL,\n" + + " holdings DECIMAL(49, 4) NOT NULL,\n" + + " FOREIGN KEY(uid) REFERENCES " + prefix + "receipts(uid) ON DELETE CASCADE\n" + + " );"; } @Override public String receiptsParticipantsTable() { + return "CREATE TABLE IF NOT EXISTS " + prefix + "receipts_participants (\n" + - " uid VARCHAR(36) NOT NULL PRIMARY KEY,\n" + - " participant VARCHAR(36) NOT NULL,\n" + - " participant_type VARCHAR(10) NOT NULL,\n" + - " tax DECIMAL(49, 4) NOT NULL,\n" + - " FOREIGN KEY(uid) REFERENCES " + prefix + "receipts(uid) ON DELETE CASCADE\n" + - " );"; + " uid VARCHAR(36) NOT NULL PRIMARY KEY,\n" + + " participant VARCHAR(36) NOT NULL,\n" + + " participant_type VARCHAR(10) NOT NULL,\n" + + " tax DECIMAL(49, 4) NOT NULL,\n" + + " FOREIGN KEY(uid) REFERENCES " + prefix + "receipts(uid) ON DELETE CASCADE\n" + + " );"; } @Override public String receiptsModifiersTable() { + return "CREATE TABLE IF NOT EXISTS " + prefix + "receipts_modifiers (\n" + - " uid VARCHAR(36) NOT NULL PRIMARY KEY,\n" + - " participant VARCHAR(36) NOT NULL,\n" + - " participant_type VARCHAR(10) NOT NULL,\n" + - " operation VARCHAR(10) NOT NULL,\n" + - " region VARCHAR(40) NOT NULL,\n" + - " currency VARCHAR(36) NOT NULL,\n" + - " modifier DECIMAL(49, 4) NOT NULL," + - " FOREIGN KEY(uid) REFERENCES " + prefix + "receipts(uid) ON DELETE CASCADE" + - " );"; + " uid VARCHAR(36) NOT NULL PRIMARY KEY,\n" + + " participant VARCHAR(36) NOT NULL,\n" + + " participant_type VARCHAR(10) NOT NULL,\n" + + " operation VARCHAR(10) NOT NULL,\n" + + " region VARCHAR(40) NOT NULL,\n" + + " currency VARCHAR(36) NOT NULL,\n" + + " modifier DECIMAL(49, 4) NOT NULL," + + " FOREIGN KEY(uid) REFERENCES " + prefix + "receipts(uid) ON DELETE CASCADE" + + " );"; } @Override public @Language("SQL") String accountPurge(final int days) { + final String acc = prefix + "accounts"; final String players = prefix + "players_accounts"; return "DELETE FROM " + acc + - "WHERE uid IN (" + - " SELECT uid FROM " + players + - " WHERE EXISTS (" + - " SELECT *" + - " FROM " + acc + - " WHERE " + acc + ".uid = " + players + ".uid" + - " AND DATEDIFF(DAY, " + players + ".last_online, NOW()) >= " + days + - " )" + - ");"; + "WHERE uid IN (" + + " SELECT uid FROM " + players + + " WHERE EXISTS (" + + " SELECT *" + + " FROM " + acc + + " WHERE " + acc + ".uid = " + players + ".uid" + + " AND DATEDIFF(DAY, " + players + ".last_online, NOW()) >= " + days + + " )" + + ");"; } @Override public @Language("SQL") String receiptPurge(final int days) { + return "DELETE FROM " + prefix + "receipts WHERE archived = false" + - "AND DATEDIFF(CURDATE(), performed) >= " + days; + "AND DATEDIFF(CURDATE(), performed) >= " + days; } @Override public @Language("SQL") String saveName() { + return saveName; } @Override public @Language("SQL") String loadAccounts() { + return loadAccounts; } @Override public @Language("SQL") String loadAccount() { + return loadAccount; } @Override public @Language("SQL") String saveAccount() { + return saveAccount; } @Override public @Language("SQL") String loadNonPlayer() { + return loadNonPlayer; } @Override public @Language("SQL") String saveNonPlayer() { + return saveNonPlayer; } @Override public @Language("SQL") String loadPlayer() { + return loadPlayer; } @Override public @Language("SQL") String savePlayer() { + return savePlayer; } @Override public @Language("SQL") String loadMembers() { + return loadMembers; } @Override public @Language("SQL") String saveMembers() { + return saveMember; } @Override public @Language("SQL") String loadHoldings() { + return loadHoldings; } @Override public @Language("SQL") String saveHoldings() { + return saveHolding; } @Override public @Language("SQL") String loadReceipts() { + return loadReceipts; } @Override public @Language("SQL") String saveReceipt() { + return saveReceipt; } @Override public @Language("SQL") String loadReceiptHolding() { + return loadReceiptHolding; } @Override public @Language("SQL") String saveReceiptHolding() { + return saveReceiptHolding; } @Override public @Language("SQL") String loadParticipants() { + return loadParticipants; } @Override public @Language("SQL") String saveParticipant() { + return saveParticipant; } @Override public @Language("SQL") String loadModifiers() { + return loadModifiers; } @Override public @Language("SQL") String saveModifier() { + return saveModifier; } @Override public String parseVersion(String version) { + return version.split("-")[1]; } @Override public String requirement() { + return requirement; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/io/storage/dialect/impl/MySQLDialect.java b/Core/src/net/tnemc/core/io/storage/dialect/impl/MySQLDialect.java index b92bd34d..55b3a153 100644 --- a/Core/src/net/tnemc/core/io/storage/dialect/impl/MySQLDialect.java +++ b/Core/src/net/tnemc/core/io/storage/dialect/impl/MySQLDialect.java @@ -95,6 +95,7 @@ public class MySQLDialect implements TNEDialect { protected final String prefix; public MySQLDialect(final String prefix) { + this.prefix = prefix; this.saveName = "INSERT INTO " + prefix + "player_names (uid, username) VALUES (UUID_TO_BIN(?), ?) ON DUPLICATE KEY UPDATE username = ?"; @@ -149,7 +150,7 @@ public MySQLDialect(final String prefix) { "VALUES (UUID_TO_BIN(?), UUID_TO_BIN(?), ?, ?) ON DUPLICATE KEY UPDATE uid=uid"; this.loadModifiers = "SELECT BIN_TO_UUID(participant) AS participant, participant_type, operation, region, " + - "BIN_TO_UUID(currency) AS currency, modifier FROM " + prefix + "receipts_modifiers WHERE uid = UUID_TO_BIN(?) AND participant = UUID_TO_BIN(?) AND participant_type = ?"; + "BIN_TO_UUID(currency) AS currency, modifier FROM " + prefix + "receipts_modifiers WHERE uid = UUID_TO_BIN(?) AND participant = UUID_TO_BIN(?) AND participant_type = ?"; this.saveModifier = "INSERT INTO " + prefix + "receipts_modifiers (uid, participant, participant_type, operation, region, currency, modifier) " + "VALUES (UUID_TO_BIN(?), UUID_TO_BIN(?), ?, ?, ?, UUID_TO_BIN(?), ?) ON DUPLICATE KEY UPDATE uid = uid"; @@ -158,240 +159,272 @@ public MySQLDialect(final String prefix) { @Override public String accountsTable() { + return "CREATE TABLE IF NOT EXISTS " + prefix + "accounts (\n" + - " uid BINARY(16) NOT NULL PRIMARY KEY,\n" + - " username VARCHAR(50) NOT NULL UNIQUE,\n" + - " account_type VARCHAR(30) NOT NULL,\n" + - " created DATETIME NOT NULL,\n" + - " pin VARCHAR(16),\n" + - " status VARCHAR(36)\n" + - " );"; + " uid BINARY(16) NOT NULL PRIMARY KEY,\n" + + " username VARCHAR(50) NOT NULL UNIQUE,\n" + + " account_type VARCHAR(30) NOT NULL,\n" + + " created DATETIME NOT NULL,\n" + + " pin VARCHAR(16),\n" + + " status VARCHAR(36)\n" + + " );"; } @Override public String accountsNonPlayerTable() { + return "CREATE TABLE IF NOT EXISTS " + prefix + "non_players_accounts (\n" + - " uid BINARY(16) NOT NULL UNIQUE,\n" + - " owner BINARY(16) NOT NULL,\n" + - " FOREIGN KEY(uid) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE,\n" + - " FOREIGN KEY(owner) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE\n" + - " );"; + " uid BINARY(16) NOT NULL UNIQUE,\n" + + " owner BINARY(16) NOT NULL,\n" + + " FOREIGN KEY(uid) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE,\n" + + " FOREIGN KEY(owner) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE\n" + + " );"; } @Override public String accountsPlayerTable() { + return "CREATE TABLE IF NOT EXISTS " + prefix + "players_accounts (\n" + - " uid BINARY(16) NOT NULL UNIQUE,\n" + - " last_online DATETIME NOT NULL,\n" + - " FOREIGN KEY(uid) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE\n" + - " );"; + " uid BINARY(16) NOT NULL UNIQUE,\n" + + " last_online DATETIME NOT NULL,\n" + + " FOREIGN KEY(uid) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE\n" + + " );"; } @Override public String accountMembersTable() { + return "CREATE TABLE IF NOT EXISTS " + prefix + "account_members (\n" + - " uid BINARY(16) NOT NULL,\n" + - " account BINARY(16) NOT NULL,\n" + - " perm VARCHAR(36) NOT NULL,\n" + - " perm_value TINYINT(1) NOT NULL,\n" + - " FOREIGN KEY(uid) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE,\n" + - " FOREIGN KEY(account) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE\n" + - " );"; + " uid BINARY(16) NOT NULL,\n" + + " account BINARY(16) NOT NULL,\n" + + " perm VARCHAR(36) NOT NULL,\n" + + " perm_value TINYINT(1) NOT NULL,\n" + + " FOREIGN KEY(uid) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE,\n" + + " FOREIGN KEY(account) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE\n" + + " );"; } @Override public String holdingsTable() { + return "CREATE TABLE IF NOT EXISTS " + prefix + "holdings (\n" + - " uid BINARY(16) NOT NULL,\n" + - " server VARCHAR(40) NOT NULL,\n" + - " region VARCHAR(40) NOT NULL,\n" + - " currency BINARY(16) NOT NULL,\n" + - " holdings_type VARCHAR(30) NOT NULL,\n" + - " holdings DECIMAL(49, 4) NOT NULL,\n" + - " UNIQUE(`uid`, `server`, `region`, `currency`, `holdings_type`),\n" + - " FOREIGN KEY(uid) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE\n" + - " );"; + " uid BINARY(16) NOT NULL,\n" + + " server VARCHAR(40) NOT NULL,\n" + + " region VARCHAR(40) NOT NULL,\n" + + " currency BINARY(16) NOT NULL,\n" + + " holdings_type VARCHAR(30) NOT NULL,\n" + + " holdings DECIMAL(49, 4) NOT NULL,\n" + + " UNIQUE(`uid`, `server`, `region`, `currency`, `holdings_type`),\n" + + " FOREIGN KEY(uid) REFERENCES " + prefix + "accounts(uid) ON DELETE CASCADE\n" + + " );"; } @Override public String receiptsTable() { + return "CREATE TABLE IF NOT EXISTS " + prefix + "receipts (\n" + - " uid BINARY(16) NOT NULL UNIQUE,\n" + - " performed DATETIME NOT NULL,\n" + - " receipt_type VARCHAR(30) NOT NULL,\n" + - " receipt_source VARCHAR(60) NOT NULL,\n" + - " receipt_source_type VARCHAR(30) NOT NULL,\n" + - " archive TINYINT(1) NOT NULL,\n" + - " voided TINYINT(1) NOT NULL\n" + - " );"; + " uid BINARY(16) NOT NULL UNIQUE,\n" + + " performed DATETIME NOT NULL,\n" + + " receipt_type VARCHAR(30) NOT NULL,\n" + + " receipt_source VARCHAR(60) NOT NULL,\n" + + " receipt_source_type VARCHAR(30) NOT NULL,\n" + + " archive TINYINT(1) NOT NULL,\n" + + " voided TINYINT(1) NOT NULL\n" + + " );"; } @Override public String receiptsHoldingsTable() { + return "CREATE TABLE IF NOT EXISTS " + prefix + "receipts_holdings (\n" + - " uid BINARY(16) NOT NULL UNIQUE,\n" + - " participant BINARY(16) NOT NULL,\n" + - " ending TINYINT(1) NOT NULL,\n" + - " server VARCHAR(40) NOT NULL,\n" + - " region VARCHAR(40) NOT NULL,\n" + - " currency BINARY(16) NOT NULL,\n" + - " holdings_type VARCHAR(30) NOT NULL,\n" + - " holdings DECIMAL(49, 4) NOT NULL,\n" + - " FOREIGN KEY(uid) REFERENCES " + prefix + "receipts(uid) ON DELETE CASCADE\n" + - " );"; + " uid BINARY(16) NOT NULL UNIQUE,\n" + + " participant BINARY(16) NOT NULL,\n" + + " ending TINYINT(1) NOT NULL,\n" + + " server VARCHAR(40) NOT NULL,\n" + + " region VARCHAR(40) NOT NULL,\n" + + " currency BINARY(16) NOT NULL,\n" + + " holdings_type VARCHAR(30) NOT NULL,\n" + + " holdings DECIMAL(49, 4) NOT NULL,\n" + + " FOREIGN KEY(uid) REFERENCES " + prefix + "receipts(uid) ON DELETE CASCADE\n" + + " );"; } @Override public String receiptsParticipantsTable() { + return "CREATE TABLE IF NOT EXISTS " + prefix + "receipts_participants (\n" + - " uid BINARY(16) NOT NULL PRIMARY KEY,\n" + - " participant BINARY(16) NOT NULL,\n" + - " participant_type VARCHAR(10) NOT NULL,\n" + - " tax DECIMAL(49, 4) NOT NULL,\n" + - " FOREIGN KEY(uid) REFERENCES " + prefix + "receipts(uid) ON DELETE CASCADE\n" + - " );"; + " uid BINARY(16) NOT NULL PRIMARY KEY,\n" + + " participant BINARY(16) NOT NULL,\n" + + " participant_type VARCHAR(10) NOT NULL,\n" + + " tax DECIMAL(49, 4) NOT NULL,\n" + + " FOREIGN KEY(uid) REFERENCES " + prefix + "receipts(uid) ON DELETE CASCADE\n" + + " );"; } @Override public String receiptsModifiersTable() { + return "CREATE TABLE IF NOT EXISTS " + prefix + "receipts_modifiers (\n" + - " uid BINARY(16) NOT NULL PRIMARY KEY,\n" + - " participant BINARY(16) NOT NULL,\n" + - " participant_type VARCHAR(10) NOT NULL,\n" + - " operation VARCHAR(10) NOT NULL,\n" + - " region VARCHAR(40) NOT NULL,\n" + - " currency BINARY(16) NOT NULL,\n" + - " modifier DECIMAL(49, 4) NOT NULL," + - " FOREIGN KEY(uid) REFERENCES " + prefix + "receipts(uid) ON DELETE CASCADE" + - " );"; + " uid BINARY(16) NOT NULL PRIMARY KEY,\n" + + " participant BINARY(16) NOT NULL,\n" + + " participant_type VARCHAR(10) NOT NULL,\n" + + " operation VARCHAR(10) NOT NULL,\n" + + " region VARCHAR(40) NOT NULL,\n" + + " currency BINARY(16) NOT NULL,\n" + + " modifier DECIMAL(49, 4) NOT NULL," + + " FOREIGN KEY(uid) REFERENCES " + prefix + "receipts(uid) ON DELETE CASCADE" + + " );"; } @Override public @Language("SQL") String accountPurge(final int days) { + final String acc = prefix + "accounts"; final String players = prefix + "players_accounts"; return "DELETE FROM " + acc + - "WHERE uid IN (" + - " SELECT uid FROM " + players + - " WHERE EXISTS (" + - " SELECT *" + - " FROM " + acc + - " WHERE " + acc + ".uid = " + players + ".uid" + - " AND DATEDIFF(DAY, " + players + ".last_online, NOW()) >= " + days + - " )" + - ");"; + "WHERE uid IN (" + + " SELECT uid FROM " + players + + " WHERE EXISTS (" + + " SELECT *" + + " FROM " + acc + + " WHERE " + acc + ".uid = " + players + ".uid" + + " AND DATEDIFF(DAY, " + players + ".last_online, NOW()) >= " + days + + " )" + + ");"; } @Override public @Language("SQL") String receiptPurge(final int days) { + return "DELETE FROM " + prefix + "receipts WHERE archived = false" + "AND DATEDIFF(CURDATE(), performed) >= " + days; } @Override public @Language("SQL") String saveName() { + return saveName; } @Override public @Language("SQL") String loadAccounts() { + return loadAccounts; } @Override public @Language("SQL") String loadAccount() { + return loadAccount; } @Override public @Language("SQL") String saveAccount() { + return saveAccount; } @Override public @Language("SQL") String loadNonPlayer() { + return loadNonPlayer; } @Override public @Language("SQL") String saveNonPlayer() { + return saveNonPlayer; } @Override public @Language("SQL") String loadPlayer() { + return loadPlayer; } @Override public @Language("SQL") String savePlayer() { + return savePlayer; } @Override public @Language("SQL") String loadMembers() { + return loadMembers; } @Override public @Language("SQL") String saveMembers() { + return saveMember; } @Override public @Language("SQL") String loadHoldings() { + return loadHoldings; } @Override public @Language("SQL") String saveHoldings() { + return saveHolding; } @Override public @Language("SQL") String loadReceipts() { + return loadReceipts; } @Override public @Language("SQL") String saveReceipt() { + return saveReceipt; } @Override public @Language("SQL") String loadReceiptHolding() { + return loadReceiptHolding; } @Override public @Language("SQL") String saveReceiptHolding() { + return saveReceiptHolding; } @Override public @Language("SQL") String loadParticipants() { + return loadParticipants; } @Override public @Language("SQL") String saveParticipant() { + return saveParticipant; } @Override public @Language("SQL") String loadModifiers() { + return loadModifiers; } @Override public @Language("SQL") String saveModifier() { + return saveModifier; } @Override public String requirement() { + return requirement; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/io/yaml/YamlStorageManager.java b/Core/src/net/tnemc/core/io/yaml/YamlStorageManager.java index 038293ff..8b24540a 100644 --- a/Core/src/net/tnemc/core/io/yaml/YamlStorageManager.java +++ b/Core/src/net/tnemc/core/io/yaml/YamlStorageManager.java @@ -32,18 +32,22 @@ public class YamlStorageManager { private final Map inUsage = new ConcurrentHashMap<>(); public Map getInUsage() { + return inUsage; } public void add(final String file) { + inUsage.put(file, true); } public boolean inUse(final String file) { + return inUsage.containsKey(file); } public void remove(final String file) { + inUsage.remove(file); } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/manager/AccountManager.java b/Core/src/net/tnemc/core/manager/AccountManager.java index 3c01dc75..2b3d766e 100644 --- a/Core/src/net/tnemc/core/manager/AccountManager.java +++ b/Core/src/net/tnemc/core/manager/AccountManager.java @@ -55,8 +55,8 @@ /** * Manages everything related to accounts. * - * @see Account * @author creatorfromhell + * @see Account * @since 0.1.2.0 */ public class AccountManager { @@ -85,33 +85,42 @@ public class AccountManager { /** * Used to create a new non-player account based on the provided name. + * * @param name The name to use for this account. + * * @return A correlating {@link AccountAPIResponse response} containing the results. */ public AccountAPIResponse createAccount(final String name) { + return createAccount(name, name, true); } /** * Used to create a new account based on the provided identifier and name. + * * @param identifier The identifier to use for the creation, if this is a player then this should * be the String value of the UUID for that player. - * @param name The name to use for this account. + * @param name The name to use for this account. + * * @return A correlating {@link AccountAPIResponse response} containing the results. */ public AccountAPIResponse createAccount(final String identifier, final String name) { + return createAccount(identifier, name, false); } /** * Used to create a new account based on the provided identifier and name. + * * @param identifier The identifier to use for the creation, if this is a player then this should * be the String value of the UUID for that player. - * @param name The name to use for this account. - * @param nonPlayer True if the new account should be a non-player account. + * @param name The name to use for this account. + * @param nonPlayer True if the new account should be a non-player account. + * * @return A correlating {@link AccountAPIResponse response} containing the results. */ public AccountAPIResponse createAccount(final String identifier, final String name, boolean nonPlayer) { + PluginCore.log().debug("Create Account Called! ID: " + identifier + " Name: " + name); if(name.contains("§")) { PluginCore.log().debug("==== AccountAPIResponse with color code! ====", DebugLevel.DEVELOPER); @@ -215,6 +224,7 @@ public AccountAPIResponse createAccount(final String identifier, final String na * {@link #types} map for a suitable alternative. * * @param name The name to use for the creation. + * * @return An Optional containing the new account class if it was able to be created, otherwise an * empty Optional. */ @@ -225,10 +235,10 @@ public Optional createNonPlayerAccount(final String name) { if(entry.getValue().apply(name)) { try { return Optional.of(entry.getKey().getDeclaredConstructor(UUID.class, String.class) - .newInstance(UUID.randomUUID(), name)); + .newInstance(UUID.randomUUID(), name)); } catch(Exception e) { PluginCore.log().error("An error occured while trying to create a new NonPlayer Account" + - "for : " + name, e, DebugLevel.STANDARD); + "for : " + name, e, DebugLevel.STANDARD); } } } @@ -241,9 +251,11 @@ public Optional createNonPlayerAccount(final String name) { * Used to delete an {@link Account account} from an identifier. * * @param identifier The identifier to use for the search. + * * @return The corresponding {@link EconomyResponse response}. */ public EconomyResponse deleteAccount(@NotNull final UUID identifier) { + return deleteAccount(identifier.toString()); } @@ -251,9 +263,11 @@ public EconomyResponse deleteAccount(@NotNull final UUID identifier) { * Used to delete an {@link Account account} from an identifier. * * @param identifier The identifier to use for the search. + * * @return The corresponding {@link EconomyResponse response}. */ public EconomyResponse deleteAccount(@NotNull final String identifier) { + if(!accounts.containsKey(identifier)) { return AccountResponse.DOESNT_EXIST; } @@ -267,21 +281,27 @@ public EconomyResponse deleteAccount(@NotNull final String identifier) { /** * Used to find an {@link Account account} from a {@link UUID unique identifier}. + * * @param id The id to use in the search. + * * @return An optional containing the {@link Account account} if it exists, otherwise an empty * optional. */ public Optional findAccount(final UUID id) { + return Optional.ofNullable(accounts.get(id.toString())); } /** * Used to find an {@link PlayerAccount account} from a {@link UUID unique identifier}. + * * @param id The id to use in the search. - * @return An optional containing the {@link PlayerAccount account} if it exists, otherwise an empty - * optional. + * + * @return An optional containing the {@link PlayerAccount account} if it exists, otherwise an + * empty optional. */ public Optional findPlayerAccount(final UUID id) { + final Account account = accounts.get(id.toString()); if((account instanceof PlayerAccount)) { @@ -293,7 +313,9 @@ public Optional findPlayerAccount(final UUID id) { /** * Used to find an {@link Account account} from a string identifier, this could be a name or a * different identifier. + * * @param identifier The identifier to use in the search. + * * @return An optional containing the {@link Account account} if it exists, otherwise an empty * optional. */ @@ -315,6 +337,7 @@ public Optional findAccount(final String identifier) { } public AccountStatus findStatus(final String identifier) { + if(statuses.containsKey(identifier)) { return statuses.get(identifier); } @@ -323,19 +346,23 @@ public AccountStatus findStatus(final String identifier) { /** * Adds a new {@link AccountStatus} status. + * * @param status The account status to add */ public void addAccountStatus(final AccountStatus status) { + statuses.put(status); } /** * Adds a new {@link Account} type. These should extend the {@link SharedAccount}. - * @param type The class for this type. - * @param check The function that should be used to check if a given String identifier, usually name, - * is valid for this account type. + * + * @param type The class for this type. + * @param check The function that should be used to check if a given String identifier, usually + * name, is valid for this account type. */ public void addAccountType(final Class type, Function check) { + types.put(type, check); } @@ -350,14 +377,17 @@ public void addDefaultTypes() { } public void addSwap(final String swapType, final UUID account, final UUID swapAccount) { + accountSwaps.put(swapType + ":" + account.toString(), swapAccount); } public void removeSwap(final String swapType, final UUID account) { + accountSwaps.remove(swapType + ":" + account.toString()); } public UUID swap(final String swapType, final UUID account) { + return accountSwaps.getOrDefault(swapType + ":" + account.toString(), account); } @@ -372,22 +402,27 @@ public void addDefaultStatuses() { } public EnhancedHashMap getStatuses() { + return statuses; } public EnhancedHashMap getAccounts() { + return accounts; } public UUIDProvider uuidProvider() { + return uuidProvider; } public List getLoading() { + return loading; } public List getImporting() { + return importing; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/manager/CurrencyManager.java b/Core/src/net/tnemc/core/manager/CurrencyManager.java index 93b20d32..a799acc8 100644 --- a/Core/src/net/tnemc/core/manager/CurrencyManager.java +++ b/Core/src/net/tnemc/core/manager/CurrencyManager.java @@ -56,7 +56,8 @@ * @since 0.1.2.0 */ public class CurrencyManager { - public static final BigDecimal largestSupported= new BigDecimal("900000000000000000000000000000000000000000000"); + + public static final BigDecimal largestSupported = new BigDecimal("900000000000000000000000000000000000000000000"); private final Map currencies = new HashMap<>(); private final Map curIDMap = new HashMap<>(); @@ -68,6 +69,7 @@ public class CurrencyManager { private boolean retry = false; public CurrencyManager() { + addType(new ExperienceType()); addType(new ExperienceLevelType()); addType(new ItemType()); @@ -76,10 +78,12 @@ public CurrencyManager() { } public boolean load(final File parent) { + return load(parent, true); } public boolean load(final File parent, boolean reset) { + saver.saveCurrenciesUUID(new File(parent, "currency")); if(reset) { currencies.clear(); @@ -129,30 +133,37 @@ public boolean load(final File parent, boolean reset) { /** * Saves all currency UUIDs only. + * * @param parent The directory used for saving. */ public void saveCurrenciesUUID(final File parent) { + saver.saveCurrenciesUUID(new File(parent, "currency")); } public CurrencyLoader getLoader() { + return loader; } public void setLoader(CurrencyLoader loader) { + this.loader = loader; } public CurrencySaver getSaver() { + return saver; } public void setSaver(CurrencySaver saver) { + this.saver = saver; } /** * Used to add a currency. + * * @param currency The currency to add. */ public void addCurrency(final Currency currency) { @@ -164,6 +175,7 @@ public void addCurrency(final Currency currency) { /** * Used to get the default currency. This could be the default currency for the server globally or * for the default world if the implementation supports multi-world. + * * @return The currency that is the default for the server if multi-world support is not available * otherwise the default for the default world. * @@ -183,8 +195,10 @@ public Currency getDefaultCurrency() { /** * Used to get the default currency for the specified world if this implementation has multi-world * support, otherwise the default currency for the server. + * * @param region The region to get the default currency for. This could be a world, biomes, or a * third party based region. + * * @return The default currency for the specified world if this implementation has multi-world * support, otherwise the default currency for the server. * @@ -203,11 +217,14 @@ public Currency getDefaultCurrency(@NotNull String region) { /** * Used to get a set of every {@link Currency} object that is available in the specified world if - * this implementation has multi-world support, otherwise all {@link Currency} objects for the server. - * @param region The region to get the currencies for. This could be a world, biomes, or a - * third party based region. - * @return A set of every {@link Currency} object that is available in the specified world if - * this implementation has multi-world support, otherwise all {@link Currency} objects for the server. + * this implementation has multi-world support, otherwise all {@link Currency} objects for the + * server. + * + * @param region The region to get the currencies for. This could be a world, biomes, or a third + * party based region. + * + * @return A set of every {@link Currency} object that is available in the specified world if this + * implementation has multi-world support, otherwise all {@link Currency} objects for the server. * * @since 0.1.2.0 */ @@ -225,20 +242,26 @@ public Collection getCurrencies(@NotNull String region) { /** * Used to find a {@link Currency currency} based on its unique identifier. + * * @param identifier The identifier to look for. + * * @return An Optional containing the currency if it exists, otherwise an empty Optional. */ public Optional findCurrency(final UUID identifier) { + return Optional.ofNullable(currencies.get(identifier)); } /** * Used to find a {@link Currency currency} based on an item. + * * @param item The item to use for this search. + * * @return An Optional containing the currency if this item is a valid currency item, otherwise an * empty Optional. */ public Optional findCurrencyByItem(final AbstractItemStack item) { + for(Currency currency : currencies.values()) { if(currency instanceof ItemCurrency) { @@ -254,11 +277,14 @@ public Optional findCurrencyByItem(final AbstractItemStack item) { /** * Used to find a {@link Currency currency} based on a material. + * * @param material The material to use for this search. + * * @return An Optional containing the currency if this item is a valid currency item, otherwise an * empty Optional. */ public Optional findCurrencyByMaterial(final String material) { + for(Currency currency : currencies.values()) { if(currency instanceof ItemCurrency) { @@ -274,10 +300,13 @@ public Optional findCurrencyByMaterial(final String material) { /** * Used to find a {@link Currency currency} based on its user-friendly identifier. + * * @param identifier The identifier to look for. + * * @return An Optional containing the currency if it exists, otherwise an empty Optional. */ public Optional findCurrency(final String identifier) { + try { return Optional.ofNullable(currencies.get(UUID.fromString(identifier))); @@ -295,24 +324,30 @@ public Optional findCurrency(final String identifier) { } /** - * Used to find a {@link Currency currency} based on its {@link UUID identifier}, or a new Currency - * object if the specified identifier doesn't exist. + * Used to find a {@link Currency currency} based on its {@link UUID identifier}, or a new + * Currency object if the specified identifier doesn't exist. + * * @param identifier The identifier to look for. + * * @return The currency object if found; Otherwise a new currency object. */ public Currency findOrDefault(final UUID identifier) { + return findOrDefault(identifier, false); } /** - * Used to find a {@link Currency currency} based on its {@link UUID identifier}, or a new Currency - * object if the specified identifier doesn't exist. + * Used to find a {@link Currency currency} based on its {@link UUID identifier}, or a new + * Currency object if the specified identifier doesn't exist. + * * @param identifier The identifier to look for. - * @param item True if this should return an {@link ItemCurrency} object if the specified identifier - * doesn't exist. + * @param item True if this should return an {@link ItemCurrency} object if the specified + * identifier doesn't exist. + * * @return The currency object if found; Otherwise a new currency object. */ public Currency findOrDefault(final UUID identifier, final boolean item) { + if(identifier != null && currencies.containsKey(identifier)) { return currencies.get(identifier); } @@ -323,39 +358,49 @@ public Currency findOrDefault(final UUID identifier, final boolean item) { } public LinkedList currencies() { + return new LinkedList<>(currencies.values()); } public Map getTypes() { + return types; } /** * Used to add a currency type. + * * @param type The currency type to add. */ public void addType(final CurrencyType type) { + types.put(type.name(), type); } /** * Used to find a currency type based on its identifier. + * * @param identifier The identifier to look for. + * * @return An Optional containing the currency type if it exists, otherwise an empty Optional. */ public Optional findType(final String identifier) { + return Optional.ofNullable(types.get(identifier)); } public CurrencyType findTypeOrDefault(final String identifier) { + return types.getOrDefault(identifier, types.get("virtual")); } public Map getCurIDMap() { + return curIDMap; } public Map getCurrencies() { + return currencies; } diff --git a/Core/src/net/tnemc/core/manager/ReceiptManager.java b/Core/src/net/tnemc/core/manager/ReceiptManager.java index a19f59cf..64054e68 100644 --- a/Core/src/net/tnemc/core/manager/ReceiptManager.java +++ b/Core/src/net/tnemc/core/manager/ReceiptManager.java @@ -30,12 +30,11 @@ import java.util.stream.Collectors; /** - * Manages receipts for transactions. Provides methods to add, retrieve, and remove receipts - * by their UUID, time, and within specific time ranges. - * - * @see Receipt + * Manages receipts for transactions. Provides methods to add, retrieve, and remove receipts by + * their UUID, time, and within specific time ranges. * * @author creatorfromhell + * @see Receipt * @since 0.1.3.0 */ public class ReceiptManager { @@ -48,6 +47,7 @@ public class ReceiptManager { * @param receipt The receipt to be added. */ public void log(final Receipt receipt) { + receipts.put(receipt.getId(), receipt); } @@ -55,9 +55,11 @@ public void log(final Receipt receipt) { * Retrieves a receipt by its UUID. * * @param id The UUID of the receipt. + * * @return The receipt with the specified UUID, or null if not found. */ public Optional getReceiptByUUID(final UUID id) { + return Optional.ofNullable(receipts.get(id)); } @@ -65,12 +67,14 @@ public Optional getReceiptByUUID(final UUID id) { * Retrieves receipts involving a specific transaction participant. * * @param participantUUID The UUID of the transaction participant. + * * @return A list of receipts that involve the specified participant. */ public List getReceiptsByParticipant(final UUID participantUUID) { + return receipts.values().stream() .filter(receipt->(receipt.getFrom() != null && receipt.getFrom().getId().equals(participantUUID)) || - (receipt.getTo() != null && receipt.getTo().getId().equals(participantUUID))) + (receipt.getTo() != null && receipt.getTo().getId().equals(participantUUID))) .collect(Collectors.toList()); } @@ -78,11 +82,13 @@ public List getReceiptsByParticipant(final UUID participantUUID) { * Retrieves receipts by their time. * * @param time The time of the receipts. + * * @return A list of receipts that occurred at the specified time. */ public List getReceiptByTime(final long time) { + return receipts.values().stream() - .filter(receipt -> receipt.getTime() == time) + .filter(receipt->receipt.getTime() == time) .collect(Collectors.toList()); } @@ -90,53 +96,63 @@ public List getReceiptByTime(final long time) { * Retrieves receipts that occurred between two time periods. * * @param startTime The start time of the range. - * @param endTime The end time of the range. + * @param endTime The end time of the range. + * * @return A TreeMap where the key is the receipt time and the value is the Receipt object. */ public TreeMap getReceiptsBetweenTimes(final long startTime, final long endTime) { + return receipts.values().stream() - .filter(receipt -> receipt.getTime() >= startTime && receipt.getTime() <= endTime) - .collect(Collectors.toMap(Receipt::getTime, receipt -> receipt, (e1, e2) -> e1, TreeMap::new)); + .filter(receipt->receipt.getTime() >= startTime && receipt.getTime() <= endTime) + .collect(Collectors.toMap(Receipt::getTime, receipt->receipt, (e1, e2)->e1, TreeMap::new)); } /** * Retrieves receipts by their time and a transaction participant UUID. * - * @param time The time of the receipts. + * @param time The time of the receipts. * @param participantUUID The UUID of the transaction participant. - * @return A list of receipts that occurred at the specified time and involve the specified participant. + * + * @return A list of receipts that occurred at the specified time and involve the specified + * participant. */ public List getReceiptsByTimeAndParticipant(final long time, final UUID participantUUID) { + return receipts.values().stream() - .filter(receipt -> receipt.getTime() == time && - (receipt.getFrom() != null && receipt.getFrom().getId().equals(participantUUID) || - receipt.getTo() != null && receipt.getTo().getId().equals(participantUUID))) + .filter(receipt->receipt.getTime() == time && + (receipt.getFrom() != null && receipt.getFrom().getId().equals(participantUUID) || + receipt.getTo() != null && receipt.getTo().getId().equals(participantUUID))) .collect(Collectors.toList()); } /** - * Retrieves receipts that occurred between two time periods and involve a specific transaction participant. + * Retrieves receipts that occurred between two time periods and involve a specific transaction + * participant. * - * @param startTime The start time of the range. - * @param endTime The end time of the range. + * @param startTime The start time of the range. + * @param endTime The end time of the range. * @param participantUUID The UUID of the transaction participant. + * * @return A TreeMap where the key is the receipt time and the value is the Receipt object. */ public TreeMap getReceiptsBetweenTimesAndParticipant(final long startTime, final long endTime, final UUID participantUUID) { + return receipts.values().stream() - .filter(receipt -> receipt.getTime() >= startTime && receipt.getTime() <= endTime && - (receipt.getFrom() != null && receipt.getFrom().getId().equals(participantUUID) || - receipt.getTo() != null && receipt.getTo().getId().equals(participantUUID))) - .collect(Collectors.toMap(Receipt::getTime, receipt -> receipt, (e1, e2) -> e1, TreeMap::new)); + .filter(receipt->receipt.getTime() >= startTime && receipt.getTime() <= endTime && + (receipt.getFrom() != null && receipt.getFrom().getId().equals(participantUUID) || + receipt.getTo() != null && receipt.getTo().getId().equals(participantUUID))) + .collect(Collectors.toMap(Receipt::getTime, receipt->receipt, (e1, e2)->e1, TreeMap::new)); } /** * Removes a receipt by its UUID. * * @param id The UUID of the receipt to be removed. + * * @return true if the receipt was removed, false otherwise. */ public boolean removeReceiptByUUID(final UUID id) { + return receipts.remove(id) != null; } @@ -144,11 +160,13 @@ public boolean removeReceiptByUUID(final UUID id) { * Removes receipts by their time. * * @param time The time of the receipts to be removed. + * * @return A list of receipts that were removed. */ public List removeReceiptsByTime(final long time) { + final List removedReceipts = getReceiptByTime(time); - for (final Receipt receipt : removedReceipts) { + for(final Receipt receipt : removedReceipts) { receipts.remove(receipt.getId()); } return removedReceipts; @@ -158,12 +176,14 @@ public List removeReceiptsByTime(final long time) { * Removes receipts that occurred between two time periods. * * @param startTime The start time of the range. - * @param endTime The end time of the range. + * @param endTime The end time of the range. + * * @return A list of receipts that were removed. */ public List removeReceiptsBetweenTimes(final long startTime, final long endTime) { + final List removedReceipts = new ArrayList<>(getReceiptsBetweenTimes(startTime, endTime).values()); - for (final Receipt receipt : removedReceipts) { + for(final Receipt receipt : removedReceipts) { receipts.remove(receipt.getId()); } return removedReceipts; @@ -172,35 +192,41 @@ public List removeReceiptsBetweenTimes(final long startTime, final long /** * Removes receipts by their time and a transaction participant UUID. * - * @param time The time of the receipts. + * @param time The time of the receipts. * @param participantUUID The UUID of the transaction participant. + * * @return A list of receipts that were removed. */ public List removeReceiptsByTimeAndParticipant(final long time, final UUID participantUUID) { + final List removedReceipts = getReceiptsByTimeAndParticipant(time, participantUUID); - for (final Receipt receipt : removedReceipts) { + for(final Receipt receipt : removedReceipts) { receipts.remove(receipt.getId()); } return removedReceipts; } /** - * Removes receipts that occurred between two time periods and involve a specific transaction participant. + * Removes receipts that occurred between two time periods and involve a specific transaction + * participant. * - * @param startTime The start time of the range. - * @param endTime The end time of the range. + * @param startTime The start time of the range. + * @param endTime The end time of the range. * @param participantUUID The UUID of the transaction participant. + * * @return A list of receipts that were removed. */ public List removeReceiptsBetweenTimesAndParticipant(final long startTime, final long endTime, final UUID participantUUID) { + final List removedReceipts = new ArrayList<>(getReceiptsBetweenTimesAndParticipant(startTime, endTime, participantUUID).values()); - for (final Receipt receipt : removedReceipts) { + for(final Receipt receipt : removedReceipts) { receipts.remove(receipt.getId()); } return removedReceipts; } public ConcurrentMap getReceipts() { + return receipts; } } diff --git a/Core/src/net/tnemc/core/manager/TopManager.java b/Core/src/net/tnemc/core/manager/TopManager.java index 1fc69723..87767b62 100644 --- a/Core/src/net/tnemc/core/manager/TopManager.java +++ b/Core/src/net/tnemc/core/manager/TopManager.java @@ -71,10 +71,12 @@ public void load() { } public Map getTopMap() { + return topMap; } public int position(final UUID currency, final String account) { + if(topMap.containsKey(currency)) { return topMap.get(currency).getBalances().position(account); } @@ -82,6 +84,7 @@ public int position(final UUID currency, final String account) { } public String getAt(final int position, final UUID currency) { + if(topMap.containsKey(currency)) { final int internalPos = (position % 5 == 0)? 5 : position % 5; @@ -92,6 +95,7 @@ public String getAt(final int position, final UUID currency) { } public MessageData getFor(final int position, final UUID currency) { + if(topMap.containsKey(currency)) { final int internalPos = (position % 5 == 0)? 5 : position % 5; @@ -106,6 +110,7 @@ public MessageData getFor(final int position, final UUID currency) { } public int positionToPage(final int position) { + int page = position / 5; if(position % 5 != 0) page++; @@ -114,6 +119,7 @@ public int positionToPage(final int position) { } public TopPage page(final int page, final UUID currency) { + if(topMap.containsKey(currency)) { return topMap.get(currency).getBalances().getValues(page); } @@ -121,6 +127,7 @@ public TopPage page(final int page, final UUID currency) { } public int page(final UUID currency) { + if(topMap.containsKey(currency)) { return topMap.get(currency).getBalances().pages(); } @@ -128,14 +135,17 @@ public int page(final UUID currency) { } public static TopManager instance() { + return instance; } public List getRegexExclusions() { + return regexExclusions; } public List getExclusions() { + return exclusions; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/manager/TransactionManager.java b/Core/src/net/tnemc/core/manager/TransactionManager.java index 1983f4bd..26ec8291 100644 --- a/Core/src/net/tnemc/core/manager/TransactionManager.java +++ b/Core/src/net/tnemc/core/manager/TransactionManager.java @@ -52,9 +52,9 @@ * Manages everything related to the transaction system. This is usually just keeping track of the * various check types and other systems. * + * @author creatorfromhell * @see Transaction * @see TransactionCheck - * @author creatorfromhell * @since 0.1.2.0 */ public class TransactionManager { @@ -118,78 +118,94 @@ public TransactionManager() { /** * Attempts to find a {@link TransactionType type}. + * * @param identifier The identifier of the type to use in the search. * * @return An Optional containing the type if it exists based on the identifier, otherwise an * empty Optional. */ public Optional findType(final String identifier) { + return Optional.ofNullable(types.get(identifier)); } /** * Adds a {@link TransactionType type}. + * * @param type The type to add. */ public void addType(final TransactionType type) { + types.put(type); } /** * Attempts to find a {@link TaxType type}. + * * @param identifier The identifier of the type to use in the search. * * @return An Optional containing the type if it exists based on the identifier, otherwise an * empty Optional. */ public Optional findTax(final String identifier) { + return Optional.ofNullable(tax.get(identifier)); } /** * Adds a {@link TaxType type}. + * * @param type The type to add. */ public void addTax(final TaxType type) { + tax.put(type); } /** * Adds a {@link TransactionCheck check}. + * * @param check The check to add. */ public void addCheck(final TransactionCheck check) { + checks.put(check); } /** * Adds a {@link TransactionCheck check}. + * * @param check The check to add. * @param group The {@link TransactionCheckGroup group} to add this check to. */ public void addCheck(final TransactionCheck check, final String group) { + checks.put(check); addCheckToGroup(check.identifier(), group); } /** * Attempts to find a {@link TransactionCheck check}. + * * @param identifier The identifier of the check to use in the search. * * @return An Optional containing the check if it exists based on the identifier, otherwise an * empty Optional. */ public Optional findCheck(final String identifier) { + return Optional.ofNullable(checks.get(identifier)); } /** * Adds a {@link TransactionCheck check} to a {@link TransactionCheckGroup group} if it exists, * otherwise it'll create a new group and add it to that. + * * @param check The check to add. * @param group The group to add the check to. */ public void addCheckToGroup(final String check, final String group) { + Optional groupOptional = findGroup(group); groupOptional.ifPresentOrElse(transactionCheckGroup->{ transactionCheckGroup.addCheck(check); @@ -204,52 +220,64 @@ public void addCheckToGroup(final String check, final String group) { /** * Adds a {@link TransactionCheckGroup group}. + * * @param group The group to add. */ public void addGroup(final TransactionCheckGroup group) { + checkGroups.put(group); } /** * Attempts to find a {@link TransactionCheckGroup group}. + * * @param identifier The identifier of the group to use in the search. * * @return An Optional containing the group if it exists based on the identifier, otherwise an * empty Optional. */ public Optional findGroup(final String identifier) { + return Optional.ofNullable(checkGroups.get(identifier)); } public boolean isTrack() { + return track; } public void setTrack(boolean track) { + this.track = track; } public BigDecimal getAmount() { + return amount; } public void setAmount(BigDecimal amount) { + this.amount = amount; } public TransactionProcessor getProcessor() { + return processor; } public void setProcessor(TransactionProcessor processor) { + this.processor = processor; } public static ReceiptManager receipts() { + return TNECore.eco().transaction().receiptManager; } public SimpleDateFormat getFormat() { + return format; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/manager/Updater.java b/Core/src/net/tnemc/core/manager/Updater.java index edcaf612..55d4316c 100644 --- a/Core/src/net/tnemc/core/manager/Updater.java +++ b/Core/src/net/tnemc/core/manager/Updater.java @@ -36,6 +36,7 @@ public class Updater extends UpdateChecker { final int pluginStrip; public Updater() { + ver = IOUtil.readVersion().orElse("0.0.0.0"); verStrip = Integer.parseInt(ver.replaceAll("\\.", "")); pluginStrip = Integer.parseInt(PluginCore.engine().version().replaceAll("\\.", "")); @@ -43,16 +44,19 @@ public Updater() { @Override public boolean isEarlyBuild() { + return verStrip < pluginStrip; } @Override public boolean needsUpdate() { + return verStrip > pluginStrip; } @Override public String stable() { + if(new Semver(PluginCore.engine().version() + "-" + PluginCore.engine().build(), Semver.SemverType.LOOSE).isStable()) { return "Stable"; } @@ -61,6 +65,7 @@ public String stable() { @Override public String getBuild() { + return ver; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/manager/top/TopCurrency.java b/Core/src/net/tnemc/core/manager/top/TopCurrency.java index 9506da95..676cf515 100644 --- a/Core/src/net/tnemc/core/manager/top/TopCurrency.java +++ b/Core/src/net/tnemc/core/manager/top/TopCurrency.java @@ -42,6 +42,7 @@ public class TopCurrency { private final UUID currency; public TopCurrency(String region, UUID currency) { + this.region = region; this.currency = currency; @@ -50,12 +51,13 @@ public TopCurrency(String region, UUID currency) { } public UUID getCurrency() { + return currency; } public void load() { - for(Account account: TNECore.eco().account().getAccounts().values()) { + for(Account account : TNECore.eco().account().getAccounts().values()) { if(excluded(account.getName())) continue; balances.put(account.getHoldingsTotal(region, currency), account.getName()); @@ -63,6 +65,7 @@ public void load() { } public boolean excluded(final String name) { + for(Pattern pattern : TopManager.instance().getRegexExclusions()) { if(pattern.matcher(name).matches()) return true; } @@ -74,6 +77,7 @@ public boolean excluded(final String name) { } public MultiTreeMap getBalances() { + return balances; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/manager/top/TopPage.java b/Core/src/net/tnemc/core/manager/top/TopPage.java index 5d33e75a..ed048611 100644 --- a/Core/src/net/tnemc/core/manager/top/TopPage.java +++ b/Core/src/net/tnemc/core/manager/top/TopPage.java @@ -38,14 +38,17 @@ public class TopPage { private final int page; public TopPage(int page) { + this.page = page; } public LinkedHashMap getValues() { + return values; } public V getAt(final int pos) { + if(pos > values.size()) return (V)"no one"; final Iterator> it = values.entrySet().iterator(); @@ -89,6 +92,7 @@ public MessageData getFor(final int pos) { } public int getPage() { + return page; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/menu/BaltopMenu.java b/Core/src/net/tnemc/core/menu/BaltopMenu.java index e3f6e4d3..73bf9460 100644 --- a/Core/src/net/tnemc/core/menu/BaltopMenu.java +++ b/Core/src/net/tnemc/core/menu/BaltopMenu.java @@ -52,6 +52,7 @@ public class BaltopMenu extends Menu { public static final int TOP_COUNT = 10; public BaltopMenu() { + this.name = "baltop_menu"; this.title = "Balance Top"; this.rows = 3; @@ -85,18 +86,18 @@ public void handleMainPage(final PageOpenCallback callback) { if(maxPages > 1) { callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("RED_WOOL", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.PreviousPageDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.PreviousPage"), id)))) - .withActions(new DataAction(TOP_PAGE_ID, prev), new SwitchPageAction(this.name, 1)) - .withSlot(0) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.PreviousPageDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.PreviousPage"), id)))) + .withActions(new DataAction(TOP_PAGE_ID, prev), new SwitchPageAction(this.name, 1)) + .withSlot(0) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("GREEN_WOOL", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.NextPageDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.NextPage"), id)))) - .withActions(new DataAction(TOP_PAGE_ID, next), new SwitchPageAction(this.name, 1)) - .withSlot(8) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.NextPageDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.NextPage"), id)))) + .withActions(new DataAction(TOP_PAGE_ID, next), new SwitchPageAction(this.name, 1)) + .withSlot(8) + .build()); } int slot = 9; @@ -141,7 +142,7 @@ protected Icon buildTransactionIcon(final int slot, final Receipt receipt) { lore.add(Component.text("From: " + from)); return new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1) - .display(Component.text(receipt.getId().toString())).lore(lore)) + .display(Component.text(receipt.getId().toString())).lore(lore)) .withSlot(slot).build(); } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/menu/MyBalMenu.java b/Core/src/net/tnemc/core/menu/MyBalMenu.java index 59164c64..bf9547ec 100644 --- a/Core/src/net/tnemc/core/menu/MyBalMenu.java +++ b/Core/src/net/tnemc/core/menu/MyBalMenu.java @@ -91,6 +91,7 @@ public class MyBalMenu extends Menu { public static final String ACTION_HOLDINGS = "ACTION_HOLDINGS"; public MyBalMenu() { + this.name = "my_bal"; this.title = "My Bal"; this.rows = 6; @@ -173,27 +174,27 @@ protected void actionsPage(final PageOpenCallback callback) { if(currencyOptional.isPresent()) { callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.MyBal.Actions.ConvertDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyBal.Actions.Convert"), id)))) - .withSlot(10) - .withActions(new SwitchPageAction(this.name, BALANCE_ACTION_CONVERT_CURRENCY_PAGE)) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.MyBal.Actions.ConvertDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyBal.Actions.Convert"), id)))) + .withSlot(10) + .withActions(new SwitchPageAction(this.name, BALANCE_ACTION_CONVERT_CURRENCY_PAGE)) + .build()); if(currencyOptional.get().type().supportsExchange()) { callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.MyBal.Actions.DepositDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyBal.Actions.Deposit"), id)))) - .withSlot(12) - .withActions(new SwitchPageAction(this.name, BALANCE_ACTION_DEPOSIT_AMOUNT_PAGE)) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.MyBal.Actions.DepositDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyBal.Actions.Deposit"), id)))) + .withSlot(12) + .withActions(new SwitchPageAction(this.name, BALANCE_ACTION_DEPOSIT_AMOUNT_PAGE)) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.MyBal.Actions.WithdrawDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyBal.Actions.Withdraw"), id)))) - .withSlot(14) - .withActions(new SwitchPageAction(this.name, BALANCE_ACTION_WITHDRAW_AMOUNT_PAGE)) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.MyBal.Actions.WithdrawDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyBal.Actions.Withdraw"), id)))) + .withSlot(14) + .withActions(new SwitchPageAction(this.name, BALANCE_ACTION_WITHDRAW_AMOUNT_PAGE)) + .build()); } } } @@ -223,9 +224,9 @@ protected void handleBreakdownPage(final PageOpenCallback callback) { balMessage.addReplacement("$balance", entry.getAmount()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1) - .display(Component.text(entry.getHandler().id())) - .lore(Collections.singletonList(MessageHandler.grab(balMessage, id)))) - .withSlot(i).build()); + .display(Component.text(entry.getHandler().id())) + .lore(Collections.singletonList(MessageHandler.grab(balMessage, id)))) + .withSlot(i).build()); i += 2; } } @@ -270,7 +271,7 @@ protected Icon buildBalanceIcon(final int slot, final Currency currency, final A } return new IconBuilder(PluginCore.server().stackBuilder().of(currency.getIconMaterial(), 1) - .display(Component.text(currency.getIdentifier())).lore(lore)) + .display(Component.text(currency.getIdentifier())).lore(lore)) .withSlot(slot) .withActions(actions.toArray(new IconAction[actions.size()])).build(); } @@ -341,13 +342,13 @@ protected void convert(final AmountSelectionHandler handler) { final String region = ""; final HoldingsModifier modifier = new HoldingsModifier(region, - currencyOptional.get().getUid(), - converted.get().setScale(currencyOptional.get().getDecimalPlaces(), RoundingMode.DOWN) + currencyOptional.get().getUid(), + converted.get().setScale(currencyOptional.get().getDecimalPlaces(), RoundingMode.DOWN) ); final HoldingsModifier modifierFrom = new HoldingsModifier(region, - fromCurrency.get().getUid(), - handler.getAmount().setScale(currencyOptional.get().getDecimalPlaces(), RoundingMode.DOWN).negate() + fromCurrency.get().getUid(), + handler.getAmount().setScale(currencyOptional.get().getDecimalPlaces(), RoundingMode.DOWN).negate() ); final Transaction transaction = new Transaction("convert") @@ -357,11 +358,11 @@ protected void convert(final AmountSelectionHandler handler) { .source(new PlayerSource(playerUUID)); final Optional receipt = processTransaction(player.get(), transaction, senderAccount.get().getName(), handler.getAmount()); - if(receipt.isPresent()){ + if(receipt.isPresent()) { final MessageData data = new MessageData("Messages.Money.Converted"); data.addReplacement("$from_amount", handler.getAmount().toPlainString()); data.addReplacement("$amount", CurrencyFormatter.format(senderAccount.get(), - modifierFrom.asEntry())); + modifierFrom.asEntry())); player.get().message(data); } } @@ -412,9 +413,9 @@ protected void deposit(final AmountSelectionHandler handler) { } final HoldingsModifier modifier = new HoldingsModifier(TNECore.eco().region().getMode().region(player.get()), - currencyOptional.get().getUid(), - handler.getAmount(), - EconomyManager.VIRTUAL + currencyOptional.get().getUid(), + handler.getAmount(), + EconomyManager.VIRTUAL ); final Transaction transaction = new Transaction("deposit") @@ -427,13 +428,14 @@ protected void deposit(final AmountSelectionHandler handler) { if(receipt.isPresent()) { final MessageData data = new MessageData("Messages.Money.Deposit"); data.addReplacement("$amount", CurrencyFormatter.format(senderAccount.get(), - modifier.asEntry())); + modifier.asEntry())); player.get().message(data); } } } } } + protected void note(final AmountSelectionHandler handler) { final Optional viewer = handler.getClick().player().viewer(); @@ -474,8 +476,8 @@ protected void note(final AmountSelectionHandler handler) { final BigDecimal amt = rounded.add(note.get().getFee().calculateTax(rounded)).setScale(currencyOptional.get().getDecimalPlaces(), RoundingMode.DOWN); final HoldingsModifier modifier = new HoldingsModifier(region, - currencyOptional.get().getUid(), - amt + currencyOptional.get().getUid(), + amt ); final Transaction transaction = new Transaction("note") @@ -487,7 +489,7 @@ protected void note(final AmountSelectionHandler handler) { final Optional receipt = processTransaction(player.get(), transaction, account.get().getName(), handler.getAmount()); if(receipt.isPresent()) { final Collection> left = PluginCore.server().calculations().giveItems(Collections.singletonList(note.get().stack(currencyOptional.get().getIdentifier(), region, rounded)), - player.get().inventory().getInventory(false)); + player.get().inventory().getInventory(false)); if(!left.isEmpty()) { PluginCore.server().calculations().drop(left, ((PlayerAccount)account.get()).getUUID()); @@ -565,7 +567,7 @@ protected void pay(final AmountSelectionHandler handler) { data.addReplacement("$distance", String.valueOf(MainConfig.yaml().getInt("Core.Commands.Pay.Radius"))); if(!(senderAccount.get() instanceof PlayerAccount) || !((PlayerAccount)senderAccount.get()).isOnline() - || !(account.get() instanceof PlayerAccount) || !((PlayerAccount)account.get()).isOnline()) { + || !(account.get() instanceof PlayerAccount) || !((PlayerAccount)account.get()).isOnline()) { player.get().message(data); return; } @@ -573,7 +575,7 @@ protected void pay(final AmountSelectionHandler handler) { final Optional senderPlayer = ((PlayerAccount)senderAccount.get()).getPlayer(); final Optional playerPlayer = ((PlayerAccount)account.get()).getPlayer(); if(senderPlayer.isEmpty() || playerPlayer.isEmpty() - || senderPlayer.get().getLocation().isEmpty() || playerPlayer.get().getLocation().isEmpty()) { + || senderPlayer.get().getLocation().isEmpty() || playerPlayer.get().getLocation().isEmpty()) { player.get().message(data); return; } @@ -585,8 +587,8 @@ protected void pay(final AmountSelectionHandler handler) { } final HoldingsModifier modifier = new HoldingsModifier(TNECore.eco().region().getMode().region(player.get()), - currencyOptional.get().getUid(), - handler.getAmount() + currencyOptional.get().getUid(), + handler.getAmount() ); final Transaction transaction = new Transaction("pay") .to(account.get(), modifier) @@ -600,7 +602,7 @@ protected void pay(final AmountSelectionHandler handler) { data.addReplacement("$player", account.get().getName()); data.addReplacement("$currency", currencyOptional.get().getIdentifier()); data.addReplacement("$amount", CurrencyFormatter.format(account.get(), - modifier.asEntry())); + modifier.asEntry())); player.get().message(data); if(account.get().isPlayer() && ((PlayerAccount)account.get()).isOnline()) { @@ -611,7 +613,7 @@ protected void pay(final AmountSelectionHandler handler) { final MessageData msgData = new MessageData("Messages.Money.Received"); msgData.addReplacement("$player", (player.get().getName() == null)? MainConfig.yaml().getString("Core.Server.Account.Name") : player.get().getName()); msgData.addReplacement("$amount", CurrencyFormatter.format(account.get(), - modifier.asEntry())); + modifier.asEntry())); provider.get().message(msgData); } } @@ -634,7 +636,7 @@ protected void withdraw(final AmountSelectionHandler handler) { final Optional currencyOptional = TNECore.eco().currency().findCurrency((UUID)currencyUUID.get()); final Optional player = PluginCore.server().findPlayer(handler.getClick().player().identifier()); if(currencyOptional.isPresent() && player.isPresent()) { - + if(EconomyManager.limitCurrency()) { if(!player.get().hasPermission("tne.money.withdraw." + currencyOptional.get().getIdentifier())) { final MessageData data = new MessageData("Messages.Account.BlockedAction"); @@ -664,9 +666,9 @@ protected void withdraw(final AmountSelectionHandler handler) { } final HoldingsModifier modifier = new HoldingsModifier(TNECore.eco().region().getMode().region(player.get()), - currencyOptional.get().getUid(), - handler.getAmount(), - EconomyManager.ITEM_ONLY + currencyOptional.get().getUid(), + handler.getAmount(), + EconomyManager.ITEM_ONLY ); final Transaction transaction = new Transaction("withdraw") @@ -681,14 +683,17 @@ protected void withdraw(final AmountSelectionHandler handler) { final MessageData data = new MessageData("Messages.Money.Withdrawn"); data.addReplacement("$currency", currencyOptional.get().getIdentifier()); data.addReplacement("$amount", CurrencyFormatter.format(senderAccount.get(), - modifier.asEntry())); + modifier.asEntry())); player.get().message(data); return; } } } } - }private static Optional processTransaction(final PlayerProvider player, final Transaction transaction, final String modifiedAccount, final BigDecimal modifier) { + } + + private static Optional processTransaction(final PlayerProvider player, final Transaction transaction, final String modifiedAccount, final BigDecimal modifier) { + try { final TransactionResult result = transaction.process(); diff --git a/Core/src/net/tnemc/core/menu/MyEcoMenu.java b/Core/src/net/tnemc/core/menu/MyEcoMenu.java index 286f0638..e32d1bae 100644 --- a/Core/src/net/tnemc/core/menu/MyEcoMenu.java +++ b/Core/src/net/tnemc/core/menu/MyEcoMenu.java @@ -123,7 +123,7 @@ public MyEcoMenu() { final UUID id = open.getPlayer().identifier(); open.getPage().addIcon(new SwitchPageIcon(2, PluginCore.server().stackBuilder().of("GOLD_INGOT", 1) .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.Main.Currencies"), id)), this.name, CURRENCIES_PAGE, ActionType.ANY)); - }); + }); addPage(main); //Currency Page @@ -156,58 +156,58 @@ public MyEcoMenu() { final UUID id = open.getPlayer().identifier(); open.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("ARROW", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.Save"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.Currency.SaveLore"), id)))) - .withActions(new RunnableAction((click)->{ + .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.Save"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.Currency.SaveLore"), id)))) + .withActions(new RunnableAction((click)->{ - final File directory = new File(PluginCore.directory(), "currency"); - TNECore.eco().currency().getSaver().backupCurrency(directory); + final File directory = new File(PluginCore.directory(), "currency"); + TNECore.eco().currency().getSaver().backupCurrency(directory); - MISCUtils.deleteFolder(directory); + MISCUtils.deleteFolder(directory); - TNECore.eco().currency().getSaver().saveCurrencies(directory); + TNECore.eco().currency().getSaver().saveCurrencies(directory); - try { + try { - TNECore.eco().currency().getCurrencies().clear(); - TNECore.eco().currency().getCurIDMap().clear(); + TNECore.eco().currency().getCurrencies().clear(); + TNECore.eco().currency().getCurIDMap().clear(); - TNECore.eco().currency().getLoader().loadCurrencies(directory); + TNECore.eco().currency().getLoader().loadCurrencies(directory); - final Optional viewer = click.player().viewer(); - if(viewer.isPresent()) { - viewer.get().addData("CURRENCY_SAVED_CONFIRM", true); - } + final Optional viewer = click.player().viewer(); + if(viewer.isPresent()) { + viewer.get().addData("CURRENCY_SAVED_CONFIRM", true); + } - final Optional provider = PluginCore.server().findPlayer(id); - if(provider.isPresent()) { - provider.get().message(new MessageData("Messages.Menu.MyEco.Main.Saved")); - } + final Optional provider = PluginCore.server().findPlayer(id); + if(provider.isPresent()) { + provider.get().message(new MessageData("Messages.Menu.MyEco.Main.Saved")); + } - } catch(NoValidCurrenciesException ignore) {} - }), new PageSwitchWithClose(this.name, -1)) - .withSlot(6) - .build()); + } catch(NoValidCurrenciesException ignore) { } + }), new PageSwitchWithClose(this.name, -1)) + .withSlot(6) + .build()); open.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("BLACK_WOOL", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.Reset"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.Currency.ResetLore"), id)))) - .withActions(new RunnableAction((click)->{ + .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.Reset"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.Currency.ResetLore"), id)))) + .withActions(new RunnableAction((click)->{ + + final File directory = new File(PluginCore.directory(), "currency"); - final File directory = new File(PluginCore.directory(), "currency"); + try { - try { + TNECore.eco().currency().getCurrencies().clear(); + TNECore.eco().currency().getCurIDMap().clear(); - TNECore.eco().currency().getCurrencies().clear(); - TNECore.eco().currency().getCurIDMap().clear(); + TNECore.eco().currency().getLoader().loadCurrencies(directory); + } catch(NoValidCurrenciesException ignore) { } + }), new PageSwitchWithClose(this.name, -1)) + .withSlot(8) + .build()); - TNECore.eco().currency().getLoader().loadCurrencies(directory); - } catch(NoValidCurrenciesException ignore) {} - }), new PageSwitchWithClose(this.name, -1)) - .withSlot(8) - .build()); - //add currency final SwitchPageIcon addCurrencyIcon = new SwitchPageIcon(2, PluginCore.server().stackBuilder().of("ARROW", 1) .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.Currency.AddCurrencyDisplay"), id)) @@ -625,54 +625,54 @@ private void handleCurrencyEditInfoOpen(final PageOpenCallback callback) { //currency name icon callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.SetIdentifierLore"), id)))) - .withSlot(18) - .withActions(new ChatAction((message)->{ - - if(message.getPlayer().viewer().isPresent()) { - - if(TNECore.eco().currency().findCurrency(message.getMessage()).isPresent()) { - message.getPlayer().message("A currency with that identifier already exists! Enter an identifier for the currency:"); - return false; - } - - currencyObject.setIdentifier(message.getMessage()); - return true; - } - message.getPlayer().message("Enter an identifier for the currency:"); - return false; - }), new RunnableAction((run)->run.player().message("Enter a identifier for the currency:"))) - .withItemProvider((provider)->PluginCore.server().stackBuilder().of("PAPER", 1) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.SetIdentifierLore"), id))) - .display(Component.text(currencyObject.getIdentifier()))) - .build()); + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.SetIdentifierLore"), id)))) + .withSlot(18) + .withActions(new ChatAction((message)->{ + + if(message.getPlayer().viewer().isPresent()) { + + if(TNECore.eco().currency().findCurrency(message.getMessage()).isPresent()) { + message.getPlayer().message("A currency with that identifier already exists! Enter an identifier for the currency:"); + return false; + } + + currencyObject.setIdentifier(message.getMessage()); + return true; + } + message.getPlayer().message("Enter an identifier for the currency:"); + return false; + }), new RunnableAction((run)->run.player().message("Enter a identifier for the currency:"))) + .withItemProvider((provider)->PluginCore.server().stackBuilder().of("PAPER", 1) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.SetIdentifierLore"), id))) + .display(Component.text(currencyObject.getIdentifier()))) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.StartingBalanceDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.StartingBalanceLore"), id)))) - .withSlot(19) - .withActions(new SwitchPageAction(this.name, CURRENCY_INFO_STARTING_SELECTION_PAGE)) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.StartingBalanceDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.StartingBalanceLore"), id)))) + .withSlot(19) + .withActions(new SwitchPageAction(this.name, CURRENCY_INFO_STARTING_SELECTION_PAGE)) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.MaximumBalanceDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.MaximumBalanceLore"), id)))) - .withSlot(20) - .withActions(new SwitchPageAction(this.name, CURRENCY_INFO_MAX_SELECTION_PAGE)) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.MaximumBalanceDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.MaximumBalanceLore"), id)))) + .withSlot(20) + .withActions(new SwitchPageAction(this.name, CURRENCY_INFO_MAX_SELECTION_PAGE)) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.MinimumBalanceDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.MinimumBalanceLore"), id)))) - .withSlot(21) - .withActions(new SwitchPageAction(this.name, CURRENCY_INFO_MIN_SELECTION_PAGE)) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.MinimumBalanceDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.MinimumBalanceLore"), id)))) + .withSlot(21) + .withActions(new SwitchPageAction(this.name, CURRENCY_INFO_MIN_SELECTION_PAGE)) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of(currencyObject.getIconMaterial(), 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.SetIconMaterialDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.SetIconMaterialLore"), id)))) - .withSlot(22) - .withActions(new SwitchPageAction(this.name, CURRENCY_ICON_MATERIAL_PAGE)) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.SetIconMaterialDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.SetIconMaterialLore"), id)))) + .withSlot(22) + .withActions(new SwitchPageAction(this.name, CURRENCY_ICON_MATERIAL_PAGE)) + .build()); if(currencyObject instanceof ItemCurrency itemCurrency) { @@ -691,14 +691,14 @@ private void handleCurrencyEditInfoOpen(final PageOpenCallback callback) { }); enderchest.setSlot(23); enderchest.addState("DISABLED", - disabledStack - .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.EnderChestDisabledDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.EnderChestDisabledLore"), id)))); + disabledStack + .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.EnderChestDisabledDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.EnderChestDisabledLore"), id)))); enderchest.addState("ENABLED", - enabledStack - .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.EnderChestEnabledDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.EnderChestEnabledLore"), id)))); + enabledStack + .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.EnderChestEnabledDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.EnderChestEnabledLore"), id)))); callback.getPage().addIcon(enderchest); @@ -714,14 +714,14 @@ private void handleCurrencyEditInfoOpen(final PageOpenCallback callback) { }); enderFill.setSlot(24); enderFill.addState("DISABLED", - disabledStack - .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.EnderFillDisabledDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.EnderFillDisabledLore"), id)))); + disabledStack + .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.EnderFillDisabledDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.EnderFillDisabledLore"), id)))); enderFill.addState("ENABLED", - enabledStack - .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.EnderFillEnabledDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.EnderFillEnabledLore"), id)))); + enabledStack + .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.EnderFillEnabledDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.EnderFillEnabledLore"), id)))); callback.getPage().addIcon(enderFill); //import item icon @@ -736,14 +736,14 @@ private void handleCurrencyEditInfoOpen(final PageOpenCallback callback) { }); importFill.setSlot(25); importFill.addState("DISABLED", - disabledStack - .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.ImportDisabledDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.ImportDisabledLore"), id)))); + disabledStack + .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.ImportDisabledDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.ImportDisabledLore"), id)))); importFill.addState("ENABLED", - enabledStack - .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.ImportEnabledDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.ImportEnabledLore"), id)))); + enabledStack + .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.ImportEnabledDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditInfo.ImportEnabledLore"), id)))); callback.getPage().addIcon(importFill); } } @@ -777,131 +777,131 @@ private void handleCurrencyEditFormatOpen(final PageOpenCallback callback) { final Currency currencyObject = (Currency)currencyOpt.get(); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.BalanceFormatDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.BalanceFormatLore"), id)))) - .withSlot(10) - .withActions(new SwitchPageAction(this.name, CURRENCY_FORMAT_SELECTION_PAGE)) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.BalanceFormatDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.BalanceFormatLore"), id)))) + .withSlot(10) + .withActions(new SwitchPageAction(this.name, CURRENCY_FORMAT_SELECTION_PAGE)) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1)) - .withSlot(11) - .withActions(new ChatAction((message)->{ - - if(message.getPlayer().viewer().isPresent()) { - - currencyObject.setSymbol(message.getMessage()); - return true; - } - message.getPlayer().message("Enter the symbol for the currency:"); - return false; - }), new RunnableAction((run)->run.player().message("Enter the symbol for the currency:"))) - .withItemProvider((provider)->PluginCore.server().stackBuilder().of("PAPER", 1) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.SetSymbolLore"), id))) - .display(Component.text(currencyObject.getSymbol()))) - .build()); + .withSlot(11) + .withActions(new ChatAction((message)->{ + + if(message.getPlayer().viewer().isPresent()) { + + currencyObject.setSymbol(message.getMessage()); + return true; + } + message.getPlayer().message("Enter the symbol for the currency:"); + return false; + }), new RunnableAction((run)->run.player().message("Enter the symbol for the currency:"))) + .withItemProvider((provider)->PluginCore.server().stackBuilder().of("PAPER", 1) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.SetSymbolLore"), id))) + .display(Component.text(currencyObject.getSymbol()))) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1)) - .withSlot(12) - .withActions(new ChatAction((message)->{ - - if(message.getPlayer().viewer().isPresent()) { - - currencyObject.setPrefixes(message.getMessage()); - return true; - } - message.getPlayer().message("Enter the prefixes for the currency:"); - return false; - }), new RunnableAction((run)->run.player().message("Enter the prefixes for the currency:"))) - .withItemProvider((provider)->PluginCore.server().stackBuilder().of("PAPER", 1) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.SetPrefixesLore"), id))) - .display(Component.text(currencyObject.getPrefixes()))) - .build()); + .withSlot(12) + .withActions(new ChatAction((message)->{ + + if(message.getPlayer().viewer().isPresent()) { + + currencyObject.setPrefixes(message.getMessage()); + return true; + } + message.getPlayer().message("Enter the prefixes for the currency:"); + return false; + }), new RunnableAction((run)->run.player().message("Enter the prefixes for the currency:"))) + .withItemProvider((provider)->PluginCore.server().stackBuilder().of("PAPER", 1) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.SetPrefixesLore"), id))) + .display(Component.text(currencyObject.getPrefixes()))) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1)) - .withSlot(13) - .withActions(new ChatAction((message)->{ - - if(message.getPlayer().viewer().isPresent()) { - - currencyObject.setDecimal(message.getMessage()); - return true; - } - message.getPlayer().message("Enter the decimal for the currency:"); - return false; - }), new RunnableAction((run)->run.player().message("Enter the decimal for the currency:"))) - .withItemProvider((provider)->PluginCore.server().stackBuilder().of("PAPER", 1) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.SetDecimalLore"), id))) - .display(Component.text(currencyObject.getDecimal()))) - .build()); + .withSlot(13) + .withActions(new ChatAction((message)->{ + + if(message.getPlayer().viewer().isPresent()) { + + currencyObject.setDecimal(message.getMessage()); + return true; + } + message.getPlayer().message("Enter the decimal for the currency:"); + return false; + }), new RunnableAction((run)->run.player().message("Enter the decimal for the currency:"))) + .withItemProvider((provider)->PluginCore.server().stackBuilder().of("PAPER", 1) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.SetDecimalLore"), id))) + .display(Component.text(currencyObject.getDecimal()))) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1)) - .withSlot(14) - .withActions(new ChatAction((message)->{ - - if(message.getPlayer().viewer().isPresent()) { - - currencyObject.setDisplay(message.getMessage()); - return true; - } - message.getPlayer().message("Enter the major singular display for the currency:"); - return false; - }), new RunnableAction((run)->run.player().message("Enter the major singular display for the currency:"))) - .withItemProvider((provider)->PluginCore.server().stackBuilder().of("PAPER", 1) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.SetMajorSingularDisplayLore"), id))) - .display(Component.text(currencyObject.getDisplay()))) - .build()); + .withSlot(14) + .withActions(new ChatAction((message)->{ + + if(message.getPlayer().viewer().isPresent()) { + + currencyObject.setDisplay(message.getMessage()); + return true; + } + message.getPlayer().message("Enter the major singular display for the currency:"); + return false; + }), new RunnableAction((run)->run.player().message("Enter the major singular display for the currency:"))) + .withItemProvider((provider)->PluginCore.server().stackBuilder().of("PAPER", 1) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.SetMajorSingularDisplayLore"), id))) + .display(Component.text(currencyObject.getDisplay()))) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1)) - .withSlot(15) - .withActions(new ChatAction((message)->{ - - if(message.getPlayer().viewer().isPresent()) { - - currencyObject.setDisplayPlural(message.getMessage()); - return true; - } - message.getPlayer().message("Enter the major plural display for the currency:"); - return false; - }), new RunnableAction((run)->run.player().message("Enter the major plural display for the currency:"))) - .withItemProvider((provider)->PluginCore.server().stackBuilder().of("PAPER", 1) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.SetMajorPluralDisplayLore"), id))) - .display(Component.text(currencyObject.getDisplayPlural()))) - .build()); + .withSlot(15) + .withActions(new ChatAction((message)->{ + + if(message.getPlayer().viewer().isPresent()) { + + currencyObject.setDisplayPlural(message.getMessage()); + return true; + } + message.getPlayer().message("Enter the major plural display for the currency:"); + return false; + }), new RunnableAction((run)->run.player().message("Enter the major plural display for the currency:"))) + .withItemProvider((provider)->PluginCore.server().stackBuilder().of("PAPER", 1) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.SetMajorPluralDisplayLore"), id))) + .display(Component.text(currencyObject.getDisplayPlural()))) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1)) - .withSlot(16) - .withActions(new ChatAction((message)->{ + .withSlot(16) + .withActions(new ChatAction((message)->{ - if(message.getPlayer().viewer().isPresent()) { + if(message.getPlayer().viewer().isPresent()) { - currencyObject.setDisplayMinor(message.getMessage()); - return true; - } + currencyObject.setDisplayMinor(message.getMessage()); + return true; + } - message.getPlayer().message("Enter the minor singular display for the currency:"); - return false; - }), new RunnableAction((run)->run.player().message("Enter the minor singular display for the currency:"))) - .withItemProvider((provider)->PluginCore.server().stackBuilder().of("PAPER", 1) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.SetMinorSingularDisplayLore"), id))) - .display(Component.text(currencyObject.getDisplayMinor()))) - .build()); + message.getPlayer().message("Enter the minor singular display for the currency:"); + return false; + }), new RunnableAction((run)->run.player().message("Enter the minor singular display for the currency:"))) + .withItemProvider((provider)->PluginCore.server().stackBuilder().of("PAPER", 1) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.SetMinorSingularDisplayLore"), id))) + .display(Component.text(currencyObject.getDisplayMinor()))) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1)) - .withSlot(17) - .withActions(new ChatAction((message)->{ - - if(message.getPlayer().viewer().isPresent()) { - - currencyObject.setDisplayMinorPlural(message.getMessage()); - return true; - } - message.getPlayer().message("Enter the minor plural display for the currency:"); - return false; - }), new RunnableAction((run)->run.player().message("Enter the minor plural display for the currency:"))) - .withItemProvider((provider)->PluginCore.server().stackBuilder().of("PAPER", 1) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.SetMinorPluralDisplayLore"), id))) - .display(Component.text(currencyObject.getDisplayMinorPlural()))) - .build()); + .withSlot(17) + .withActions(new ChatAction((message)->{ + + if(message.getPlayer().viewer().isPresent()) { + + currencyObject.setDisplayMinorPlural(message.getMessage()); + return true; + } + message.getPlayer().message("Enter the minor plural display for the currency:"); + return false; + }), new RunnableAction((run)->run.player().message("Enter the minor plural display for the currency:"))) + .withItemProvider((provider)->PluginCore.server().stackBuilder().of("PAPER", 1) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.SetMinorPluralDisplayLore"), id))) + .display(Component.text(currencyObject.getDisplayMinorPlural()))) + .build()); final AbstractItemStack disabledStack = PluginCore.server().stackBuilder().display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.Disabled"), id)).of("RED_WOOL", 1); final AbstractItemStack enabledStack = PluginCore.server().stackBuilder().display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.Enabled"), id)).of("GREEN_WOOL", 1); @@ -918,33 +918,33 @@ private void handleCurrencyEditFormatOpen(final PageOpenCallback callback) { }); majorSeparate.setSlot(18); majorSeparate.addState("DISABLED", - disabledStack - .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.SeparateMajorDisabledDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.SeparateMajorDisabledLore"), id)))); + disabledStack + .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.SeparateMajorDisabledDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.SeparateMajorDisabledLore"), id)))); majorSeparate.addState("ENABLED", - enabledStack - .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.SeparateMajorEnabledDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.SeparateMajorEnabledLore"), id)))); + enabledStack + .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.SeparateMajorEnabledDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.SeparateMajorEnabledLore"), id)))); callback.getPage().addIcon(majorSeparate); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1)) - .withSlot(19) - .withActions(new ChatAction((message)->{ - - if(message.getPlayer().viewer().isPresent()) { - - currencyObject.setMajorSeparator(message.getMessage()); - return true; - } - message.getPlayer().message("Enter the major value separator for the currency:"); - return false; - }), new RunnableAction((run)->run.player().message("Enter the major value separator for the currency:"))) - .withItemProvider((provider)->PluginCore.server().stackBuilder().of("PAPER", 1) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.SetMajorSeparatorLore"), id))) - .display(Component.text(currencyObject.getMajorSeparator()))) - .build()); + .withSlot(19) + .withActions(new ChatAction((message)->{ + + if(message.getPlayer().viewer().isPresent()) { + + currencyObject.setMajorSeparator(message.getMessage()); + return true; + } + message.getPlayer().message("Enter the major value separator for the currency:"); + return false; + }), new RunnableAction((run)->run.player().message("Enter the major value separator for the currency:"))) + .withItemProvider((provider)->PluginCore.server().stackBuilder().of("PAPER", 1) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.SetMajorSeparatorLore"), id))) + .display(Component.text(currencyObject.getMajorSeparator()))) + .build()); //ender chest icon final String balanceState = (currencyObject.isBalanceShow())? "ENABLED" : "DISABLED"; @@ -958,14 +958,14 @@ private void handleCurrencyEditFormatOpen(final PageOpenCallback callback) { }); showBalance.setSlot(20); showBalance.addState("DISABLED", - disabledStack - .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.BalanceDisabledDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.BalanceDisabledLore"), id)))); + disabledStack + .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.BalanceDisabledDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.BalanceDisabledLore"), id)))); showBalance.addState("ENABLED", - enabledStack - .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.BalanceEnabledDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.BalanceEnabledLore"), id)))); + enabledStack + .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.BalanceEnabledDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditFormat.BalanceEnabledLore"), id)))); callback.getPage().addIcon(showBalance); } @@ -1008,75 +1008,75 @@ private void handleCurrencyEditNoteOpen(final PageOpenCallback callback) { }); notableIcon.setSlot(23); notableIcon.addState("DISABLED", - disabledStack - .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditNote.NotableDisabledDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditNote.NotableDisabledLore"), id)))); + disabledStack + .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditNote.NotableDisabledDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditNote.NotableDisabledLore"), id)))); notableIcon.addState("ENABLED", - enabledStack - .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditNote.NotableEnabledDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditNote.NotableEnabledLore"), id)))); + enabledStack + .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditNote.NotableEnabledDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditNote.NotableEnabledLore"), id)))); callback.getPage().addIcon(notableIcon); if(currency.getNote().isPresent()) { final String material = (currency.getNote().isPresent())? currency.getNote().get().getMaterial() : "PAPER"; callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of(material, 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditNote.NoteMaterialDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditNote.NoteMaterialLore"), id)))) - .withSlot(10) - .withActions(new SwitchPageAction(this.name, CURRENCY_NOTE_MATERIAL_PAGE)) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditNote.NoteMaterialDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditNote.NoteMaterialLore"), id)))) + .withSlot(10) + .withActions(new SwitchPageAction(this.name, CURRENCY_NOTE_MATERIAL_PAGE)) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.FlagsDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditNote.NoteFlagsLore"), id)))) - .withSlot(11) - .withActions(new SwitchPageAction(this.name, CURRENCY_NOTE_FLAGS_PAGE)) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.FlagsDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditNote.NoteFlagsLore"), id)))) + .withSlot(11) + .withActions(new SwitchPageAction(this.name, CURRENCY_NOTE_FLAGS_PAGE)) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.EnchantsDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditNote.NoteEnchantsLore"), id)))) - .withSlot(12) - .withActions(new SwitchPageAction(this.name, CURRENCY_NOTE_ENCHANTS_PAGE)) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.EnchantsDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditNote.NoteEnchantsLore"), id)))) + .withSlot(12) + .withActions(new SwitchPageAction(this.name, CURRENCY_NOTE_ENCHANTS_PAGE)) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditNote.NoteMinDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditNote.MinLore"), id)))) - .withSlot(13) - .withActions(new SwitchPageAction(this.name, CURRENCY_NOTE_MIN_SELECTION_PAGE)) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditNote.NoteMinDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditNote.MinLore"), id)))) + .withSlot(13) + .withActions(new SwitchPageAction(this.name, CURRENCY_NOTE_MIN_SELECTION_PAGE)) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("ARROW", 1) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditNote.CustomModelLore"), id)))) - .withSlot(14) - .withActions(new ChatAction((message)->{ + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditNote.CustomModelLore"), id)))) + .withSlot(14) + .withActions(new ChatAction((message)->{ - if(message.getPlayer().viewer().isPresent()) { + if(message.getPlayer().viewer().isPresent()) { - try { + try { - currency.getNote().get().setCustomModelData(Integer.parseInt(message.getMessage())); + currency.getNote().get().setCustomModelData(Integer.parseInt(message.getMessage())); - return true; - } catch(NumberFormatException ignore) {} - } - message.getPlayer().message("Enter custom model of the note item:"); - return false; - }), new RunnableAction((run)->run.player().message("Enter custom model of the note item:"))) - .withItemProvider((provider)->PluginCore.server().stackBuilder().of("PAPER", 1) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditNote.CustomModelLore"), id))) - .display(Component.text(String.valueOf(currency.getNote().get().getCustomModelData())))) - .build()); + return true; + } catch(NumberFormatException ignore) { } + } + message.getPlayer().message("Enter custom model of the note item:"); + return false; + }), new RunnableAction((run)->run.player().message("Enter custom model of the note item:"))) + .withItemProvider((provider)->PluginCore.server().stackBuilder().of("PAPER", 1) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditNote.CustomModelLore"), id))) + .display(Component.text(String.valueOf(currency.getNote().get().getCustomModelData())))) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditNote.NoteFeeDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditNote.NoteFeeLore"), id)))) - .withSlot(19) - .withActions(new SwitchPageAction(this.name, CURRENCY_NOTE_FEE_MAIN_PAGE)) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditNote.NoteFeeDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.EditNote.NoteFeeLore"), id)))) + .withSlot(19) + .withActions(new SwitchPageAction(this.name, CURRENCY_NOTE_FEE_MAIN_PAGE)) + .build()); } } } @@ -1112,7 +1112,7 @@ private void handleDenominationOpen(final PageOpenCallback callback) { message.getPlayer().viewer().get().addData(ACTIVE_DENOMINATION, denomObj); return true; - } catch(NumberFormatException ignore) {} + } catch(NumberFormatException ignore) { } } message.getPlayer().message("Enter a valid decimal for the weight of the denomination:"); return false; @@ -1126,7 +1126,7 @@ private void handleDenominationOpen(final PageOpenCallback callback) { callback.getPage().addIcon(new DenominationIcon(i, denomObj)); - i+= 2; + i += 2; } } } @@ -1161,164 +1161,164 @@ private void handleDenominationEditOpen(final PageOpenCallback callback) { final Denomination denomination = (Denomination)denomOpt.get(); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.SingularNameLore"), id)))) - .withSlot(10) - .withActions(new ChatAction((message)->{ + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.SingularNameLore"), id)))) + .withSlot(10) + .withActions(new ChatAction((message)->{ - if(message.getPlayer().viewer().isPresent()) { + if(message.getPlayer().viewer().isPresent()) { - denomination.setSingle(message.getMessage()); - viewer.get().addData(ACTIVE_DENOMINATION, denomination); - return true; - } - message.getPlayer().message("Enter a singular name for the denomination:"); - return false; + denomination.setSingle(message.getMessage()); + viewer.get().addData(ACTIVE_DENOMINATION, denomination); + return true; + } + message.getPlayer().message("Enter a singular name for the denomination:"); + return false; - }), new RunnableAction((run)->run.player().message("Enter a singular name for the denomination:"))) - .withItemProvider((provider)->PluginCore.server().stackBuilder().of("PAPER", 1) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.SingularNameLore"), id))) - .display(Component.text(denomination.singular()))) - .build()); + }), new RunnableAction((run)->run.player().message("Enter a singular name for the denomination:"))) + .withItemProvider((provider)->PluginCore.server().stackBuilder().of("PAPER", 1) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.SingularNameLore"), id))) + .display(Component.text(denomination.singular()))) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.PluralNameLore"), id)))) - .withSlot(11) - .withActions(new ChatAction((message)->{ + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.PluralNameLore"), id)))) + .withSlot(11) + .withActions(new ChatAction((message)->{ - if(message.getPlayer().viewer().isPresent()) { + if(message.getPlayer().viewer().isPresent()) { - denomination.setPlural(message.getMessage()); - viewer.get().addData(ACTIVE_DENOMINATION, denomination); - return true; - } - message.getPlayer().message("Enter a plural name for the denomination:"); - return false; + denomination.setPlural(message.getMessage()); + viewer.get().addData(ACTIVE_DENOMINATION, denomination); + return true; + } + message.getPlayer().message("Enter a plural name for the denomination:"); + return false; - }), new RunnableAction((run)->run.player().message("Enter a plural name for the denomination:"))) - .withItemProvider((provider)->PluginCore.server().stackBuilder().of("PAPER", 1) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.PluralNameLore"), id))) - .display(Component.text(denomination.plural()))) - .build()); + }), new RunnableAction((run)->run.player().message("Enter a plural name for the denomination:"))) + .withItemProvider((provider)->PluginCore.server().stackBuilder().of("PAPER", 1) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.PluralNameLore"), id))) + .display(Component.text(denomination.plural()))) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.SetWeightDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.SetWeightLore"), id)))) - .withSlot(12) - .withActions(new SwitchPageAction(this.name, DENOMINATION_WEIGHT_SELECTION_PAGE)) - .withItemProvider((provider)->PluginCore.server().stackBuilder().of("PAPER", 1) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.SetWeightLore"), id))) - .display(Component.text(denomination.weight().toString()))) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.SetWeightDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.SetWeightLore"), id)))) + .withSlot(12) + .withActions(new SwitchPageAction(this.name, DENOMINATION_WEIGHT_SELECTION_PAGE)) + .withItemProvider((provider)->PluginCore.server().stackBuilder().of("PAPER", 1) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.SetWeightLore"), id))) + .display(Component.text(denomination.weight().toString()))) + .build()); if(denomination instanceof ItemDenomination itemDenomination) { callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of(itemDenomination.getMaterial(), 1) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.SetMaterialLore"), id)))) - .withSlot(13) - .withActions(new SwitchPageAction(this.name, DENOMINATION_MATERIAL_PAGE)) - .build()); + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.SetMaterialLore"), id)))) + .withSlot(13) + .withActions(new SwitchPageAction(this.name, DENOMINATION_MATERIAL_PAGE)) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.DisplayNameLore"), id)))) - .withSlot(14) - .withActions(new ChatAction((message)->{ + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.DisplayNameLore"), id)))) + .withSlot(14) + .withActions(new ChatAction((message)->{ - if(message.getPlayer().viewer().isPresent()) { + if(message.getPlayer().viewer().isPresent()) { - itemDenomination.setName(message.getMessage()); - return true; - } - message.getPlayer().message("Enter display name of the denomination item:"); - return false; - }), new RunnableAction((run)->run.player().message("Enter display name of the denomination item:"))) - .withItemProvider((provider)->{ + itemDenomination.setName(message.getMessage()); + return true; + } + message.getPlayer().message("Enter display name of the denomination item:"); + return false; + }), new RunnableAction((run)->run.player().message("Enter display name of the denomination item:"))) + .withItemProvider((provider)->{ - final String message = (itemDenomination.getName() != null)? itemDenomination.getName() : "No Display"; + final String message = (itemDenomination.getName() != null)? itemDenomination.getName() : "No Display"; - return PluginCore.server().stackBuilder().of("PAPER", 1) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.DisplayNameLore"), id))) - .display(Component.text(message)); - }) - .build()); + return PluginCore.server().stackBuilder().of("PAPER", 1) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.DisplayNameLore"), id))) + .display(Component.text(message)); + }) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.CustomModelLore"), id)))) - .withSlot(15) - .withActions(new ChatAction((message)->{ - - if(message.getPlayer().viewer().isPresent()) { - - try { - - itemDenomination.setCustomModel(Integer.parseInt(message.getMessage())); - return true; - } catch(NumberFormatException ignore) {} - } - message.getPlayer().message("Enter custom model of the denomination item:"); - return false; - }), new RunnableAction((run)->run.player().message("Enter custom model of the denomination item:"))) - .withItemProvider((provider)->PluginCore.server().stackBuilder().of("PAPER", 1) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.CustomModelLore"), id))) - .display(Component.text(String.valueOf(itemDenomination.getCustomModel())))) - .build()); + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.CustomModelLore"), id)))) + .withSlot(15) + .withActions(new ChatAction((message)->{ + + if(message.getPlayer().viewer().isPresent()) { + + try { + + itemDenomination.setCustomModel(Integer.parseInt(message.getMessage())); + return true; + } catch(NumberFormatException ignore) { } + } + message.getPlayer().message("Enter custom model of the denomination item:"); + return false; + }), new RunnableAction((run)->run.player().message("Enter custom model of the denomination item:"))) + .withItemProvider((provider)->PluginCore.server().stackBuilder().of("PAPER", 1) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.CustomModelLore"), id))) + .display(Component.text(String.valueOf(itemDenomination.getCustomModel())))) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.SetBase64TextureLore"), id)))) - .withSlot(16) - .withActions(new ChatAction((message)->{ - - if(message.getPlayer().viewer().isPresent()) { - itemDenomination.setTexture(message.getMessage()); - return true; - } - message.getPlayer().message("Enter the base64 texture to use if the material of the denomination item is PLAYER_HEAD:"); - return false; - }), new RunnableAction((run)->run.player().message("Enter the base64 texture to use if the material of the denomination item is PLAYER_HEAD:"))) - .withItemProvider((provider)->{ - - final String message = (itemDenomination.getTexture() != null)? itemDenomination.getTexture() : "No Texture"; - - return PluginCore.server().stackBuilder().of("PAPER", 1) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.SetBase64TextureLore"), id))) - .display(Component.text(message)); - }) - .build()); + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.SetBase64TextureLore"), id)))) + .withSlot(16) + .withActions(new ChatAction((message)->{ + + if(message.getPlayer().viewer().isPresent()) { + itemDenomination.setTexture(message.getMessage()); + return true; + } + message.getPlayer().message("Enter the base64 texture to use if the material of the denomination item is PLAYER_HEAD:"); + return false; + }), new RunnableAction((run)->run.player().message("Enter the base64 texture to use if the material of the denomination item is PLAYER_HEAD:"))) + .withItemProvider((provider)->{ + + final String message = (itemDenomination.getTexture() != null)? itemDenomination.getTexture() : "No Texture"; + + return PluginCore.server().stackBuilder().of("PAPER", 1) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.SetBase64TextureLore"), id))) + .display(Component.text(message)); + }) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.LoreStringLore"), id)))) - .withSlot(17) - .withActions(new ChatAction((message)->{ - - if(message.getPlayer().viewer().isPresent()) { - message.getPlayer().viewer().get().addData("DENOMINATION_LORE", message.getMessage()); - return true; - } - message.getPlayer().message("Enter the lore string this denomination item must have in order to be considered currency. Use newline for a different line:"); - return false; - }), new RunnableAction((run)->run.player().message("Enter the lore string this denomination item must have in order to be considered currency. Use newline for a different line:"))) - .withItemProvider((provider)->{ - - final String message = (provider.viewer().isPresent())? (String)provider.viewer().get().dataOrDefault("DENOMINATION_LORE", "No Lore") : "No Lore"; - - return PluginCore.server().stackBuilder().of("PAPER", 1) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.LoreStringLore"), id))) - .display(Component.text(message)); - }) - .build()); + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.LoreStringLore"), id)))) + .withSlot(17) + .withActions(new ChatAction((message)->{ + + if(message.getPlayer().viewer().isPresent()) { + message.getPlayer().viewer().get().addData("DENOMINATION_LORE", message.getMessage()); + return true; + } + message.getPlayer().message("Enter the lore string this denomination item must have in order to be considered currency. Use newline for a different line:"); + return false; + }), new RunnableAction((run)->run.player().message("Enter the lore string this denomination item must have in order to be considered currency. Use newline for a different line:"))) + .withItemProvider((provider)->{ + + final String message = (provider.viewer().isPresent())? (String)provider.viewer().get().dataOrDefault("DENOMINATION_LORE", "No Lore") : "No Lore"; + + return PluginCore.server().stackBuilder().of("PAPER", 1) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.LoreStringLore"), id))) + .display(Component.text(message)); + }) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.FlagsDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.FlagsLore"), id)))) - .withSlot(18) - .withActions(new SwitchPageAction(this.name, DENOMINATION_FLAGS_PAGE)) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.FlagsDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.FlagsLore"), id)))) + .withSlot(18) + .withActions(new SwitchPageAction(this.name, DENOMINATION_FLAGS_PAGE)) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.EnchantsDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.EnchantsLore"), id)))) - .withSlot(19) - .withActions(new SwitchPageAction(this.name, DENOMINATION_ENCHANTS_PAGE)) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.EnchantsDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.DenomEdit.EnchantsLore"), id)))) + .withSlot(19) + .withActions(new SwitchPageAction(this.name, DENOMINATION_ENCHANTS_PAGE)) + .build()); } } } diff --git a/Core/src/net/tnemc/core/menu/TransactionMenu.java b/Core/src/net/tnemc/core/menu/TransactionMenu.java index bdafe24b..7abaee37 100644 --- a/Core/src/net/tnemc/core/menu/TransactionMenu.java +++ b/Core/src/net/tnemc/core/menu/TransactionMenu.java @@ -53,6 +53,7 @@ public class TransactionMenu extends Menu { public static final int TRANSACTION_HISTORY_COUNT = 10; public TransactionMenu() { + this.name = "transaction_menu"; this.title = "Transactions"; this.rows = 4; @@ -90,18 +91,18 @@ public void handleMainPage(final PageOpenCallback callback) { if(maxPages > 1) { callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("RED_WOOL", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.PreviousPageDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.PreviousPage"), id)))) - .withActions(new DataAction(TRANSACTION_PAGE_ID, prev), new SwitchPageAction(this.name, 1)) - .withSlot(0) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.PreviousPageDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.PreviousPage"), id)))) + .withActions(new DataAction(TRANSACTION_PAGE_ID, prev), new SwitchPageAction(this.name, 1)) + .withSlot(0) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("GREEN_WOOL", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.NextPageDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.NextPage"), id)))) - .withActions(new DataAction(TRANSACTION_PAGE_ID, next), new SwitchPageAction(this.name, 1)) - .withSlot(8) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.NextPageDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.NextPage"), id)))) + .withActions(new DataAction(TRANSACTION_PAGE_ID, next), new SwitchPageAction(this.name, 1)) + .withSlot(8) + .build()); } int slot = 9; @@ -132,7 +133,7 @@ protected Icon buildTransactionIcon(final int slot, final UUID transaction) { lore.add(Component.text("Click for information.")); return new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1) - .display(Component.text(transaction.toString())).lore(lore)) + .display(Component.text(transaction.toString())).lore(lore)) .withSlot(slot) .withActions(new SwitchPageAction(this.name, TRANSACTION_VIEW)).build(); } diff --git a/Core/src/net/tnemc/core/menu/constraints/TNEStringConstraints.java b/Core/src/net/tnemc/core/menu/constraints/TNEStringConstraints.java index b293fbd5..34c53eaa 100644 --- a/Core/src/net/tnemc/core/menu/constraints/TNEStringConstraints.java +++ b/Core/src/net/tnemc/core/menu/constraints/TNEStringConstraints.java @@ -31,11 +31,13 @@ public enum TNEStringConstraints implements StringConstraint { CURRENCY_UUID { @Override public String identifier() { + return "CURRENCY_UUID"; } @Override public String defaultValue() { + return "----"; } } diff --git a/Core/src/net/tnemc/core/menu/handlers/AmountSelectionHandler.java b/Core/src/net/tnemc/core/menu/handlers/AmountSelectionHandler.java index 9585ee6b..f8988d82 100644 --- a/Core/src/net/tnemc/core/menu/handlers/AmountSelectionHandler.java +++ b/Core/src/net/tnemc/core/menu/handlers/AmountSelectionHandler.java @@ -34,15 +34,18 @@ public class AmountSelectionHandler { private final BigDecimal amount; public AmountSelectionHandler(MenuClickHandler click, BigDecimal amount) { + this.click = click; this.amount = amount; } public MenuClickHandler getClick() { + return click; } public BigDecimal getAmount() { + return amount; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/menu/handlers/StringSelectionHandler.java b/Core/src/net/tnemc/core/menu/handlers/StringSelectionHandler.java index 5b84fcab..8780757c 100644 --- a/Core/src/net/tnemc/core/menu/handlers/StringSelectionHandler.java +++ b/Core/src/net/tnemc/core/menu/handlers/StringSelectionHandler.java @@ -32,15 +32,18 @@ public class StringSelectionHandler { private final String value; public StringSelectionHandler(MenuClickHandler click, String value) { + this.click = click; this.value = value; } public MenuClickHandler getClick() { + return click; } public String getValue() { + return value; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/menu/icons/actions/PageSwitchWithClose.java b/Core/src/net/tnemc/core/menu/icons/actions/PageSwitchWithClose.java index 96e19878..e9f534da 100644 --- a/Core/src/net/tnemc/core/menu/icons/actions/PageSwitchWithClose.java +++ b/Core/src/net/tnemc/core/menu/icons/actions/PageSwitchWithClose.java @@ -35,12 +35,14 @@ public class PageSwitchWithClose extends IconAction { private final int page; public PageSwitchWithClose(String menu, int page) { + super(ActionType.ANY); this.menu = menu; this.page = page; } public PageSwitchWithClose(String menu, int page, ActionType type) { + super(type); this.menu = menu; this.page = page; diff --git a/Core/src/net/tnemc/core/menu/icons/myeco/CurrencyIcon.java b/Core/src/net/tnemc/core/menu/icons/myeco/CurrencyIcon.java index 3f5546e8..bc9186be 100644 --- a/Core/src/net/tnemc/core/menu/icons/myeco/CurrencyIcon.java +++ b/Core/src/net/tnemc/core/menu/icons/myeco/CurrencyIcon.java @@ -37,10 +37,12 @@ * @since 0.1.3.0 */ public class CurrencyIcon extends SwitchPageIcon { + public CurrencyIcon(int slot, Currency currency) { + super(slot, PluginCore.server().stackBuilder().of(currency.getIconMaterial(), 1) - .display(Component.text(currency.getIdentifier())).lore(Collections.singletonList(Component.text("Click to edit currency"))), - "my_eco", CURRENCY_EDIT_PAGE, ActionType.ANY, false); + .display(Component.text(currency.getIdentifier())).lore(Collections.singletonList(Component.text("Click to edit currency"))), + "my_eco", CURRENCY_EDIT_PAGE, ActionType.ANY, false); actions.add(new DataAction(ACTIVE_CURRENCY, currency)); diff --git a/Core/src/net/tnemc/core/menu/icons/myeco/DenominationIcon.java b/Core/src/net/tnemc/core/menu/icons/myeco/DenominationIcon.java index a95062f0..2f25e7e8 100644 --- a/Core/src/net/tnemc/core/menu/icons/myeco/DenominationIcon.java +++ b/Core/src/net/tnemc/core/menu/icons/myeco/DenominationIcon.java @@ -39,9 +39,10 @@ public class DenominationIcon extends SwitchPageIcon { public DenominationIcon(int slot, final Denomination denomination) { + super(slot, PluginCore.server().stackBuilder().of((denomination instanceof ItemDenomination)? ((ItemDenomination)denomination).getMaterial() : "PAPER", 1) - .display(Component.text(denomination.weight().toString())).lore(Collections.singletonList(Component.text("Click to edit denomination"))), - "my_eco", DENOMINATION_EDIT_PAGE, ActionType.ANY, false); + .display(Component.text(denomination.weight().toString())).lore(Collections.singletonList(Component.text("Click to edit denomination"))), + "my_eco", DENOMINATION_EDIT_PAGE, ActionType.ANY, false); actions.add(new DataAction("ACTIVE_DENOMINATION", denomination)); diff --git a/Core/src/net/tnemc/core/menu/icons/myeco/SaveCurrencyIcon.java b/Core/src/net/tnemc/core/menu/icons/myeco/SaveCurrencyIcon.java index 3fdc7b46..d06cabd3 100644 --- a/Core/src/net/tnemc/core/menu/icons/myeco/SaveCurrencyIcon.java +++ b/Core/src/net/tnemc/core/menu/icons/myeco/SaveCurrencyIcon.java @@ -36,15 +36,16 @@ * @since 0.1.3.0 */ public class SaveCurrencyIcon extends SwitchPageIcon { + public SaveCurrencyIcon(int slot, final Currency currency) { + super(slot, PluginCore.server().stackBuilder().of("GREEN_WOOL", 1) - .display(Component.text(currency.getIdentifier())).lore(Collections.singletonList(Component.text("Click to Save Currency"))), - "my_eco", CURRENCIES_PAGE, ActionType.ANY, false); + .display(Component.text(currency.getIdentifier())).lore(Collections.singletonList(Component.text("Click to Save Currency"))), + "my_eco", CURRENCIES_PAGE, ActionType.ANY, false); addAction(new RunnableAction((click->{ - }))); addActions(); diff --git a/Core/src/net/tnemc/core/menu/icons/shared/PreviousMenuIcon.java b/Core/src/net/tnemc/core/menu/icons/shared/PreviousMenuIcon.java index 752a3dfa..60410fe9 100644 --- a/Core/src/net/tnemc/core/menu/icons/shared/PreviousMenuIcon.java +++ b/Core/src/net/tnemc/core/menu/icons/shared/PreviousMenuIcon.java @@ -33,6 +33,7 @@ public class PreviousMenuIcon extends Icon { public PreviousMenuIcon(int slot, final String menu, final ActionType type) { + super(PluginCore.server().stackBuilder().of("RED_WOOL", 1).display(Component.text("Previous Menu")), null); this.slot = slot; diff --git a/Core/src/net/tnemc/core/menu/icons/shared/PreviousPageIcon.java b/Core/src/net/tnemc/core/menu/icons/shared/PreviousPageIcon.java index b41fa7a0..920c26f9 100644 --- a/Core/src/net/tnemc/core/menu/icons/shared/PreviousPageIcon.java +++ b/Core/src/net/tnemc/core/menu/icons/shared/PreviousPageIcon.java @@ -33,6 +33,7 @@ public class PreviousPageIcon extends Icon { public PreviousPageIcon(int slot, final String menu, final int page, final ActionType type) { + super(PluginCore.server().stackBuilder().of("RED_WOOL", 1).display(Component.text("Previous Page")), null); this.slot = slot; diff --git a/Core/src/net/tnemc/core/menu/icons/shared/SwitchMenuIcon.java b/Core/src/net/tnemc/core/menu/icons/shared/SwitchMenuIcon.java index 6ab9c661..5303812a 100644 --- a/Core/src/net/tnemc/core/menu/icons/shared/SwitchMenuIcon.java +++ b/Core/src/net/tnemc/core/menu/icons/shared/SwitchMenuIcon.java @@ -31,7 +31,9 @@ * @since 0.1.3.0 */ public class SwitchMenuIcon extends Icon { + public SwitchMenuIcon(int slot, @NotNull AbstractItemStack item, final String menu, final ActionType type) { + super(item, null); this.slot = slot; diff --git a/Core/src/net/tnemc/core/menu/icons/shared/SwitchPageIcon.java b/Core/src/net/tnemc/core/menu/icons/shared/SwitchPageIcon.java index b1a32591..869a7129 100644 --- a/Core/src/net/tnemc/core/menu/icons/shared/SwitchPageIcon.java +++ b/Core/src/net/tnemc/core/menu/icons/shared/SwitchPageIcon.java @@ -37,9 +37,12 @@ public class SwitchPageIcon extends Icon { private final ActionType actionType; public SwitchPageIcon(int slot, @NotNull AbstractItemStack item, final String menu, final int page, final ActionType type) { + this(slot, item, menu, page, type, true); } + public SwitchPageIcon(int slot, @NotNull AbstractItemStack item, final String menu, final int page, final ActionType type, boolean registerAction) { + super(item, null); this.slot = slot; @@ -53,6 +56,7 @@ public SwitchPageIcon(int slot, @NotNull AbstractItemStack item, final String } public void addActions() { + actions.add(new SwitchPageAction(menu, page, actionType)); } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/menu/page/mybal/MyBalAmountSelectionPage.java b/Core/src/net/tnemc/core/menu/page/mybal/MyBalAmountSelectionPage.java index 9f964a14..a4b1d864 100644 --- a/Core/src/net/tnemc/core/menu/page/mybal/MyBalAmountSelectionPage.java +++ b/Core/src/net/tnemc/core/menu/page/mybal/MyBalAmountSelectionPage.java @@ -45,23 +45,25 @@ public class MyBalAmountSelectionPage extends AmountSelectionPage { public MyBalAmountSelectionPage(String amtID, String returnMenu, String menuName, int menuPage, int returnPage, final Consumer selectionListener) { + super(amtID, returnMenu, menuName, menuPage, returnPage, selectionListener); } @Override public void handle(PageOpenCallback callback) { + super.handle(callback); final Optional viewer = callback.getPlayer().viewer(); if(viewer.isPresent()) { callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("STONE_BUTTON", 1) - .display(Component.text("Add Max")) - .lore(Collections.singletonList(Component.text("Adds your entire balance.")))) - .withActions(new SwitchPageAction(menuName, menuPage)) - .withClick((click)->balAddClick(click, ((BigDecimal)viewer.get().dataOrDefault(MyBalMenu.ACTION_MAX_HOLDINGS, BigDecimal.ZERO)))) - .withSlot(31) - .build()); + .display(Component.text("Add Max")) + .lore(Collections.singletonList(Component.text("Adds your entire balance.")))) + .withActions(new SwitchPageAction(menuName, menuPage)) + .withClick((click)->balAddClick(click, ((BigDecimal)viewer.get().dataOrDefault(MyBalMenu.ACTION_MAX_HOLDINGS, BigDecimal.ZERO)))) + .withSlot(31) + .build()); final Optional name = viewer.get().findData(MyBalMenu.ACTION_ACCOUNT_ID + "_NAME"); final Optional id = viewer.get().findData(MyBalMenu.ACTION_ACCOUNT_ID + "_ID"); @@ -77,15 +79,15 @@ public void handle(PageOpenCallback callback) { profile.setUuid(account); } - } catch(Exception ignore) {} + } catch(Exception ignore) { } callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PLAYER_HEAD", 1) - .display(Component.text((String)name.get())) - .lore(Collections.singletonList(Component.text("Player action will be performed on."))) - .profile(profile)) - .withActions(new SwitchPageAction(menuName, menuPage)) - .withSlot(13) - .build()); + .display(Component.text((String)name.get())) + .lore(Collections.singletonList(Component.text("Player action will be performed on."))) + .profile(profile)) + .withActions(new SwitchPageAction(menuName, menuPage)) + .withSlot(13) + .build()); } } } diff --git a/Core/src/net/tnemc/core/menu/page/myeco/FormatSelectionPage.java b/Core/src/net/tnemc/core/menu/page/myeco/FormatSelectionPage.java index fb1ed404..25c503b0 100644 --- a/Core/src/net/tnemc/core/menu/page/myeco/FormatSelectionPage.java +++ b/Core/src/net/tnemc/core/menu/page/myeco/FormatSelectionPage.java @@ -61,6 +61,7 @@ public class FormatSelectionPage { public FormatSelectionPage(String formatID, String returnMenu, String menuName, final int menuPage, final int returnPage, String formatPageID, final int menuRows, Consumer selectionListener) { + this.returnMenu = returnMenu; this.menuName = menuName; this.menuPage = menuPage; @@ -90,86 +91,86 @@ public void handle(final PageOpenCallback callback) { if(maxPages > 1) { callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("RED_WOOL", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.PreviousPageDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.PreviousPage"), id)))) - .withActions(new DataAction(formatPageID, prev), new SwitchPageAction(menuName, menuPage)) - .withSlot(0) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.PreviousPageDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.PreviousPage"), id)))) + .withActions(new DataAction(formatPageID, prev), new SwitchPageAction(menuName, menuPage)) + .withSlot(0) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("GREEN_WOOL", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.NextPageDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.NextPage"), id)))) - .withActions(new DataAction(formatPageID, next), new SwitchPageAction(menuName, menuPage)) - .withSlot(8) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.NextPageDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.NextPage"), id)))) + .withActions(new DataAction(formatPageID, next), new SwitchPageAction(menuName, menuPage)) + .withSlot(8) + .build()); } callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("ARROW", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.Format.Space"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.Format.Add"), id)))) - .withActions(new SwitchPageAction(menuName, menuPage)) - .withClick((click)->formatAddClick(click, " ")) - .withSlot(2) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.Format.Space"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.Format.Add"), id)))) + .withActions(new SwitchPageAction(menuName, menuPage)) + .withClick((click)->formatAddClick(click, " ")) + .withSlot(2) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("ARROW", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.Format.OwnDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.Format.Own"), id)))) - .withActions(new ChatAction((message)->{ + .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.Format.OwnDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.Format.Own"), id)))) + .withActions(new ChatAction((message)->{ - if(message.getPlayer().viewer().isPresent() && !message.getMessage().isEmpty()) { + if(message.getPlayer().viewer().isPresent() && !message.getMessage().isEmpty()) { - addToClickData(message.getPlayer().viewer().get(), message.getMessage()); - return true; - } + addToClickData(message.getPlayer().viewer().get(), message.getMessage()); + return true; + } - message.getPlayer().message("Enter your own text to add to the format:"); - return false; + message.getPlayer().message("Enter your own text to add to the format:"); + return false; - }), new RunnableAction((run)->run.player().message("Enter your own text to add to the format:")), - new SwitchPageAction(menuName, menuPage)) - .withSlot(5) - .build()); + }), new RunnableAction((run)->run.player().message("Enter your own text to add to the format:")), + new SwitchPageAction(menuName, menuPage)) + .withSlot(5) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("BLACK_WOOL", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.Format.ResetDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.Format.Reset"), id)))) - .withClick((click)->click.player().viewer().ifPresent(menuViewer->menuViewer.addData(formatID, ""))) - .withActions(new SwitchPageAction(menuName, menuPage)) - .withSlot(6) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.Format.ResetDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.Format.Reset"), id)))) + .withClick((click)->click.player().viewer().ifPresent(menuViewer->menuViewer.addData(formatID, ""))) + .withActions(new SwitchPageAction(menuName, menuPage)) + .withSlot(6) + .build()); //TODO: Fix display final Optional formatData = viewer.get().findData(formatID); final Component display = (formatData.isPresent())? Component.text((String)formatData.get()) : MessageHandler.grab(new MessageData("Messages.Menu.MyEco.Format.None"), id); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("ARROW", 1) - .display(display) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.Format.Format"), id)))) - .withActions(new SwitchPageAction(menuName, menuPage)) - .withSlot(4) - .build()); + .display(display) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.Format.Format"), id)))) + .withActions(new SwitchPageAction(menuName, menuPage)) + .withSlot(4) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("BARRIER", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.EscapeDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.Escape"), id)))) - .withActions(new SwitchPageAction(returnMenu, returnPage)) - .withSlot(1) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.EscapeDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.Escape"), id)))) + .withActions(new SwitchPageAction(returnMenu, returnPage)) + .withSlot(1) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("ARROW", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.Save"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.Format.Save"), id)))) - .withActions(new RunnableAction((click)->{ + .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.Save"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.Format.Save"), id)))) + .withActions(new RunnableAction((click)->{ - if(selectionListener != null) { + if(selectionListener != null) { - selectionListener.accept(new StringSelectionHandler(click, (String)viewer.get().dataOrDefault(formatID, ""))); - } - }), new SwitchPageAction(returnMenu, returnPage)) - .withSlot(7) - .build()); + selectionListener.accept(new StringSelectionHandler(click, (String)viewer.get().dataOrDefault(formatID, ""))); + } + }), new SwitchPageAction(returnMenu, returnPage)) + .withSlot(7) + .build()); final String[] stringSet = CurrencyFormatter.rules().keySet().toArray(new String[CurrencyFormatter.rules().size()]); @@ -194,12 +195,12 @@ public void handle(final PageOpenCallback callback) { lore.set(1, Component.text(rule.description())); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1) - .display(Component.text(rule.name())) - .lore(lore)) - .withActions(new SwitchPageAction(menuName, menuPage)) - .withClick((click)->formatAddClick(click, rule.name())) - .withSlot(slot) - .build()); + .display(Component.text(rule.name())) + .lore(lore)) + .withActions(new SwitchPageAction(menuName, menuPage)) + .withClick((click)->formatAddClick(click, rule.name())) + .withSlot(slot) + .build()); slot++; } diff --git a/Core/src/net/tnemc/core/menu/page/shared/AccountSelectionPage.java b/Core/src/net/tnemc/core/menu/page/shared/AccountSelectionPage.java index 72b65d55..6298384a 100644 --- a/Core/src/net/tnemc/core/menu/page/shared/AccountSelectionPage.java +++ b/Core/src/net/tnemc/core/menu/page/shared/AccountSelectionPage.java @@ -55,6 +55,7 @@ public class AccountSelectionPage { public AccountSelectionPage(String accountDataID, String returnMenu, String menuName, final int menuPage, final int returnPage, String accountPageID, final int menuRows) { + this.returnMenu = returnMenu; this.menuName = menuName; this.menuPage = menuPage; @@ -84,26 +85,26 @@ public void handle(final PageOpenCallback callback) { if(maxPages > 1) { callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("RED_WOOL", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.PreviousPageDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.PreviousPage"), id)))) - .withActions(new DataAction(accountPageID, prev), new SwitchPageAction(menuName, menuPage)) - .withSlot(0) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.PreviousPageDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.PreviousPage"), id)))) + .withActions(new DataAction(accountPageID, prev), new SwitchPageAction(menuName, menuPage)) + .withSlot(0) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("GREEN_WOOL", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.NextPageDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.NextPage"), id)))) - .withActions(new DataAction(accountPageID, next), new SwitchPageAction(menuName, menuPage)) - .withSlot(8) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.NextPageDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.NextPage"), id)))) + .withActions(new DataAction(accountPageID, next), new SwitchPageAction(menuName, menuPage)) + .withSlot(8) + .build()); } callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("BARRIER", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.EscapeDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.Escape"), id)))) - .withActions(new SwitchPageAction(returnMenu, returnPage)) - .withSlot(4) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.EscapeDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.Escape"), id)))) + .withActions(new SwitchPageAction(returnMenu, returnPage)) + .withSlot(4) + .build()); int i = 0; for(Map.Entry entry : TNECore.eco().account().getAccounts().entrySet()) { @@ -127,18 +128,18 @@ public void handle(final PageOpenCallback callback) { } } - } catch(Exception ignore) {} + } catch(Exception ignore) { } callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PLAYER_HEAD", 1) - .display(Component.text(entry.getValue().getName())) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.Account.Select"), id))) - .profile(profile)) - .withActions(new DataAction(accountDataID + "_ID", entry.getKey()), - new DataAction(accountDataID + "_NAME", entry.getValue().getName()), - new SwitchPageAction(returnMenu, returnPage)) - .withSlot(9 + (i - start)) - .build()); + .display(Component.text(entry.getValue().getName())) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.Account.Select"), id))) + .profile(profile)) + .withActions(new DataAction(accountDataID + "_ID", entry.getKey()), + new DataAction(accountDataID + "_NAME", entry.getValue().getName()), + new SwitchPageAction(returnMenu, returnPage)) + .withSlot(9 + (i - start)) + .build()); i++; } diff --git a/Core/src/net/tnemc/core/menu/page/shared/AmountSelectionPage.java b/Core/src/net/tnemc/core/menu/page/shared/AmountSelectionPage.java index 39d73518..48e3c2a5 100644 --- a/Core/src/net/tnemc/core/menu/page/shared/AmountSelectionPage.java +++ b/Core/src/net/tnemc/core/menu/page/shared/AmountSelectionPage.java @@ -53,6 +53,7 @@ public class AmountSelectionPage { public AmountSelectionPage(String amtID, String returnMenu, String menuName, final int menuPage, final int returnPage, Consumer selectionListener) { + this.returnMenu = returnMenu; this.menuName = menuName; this.menuPage = menuPage; @@ -67,144 +68,144 @@ public void handle(final PageOpenCallback callback) { if(viewer.isPresent()) { callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("BARRIER", 1) - .display(Component.text("Escape Menu")) - .lore(Collections.singletonList(Component.text("Click to exit this menu.")))) - .withActions(new PageSwitchWithClose(returnMenu, returnPage)) - .withSlot(0) - .build()); + .display(Component.text("Escape Menu")) + .lore(Collections.singletonList(Component.text("Click to exit this menu.")))) + .withActions(new PageSwitchWithClose(returnMenu, returnPage)) + .withSlot(0) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("GREEN_WOOL", 1) - .display(Component.text("Save.")) - .lore(Collections.singletonList(Component.text("Click save the amount.")))) - .withActions(new RunnableAction((click)->{ - if(selectionListener != null) { + .display(Component.text("Save.")) + .lore(Collections.singletonList(Component.text("Click save the amount.")))) + .withActions(new RunnableAction((click)->{ + if(selectionListener != null) { - selectionListener.accept(new AmountSelectionHandler(click, ((BigDecimal)viewer.get().dataOrDefault(amtID, BigDecimal.ZERO)))); - } - }), new PageSwitchWithClose(returnMenu, returnPage)) - .withSlot(8) - .build()); + selectionListener.accept(new AmountSelectionHandler(click, ((BigDecimal)viewer.get().dataOrDefault(amtID, BigDecimal.ZERO)))); + } + }), new PageSwitchWithClose(returnMenu, returnPage)) + .withSlot(8) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("ARROW", 1) - .display(Component.text("Enter your own")) - .lore(Collections.singletonList(Component.text("Click to enter a custom amount.")))) - .withActions(new ChatAction((message)->{ + .display(Component.text("Enter your own")) + .lore(Collections.singletonList(Component.text("Click to enter a custom amount.")))) + .withActions(new ChatAction((message)->{ - if(message.getPlayer().viewer().isPresent() && !message.getMessage().isEmpty()) { + if(message.getPlayer().viewer().isPresent() && !message.getMessage().isEmpty()) { - try { + try { - message.getPlayer().viewer().get().addData(amtID, new BigDecimal(message.getMessage())); - return true; - } catch(NumberFormatException ignore) {} - } + message.getPlayer().viewer().get().addData(amtID, new BigDecimal(message.getMessage())); + return true; + } catch(NumberFormatException ignore) { } + } - message.getPlayer().message("Enter a valid decimal value:"); - return false; + message.getPlayer().message("Enter a valid decimal value:"); + return false; - }), new RunnableAction((run)->run.player().message("Enter a valid decimal value:"))) - .withSlot(2) - .build()); + }), new RunnableAction((run)->run.player().message("Enter a valid decimal value:"))) + .withSlot(2) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1) - .display(Component.text(((BigDecimal)viewer.get().dataOrDefault(amtID, BigDecimal.ZERO)).toPlainString())) - .lore(Collections.singletonList(Component.text("The amount")))) - .withActions(new SwitchPageAction(menuName, menuPage)) - .withSlot(4) - .build()); + .display(Component.text(((BigDecimal)viewer.get().dataOrDefault(amtID, BigDecimal.ZERO)).toPlainString())) + .lore(Collections.singletonList(Component.text("The amount")))) + .withActions(new SwitchPageAction(menuName, menuPage)) + .withSlot(4) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("BLACK_WOOL", 1) - .display(Component.text("Reset To Zero")) - .lore(Collections.singletonList(Component.text("Click to reset the amount to zero.")))) - .withClick((click)->click.player().viewer().ifPresent(menuViewer->menuViewer.addData(amtID, BigDecimal.ZERO))) - .withActions(new SwitchPageAction(menuName, menuPage)) - .withSlot(6) - .build()); + .display(Component.text("Reset To Zero")) + .lore(Collections.singletonList(Component.text("Click to reset the amount to zero.")))) + .withClick((click)->click.player().viewer().ifPresent(menuViewer->menuViewer.addData(amtID, BigDecimal.ZERO))) + .withActions(new SwitchPageAction(menuName, menuPage)) + .withSlot(6) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("STONE_BUTTON", 1) - .display(Component.text("Add 100"))) - .withActions(new SwitchPageAction(menuName, menuPage)) - .withClick((click)->balAddClick(click, new BigDecimal("100"))) - .withSlot(15) - .build()); + .display(Component.text("Add 100"))) + .withActions(new SwitchPageAction(menuName, menuPage)) + .withClick((click)->balAddClick(click, new BigDecimal("100"))) + .withSlot(15) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("STONE_BUTTON", 1) - .display(Component.text("Add 50"))) - .withActions(new SwitchPageAction(menuName, menuPage)) - .withClick((click)->balAddClick(click, new BigDecimal("50"))) - .withSlot(17) - .build()); + .display(Component.text("Add 50"))) + .withActions(new SwitchPageAction(menuName, menuPage)) + .withClick((click)->balAddClick(click, new BigDecimal("50"))) + .withSlot(17) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("STONE_BUTTON", 1) - .display(Component.text("Add 10"))) - .withActions(new SwitchPageAction(menuName, menuPage)) - .withClick((click)->balAddClick(click, new BigDecimal("10"))) - .withSlot(33) - .build()); + .display(Component.text("Add 10"))) + .withActions(new SwitchPageAction(menuName, menuPage)) + .withClick((click)->balAddClick(click, new BigDecimal("10"))) + .withSlot(33) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("STONE_BUTTON", 1) - .display(Component.text("Add 1"))) - .withActions(new SwitchPageAction(menuName, menuPage)) - .withClick((click)->balAddClick(click, new BigDecimal("1"))) - .withSlot(35) - .build()); + .display(Component.text("Add 1"))) + .withActions(new SwitchPageAction(menuName, menuPage)) + .withClick((click)->balAddClick(click, new BigDecimal("1"))) + .withSlot(35) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("STONE_BUTTON", 1) - .display(Component.text("Add .10"))) - .withActions(new SwitchPageAction(menuName, menuPage)) - .withClick((click)->balAddClick(click, new BigDecimal(".10"))) - .withSlot(51) - .build()); + .display(Component.text("Add .10"))) + .withActions(new SwitchPageAction(menuName, menuPage)) + .withClick((click)->balAddClick(click, new BigDecimal(".10"))) + .withSlot(51) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("STONE_BUTTON", 1) - .display(Component.text("Add .01"))) - .withActions(new SwitchPageAction(menuName, menuPage)) - .withClick((click)->balAddClick(click, new BigDecimal(".01"))) - .withSlot(53) - .build()); + .display(Component.text("Add .01"))) + .withActions(new SwitchPageAction(menuName, menuPage)) + .withClick((click)->balAddClick(click, new BigDecimal(".01"))) + .withSlot(53) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("STONE_BUTTON", 1) - .display(Component.text("Remove 100"))) - .withActions(new SwitchPageAction(menuName, menuPage)) - .withClick((click)->balAddClick(click, new BigDecimal("-100"))) - .withSlot(11) - .build()); + .display(Component.text("Remove 100"))) + .withActions(new SwitchPageAction(menuName, menuPage)) + .withClick((click)->balAddClick(click, new BigDecimal("-100"))) + .withSlot(11) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("STONE_BUTTON", 1) - .display(Component.text("Remove 50"))) - .withActions(new SwitchPageAction(menuName, menuPage)) - .withClick((click)->balAddClick(click, new BigDecimal("-50"))) - .withSlot(9) - .build()); + .display(Component.text("Remove 50"))) + .withActions(new SwitchPageAction(menuName, menuPage)) + .withClick((click)->balAddClick(click, new BigDecimal("-50"))) + .withSlot(9) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("STONE_BUTTON", 1) - .display(Component.text("Remove 10"))) - .withActions(new SwitchPageAction(menuName, menuPage)) - .withClick((click)->balAddClick(click, new BigDecimal("-10"))) - .withSlot(29) - .build()); + .display(Component.text("Remove 10"))) + .withActions(new SwitchPageAction(menuName, menuPage)) + .withClick((click)->balAddClick(click, new BigDecimal("-10"))) + .withSlot(29) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("STONE_BUTTON", 1) - .display(Component.text("Remove 1"))) - .withActions(new SwitchPageAction(menuName, menuPage)) - .withClick((click)->balAddClick(click, new BigDecimal("-1"))) - .withSlot(27) - .build()); + .display(Component.text("Remove 1"))) + .withActions(new SwitchPageAction(menuName, menuPage)) + .withClick((click)->balAddClick(click, new BigDecimal("-1"))) + .withSlot(27) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("STONE_BUTTON", 1) - .display(Component.text("Remove .10"))) - .withActions(new SwitchPageAction(menuName, menuPage)) - .withClick((click)->balAddClick(click, new BigDecimal("-.10"))) - .withSlot(47) - .build()); + .display(Component.text("Remove .10"))) + .withActions(new SwitchPageAction(menuName, menuPage)) + .withClick((click)->balAddClick(click, new BigDecimal("-.10"))) + .withSlot(47) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("STONE_BUTTON", 1) - .display(Component.text("Remove .01"))) - .withActions(new SwitchPageAction(menuName, menuPage)) - .withClick((click)->balAddClick(click, new BigDecimal("-.01"))) - .withSlot(45) - .build()); + .display(Component.text("Remove .01"))) + .withActions(new SwitchPageAction(menuName, menuPage)) + .withClick((click)->balAddClick(click, new BigDecimal("-.01"))) + .withSlot(45) + .build()); } } diff --git a/Core/src/net/tnemc/core/menu/page/shared/CurrencySelectionPage.java b/Core/src/net/tnemc/core/menu/page/shared/CurrencySelectionPage.java index 0a2d64a5..d927a28a 100644 --- a/Core/src/net/tnemc/core/menu/page/shared/CurrencySelectionPage.java +++ b/Core/src/net/tnemc/core/menu/page/shared/CurrencySelectionPage.java @@ -52,6 +52,7 @@ public class CurrencySelectionPage { public CurrencySelectionPage(String currencyID, String returnMenu, String menuName, final int menuPage, final int returnPage, String currencyPageID, final int menuRows) { + this.returnMenu = returnMenu; this.menuName = menuName; this.menuPage = menuPage; @@ -82,26 +83,26 @@ public void handle(final PageOpenCallback callback) { if(maxPages > 1) { callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("RED_WOOL", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.PreviousPageDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.PreviousPage"), id)))) - .withActions(new DataAction(currencyPageID, prev), new SwitchPageAction(menuName, menuPage)) - .withSlot(0) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.PreviousPageDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.PreviousPage"), id)))) + .withActions(new DataAction(currencyPageID, prev), new SwitchPageAction(menuName, menuPage)) + .withSlot(0) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("GREEN_WOOL", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.NextPageDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.NextPage"), id)))) - .withActions(new DataAction(currencyPageID, next), new SwitchPageAction(menuName, menuPage)) - .withSlot(8) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.NextPageDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.NextPage"), id)))) + .withActions(new DataAction(currencyPageID, next), new SwitchPageAction(menuName, menuPage)) + .withSlot(8) + .build()); } callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("BARRIER", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.EscapeDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.Escape"), id)))) - .withActions(new SwitchPageAction(returnMenu, returnPage)) - .withSlot(4) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.EscapeDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.Escape"), id)))) + .withActions(new SwitchPageAction(returnMenu, returnPage)) + .withSlot(4) + .build()); for(int i = start; i < start + items; i++) { if(TNECore.eco().currency().currencies().size() <= i) { @@ -111,12 +112,12 @@ public void handle(final PageOpenCallback callback) { final Currency currency = TNECore.eco().currency().currencies().get(i); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of(currency.getIconMaterial(), 1) - .display(Component.text(currency.getIdentifier())) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyBal.Currency.Select"), id)))) - .withActions(new DataAction(currencyID, currency.getUid()), - new SwitchPageAction(returnMenu, returnPage)) - .withSlot(9 + (i - start)) - .build()); + .display(Component.text(currency.getIdentifier())) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyBal.Currency.Select"), id)))) + .withActions(new DataAction(currencyID, currency.getUid()), + new SwitchPageAction(returnMenu, returnPage)) + .withSlot(9 + (i - start)) + .build()); } } } diff --git a/Core/src/net/tnemc/core/menu/page/shared/EnchantmentSelectionPage.java b/Core/src/net/tnemc/core/menu/page/shared/EnchantmentSelectionPage.java index 14401ebd..a45be386 100644 --- a/Core/src/net/tnemc/core/menu/page/shared/EnchantmentSelectionPage.java +++ b/Core/src/net/tnemc/core/menu/page/shared/EnchantmentSelectionPage.java @@ -60,6 +60,7 @@ public class EnchantmentSelectionPage { public EnchantmentSelectionPage(String enchantsID, String returnMenu, String menuName, final int menuPage, final int returnPage, String enchantPageID, final int menuRows, Consumer selectionListener) { + this.enchantsID = enchantsID; this.returnMenu = returnMenu; this.menuName = menuName; @@ -89,52 +90,52 @@ public void handle(final PageOpenCallback callback) { if(maxPages > 1) { callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("RED_WOOL", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.PreviousPageDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.PreviousPage"), id)))) - .withActions(new DataAction(menuName + "_ENCHANTMENT_SELECTION_PAGE", prev), new SwitchPageAction(menuName, menuPage)) - .withSlot(0) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.PreviousPageDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.PreviousPage"), id)))) + .withActions(new DataAction(menuName + "_ENCHANTMENT_SELECTION_PAGE", prev), new SwitchPageAction(menuName, menuPage)) + .withSlot(0) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("GREEN_WOOL", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.NextPageDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.NextPage"), id)))) - .withActions(new DataAction(menuName + "_ENCHANTMENT_SELECTION_PAGE", next), new SwitchPageAction(menuName, menuPage)) - .withSlot(8) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.NextPageDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.NextPage"), id)))) + .withActions(new DataAction(menuName + "_ENCHANTMENT_SELECTION_PAGE", next), new SwitchPageAction(menuName, menuPage)) + .withSlot(8) + .build()); } callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("BARRIER", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.EscapeDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.Escape"), id)))) - .withActions(new SwitchPageAction(returnMenu, returnPage)) - .withSlot(3) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.EscapeDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.Escape"), id)))) + .withActions(new SwitchPageAction(returnMenu, returnPage)) + .withSlot(3) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("ARROW", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.Save"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.Enchants.Save"), id)))) - .withActions(new RunnableAction((click)->{ - - if(selectionListener != null) { - - final StringBuilder builder = new StringBuilder(); - for(final String enchant : MenuManager.instance().getHelper().enchantments()) { - - final String value = (String)viewer.get().dataOrDefault(menuName + "_" + enchant, "Disabled"); - final boolean enabled = value.equalsIgnoreCase("enabled"); - if(enabled) { - - if(!builder.isEmpty()) { - builder.append(","); - } - builder.append(enchant); - } - } - selectionListener.accept(new StringSelectionHandler(click, builder.toString())); - } - }), new SwitchPageAction(returnMenu, returnPage)) - .withSlot(6) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.Save"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.MyEco.Enchants.Save"), id)))) + .withActions(new RunnableAction((click)->{ + + if(selectionListener != null) { + + final StringBuilder builder = new StringBuilder(); + for(final String enchant : MenuManager.instance().getHelper().enchantments()) { + + final String value = (String)viewer.get().dataOrDefault(menuName + "_" + enchant, "Disabled"); + final boolean enabled = value.equalsIgnoreCase("enabled"); + if(enabled) { + + if(!builder.isEmpty()) { + builder.append(","); + } + builder.append(enchant); + } + } + selectionListener.accept(new StringSelectionHandler(click, builder.toString())); + } + }), new SwitchPageAction(returnMenu, returnPage)) + .withSlot(6) + .build()); for(int i = start; i < start + items; i++) { if(MenuManager.instance().getHelper().enchantments().size() <= i) { diff --git a/Core/src/net/tnemc/core/menu/page/shared/FlagSelectionPage.java b/Core/src/net/tnemc/core/menu/page/shared/FlagSelectionPage.java index 1f13f0cc..834f7d07 100644 --- a/Core/src/net/tnemc/core/menu/page/shared/FlagSelectionPage.java +++ b/Core/src/net/tnemc/core/menu/page/shared/FlagSelectionPage.java @@ -57,6 +57,7 @@ public class FlagSelectionPage { public FlagSelectionPage(String flagsID, String returnMenu, String menuName, final int menuPage, final int returnPage, String flagPageID, final int menuRows, Consumer selectionListener) { + this.flagsID = flagsID; this.returnMenu = returnMenu; this.menuName = menuName; @@ -85,52 +86,52 @@ public void handle(final PageOpenCallback callback) { if(maxPages > 1) { callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("RED_WOOL", 1) - .display(Component.text("Previous Page")) - .lore(Collections.singletonList(Component.text("Click to go to previous page.")))) - .withActions(new DataAction(flagPageID, prev), new SwitchPageAction(menuName, menuPage)) - .withSlot(0) - .build()); + .display(Component.text("Previous Page")) + .lore(Collections.singletonList(Component.text("Click to go to previous page.")))) + .withActions(new DataAction(flagPageID, prev), new SwitchPageAction(menuName, menuPage)) + .withSlot(0) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("GREEN_WOOL", 1) - .display(Component.text("Next Page")) - .lore(Collections.singletonList(Component.text("Click to go to next page.")))) - .withActions(new DataAction(flagPageID, next), new SwitchPageAction(menuName, menuPage)) - .withSlot(8) - .build()); + .display(Component.text("Next Page")) + .lore(Collections.singletonList(Component.text("Click to go to next page.")))) + .withActions(new DataAction(flagPageID, next), new SwitchPageAction(menuName, menuPage)) + .withSlot(8) + .build()); } callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("BARRIER", 1) - .display(Component.text("Escape Menu")) - .lore(Collections.singletonList(Component.text("Click to exit this menu.")))) - .withActions(new SwitchPageAction(returnMenu, returnPage)) - .withSlot(4) - .build()); + .display(Component.text("Escape Menu")) + .lore(Collections.singletonList(Component.text("Click to exit this menu.")))) + .withActions(new SwitchPageAction(returnMenu, returnPage)) + .withSlot(4) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("ARROW", 1) - .display(Component.text("Save")) - .lore(Collections.singletonList(Component.text("Click to save the flags.")))) - .withActions(new RunnableAction((click)->{ - - if(selectionListener != null) { - - final StringBuilder builder = new StringBuilder(); - for(final String flag : MenuManager.instance().getHelper().flags()) { - - final String value = (String)viewer.get().dataOrDefault(menuName + "_" + flag, "Disabled"); - final boolean enabled = value.equalsIgnoreCase("enabled"); - if(enabled) { - - if(!builder.isEmpty()) { - builder.append(","); - } - builder.append(flag); - } - } - selectionListener.accept(new StringSelectionHandler(click, builder.toString())); - } - }), new SwitchPageAction(returnMenu, returnPage)) - .withSlot(6) - .build()); + .display(Component.text("Save")) + .lore(Collections.singletonList(Component.text("Click to save the flags.")))) + .withActions(new RunnableAction((click)->{ + + if(selectionListener != null) { + + final StringBuilder builder = new StringBuilder(); + for(final String flag : MenuManager.instance().getHelper().flags()) { + + final String value = (String)viewer.get().dataOrDefault(menuName + "_" + flag, "Disabled"); + final boolean enabled = value.equalsIgnoreCase("enabled"); + if(enabled) { + + if(!builder.isEmpty()) { + builder.append(","); + } + builder.append(flag); + } + } + selectionListener.accept(new StringSelectionHandler(click, builder.toString())); + } + }), new SwitchPageAction(returnMenu, returnPage)) + .withSlot(6) + .build()); for(int i = start; i < start + items; i++) { diff --git a/Core/src/net/tnemc/core/menu/page/shared/MaterialSelectionPageCallback.java b/Core/src/net/tnemc/core/menu/page/shared/MaterialSelectionPageCallback.java index ab4723bf..9420d166 100644 --- a/Core/src/net/tnemc/core/menu/page/shared/MaterialSelectionPageCallback.java +++ b/Core/src/net/tnemc/core/menu/page/shared/MaterialSelectionPageCallback.java @@ -53,6 +53,7 @@ public class MaterialSelectionPageCallback { public MaterialSelectionPageCallback(String materialDataID, String returnMenu, String menuName, final int menuPage, final int returnPage, String materialPageID, final int menuRows, Consumer selectionListener) { + this.returnMenu = returnMenu; this.menuName = menuName; this.menuPage = menuPage; @@ -82,26 +83,26 @@ public void handle(final PageOpenCallback callback) { if(maxPages > 1) { callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("RED_WOOL", 1) - .display(Component.text("Previous Page")) - .lore(Collections.singletonList(Component.text("Click to go to previous page.")))) - .withActions(new DataAction(materialPageID, prev), new SwitchPageAction(menuName, menuPage)) - .withSlot(0) - .build()); + .display(Component.text("Previous Page")) + .lore(Collections.singletonList(Component.text("Click to go to previous page.")))) + .withActions(new DataAction(materialPageID, prev), new SwitchPageAction(menuName, menuPage)) + .withSlot(0) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("GREEN_WOOL", 1) - .display(Component.text("Next Page")) - .lore(Collections.singletonList(Component.text("Click to go to next page.")))) - .withActions(new DataAction(materialPageID, next), new SwitchPageAction(menuName, menuPage)) - .withSlot(8) - .build()); + .display(Component.text("Next Page")) + .lore(Collections.singletonList(Component.text("Click to go to next page.")))) + .withActions(new DataAction(materialPageID, next), new SwitchPageAction(menuName, menuPage)) + .withSlot(8) + .build()); } callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("BARRIER", 1) - .display(Component.text("Escape Menu")) - .lore(Collections.singletonList(Component.text("Click to exit this menu.")))) - .withActions(new SwitchPageAction(returnMenu, returnPage)) - .withSlot(4) - .build()); + .display(Component.text("Escape Menu")) + .lore(Collections.singletonList(Component.text("Click to exit this menu.")))) + .withActions(new SwitchPageAction(returnMenu, returnPage)) + .withSlot(4) + .build()); for(int i = start; i < start + items; i++) { if(MenuManager.instance().getHelper().materials().size() <= i) { @@ -111,17 +112,17 @@ public void handle(final PageOpenCallback callback) { final String material = MenuManager.instance().getHelper().materials().get(i); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of(material, 1) - .lore(Collections.singletonList(Component.text("Click to select material.")))) - .withActions(new DataAction(materialDataID, material), - new RunnableAction((click)->{ + .lore(Collections.singletonList(Component.text("Click to select material.")))) + .withActions(new DataAction(materialDataID, material), + new RunnableAction((click)->{ - if(selectionListener != null) { + if(selectionListener != null) { - selectionListener.accept(new StringSelectionHandler(click, material)); - } - }), new SwitchPageAction(returnMenu, returnPage)) - .withSlot(9 + (i - start)) - .build()); + selectionListener.accept(new StringSelectionHandler(click, material)); + } + }), new SwitchPageAction(returnMenu, returnPage)) + .withSlot(9 + (i - start)) + .build()); } } } diff --git a/Core/src/net/tnemc/core/menu/page/shared/TransactionInfoPage.java b/Core/src/net/tnemc/core/menu/page/shared/TransactionInfoPage.java index 23fe6fe2..9de618e0 100644 --- a/Core/src/net/tnemc/core/menu/page/shared/TransactionInfoPage.java +++ b/Core/src/net/tnemc/core/menu/page/shared/TransactionInfoPage.java @@ -50,6 +50,7 @@ public class TransactionInfoPage { private final String transactionID; public TransactionInfoPage(String returnMenu, int returnPage, String transactionID) { + this.returnMenu = returnMenu; this.returnPage = returnPage; this.transactionID = transactionID; @@ -61,11 +62,11 @@ public void handle(final PageOpenCallback callback) { if(viewer.isPresent()) { callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("BARRIER", 1) - .display(Component.text("Escape Menu")) - .lore(Collections.singletonList(Component.text("Click to exit this menu.")))) - .withActions(new PageSwitchWithClose(returnMenu, returnPage)) - .withSlot(0) - .build()); + .display(Component.text("Escape Menu")) + .lore(Collections.singletonList(Component.text("Click to exit this menu.")))) + .withActions(new PageSwitchWithClose(returnMenu, returnPage)) + .withSlot(0) + .build()); final Optional transactionObj = viewer.get().findData(transactionID); if(transactionObj.isEmpty()) { @@ -79,29 +80,29 @@ public void handle(final PageOpenCallback callback) { if(receipt.isPresent()) { callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("CLOCK", 1) - .display(Component.text(TNECore.eco().transaction().getFormat().format(new Date(receipt.get().getTime())))) - .lore(Collections.singletonList(Component.text("Time of Transaction")))) - .withSlot(2) - .build()); + .display(Component.text(TNECore.eco().transaction().getFormat().format(new Date(receipt.get().getTime())))) + .lore(Collections.singletonList(Component.text("Time of Transaction")))) + .withSlot(2) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("NAME_TAG", 1) - .display(Component.text(id.toString())) - .lore(Collections.singletonList(Component.text("UUID of Transaction")))) - .withSlot(4) - .build()); + .display(Component.text(id.toString())) + .lore(Collections.singletonList(Component.text("UUID of Transaction")))) + .withSlot(4) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1) - .display(Component.text(receipt.get().getType())) - .lore(Collections.singletonList(Component.text("Type of Transaction")))) - .withSlot(6) - .build()); + .display(Component.text(receipt.get().getType())) + .lore(Collections.singletonList(Component.text("Type of Transaction")))) + .withSlot(6) + .build()); final String source = (receipt.get().getSource() != null)? receipt.get().getSource().asString() : "No Source Logged"; callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PAPER", 1) - .display(Component.text(source)) - .lore(Collections.singletonList(Component.text("Source of Transaction")))) - .withSlot(8) - .build()); + .display(Component.text(source)) + .lore(Collections.singletonList(Component.text("Source of Transaction")))) + .withSlot(8) + .build()); if(receipt.get().getModifierTo() != null && receipt.get().getTo() != null) { @@ -120,39 +121,39 @@ public void handle(final PageOpenCallback callback) { } } - } catch(Exception ignore) {} + } catch(Exception ignore) { } callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PLAYER_HEAD", 1) - .profile(profile) - .display(Component.text(name)) - .lore(Collections.singletonList(Component.text("To Account")))) - .withSlot(24) - .build()); + .profile(profile) + .display(Component.text(name)) + .lore(Collections.singletonList(Component.text("To Account")))) + .withSlot(24) + .build()); final Currency cur = TNECore.eco().currency().findOrDefault(modifier.getCurrency()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of(cur.getIconMaterial(), 1) - .display(Component.text(cur.getIdentifier())) - .lore(Collections.singletonList(Component.text("Modifier Currency")))) - .withSlot(27) - .build()); + .display(Component.text(cur.getIdentifier())) + .lore(Collections.singletonList(Component.text("Modifier Currency")))) + .withSlot(27) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("MAP", 1) - .display(Component.text(modifier.getRegion())) - .lore(Collections.singletonList(Component.text("Modifier Region")))) - .withSlot(28) - .build()); + .display(Component.text(modifier.getRegion())) + .lore(Collections.singletonList(Component.text("Modifier Region")))) + .withSlot(28) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("GOLD_INGOT", 1) - .display(Component.text(modifier.getModifier().toPlainString())) - .lore(Collections.singletonList(Component.text("Modifier Amount")))) - .withSlot(29) - .build()); + .display(Component.text(modifier.getModifier().toPlainString())) + .lore(Collections.singletonList(Component.text("Modifier Amount")))) + .withSlot(29) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("REDSTONE_TORCH", 1) - .display(Component.text(modifier.getOperation().name())) - .lore(Collections.singletonList(Component.text("Modifier Operation")))) - .withSlot(30) - .build()); + .display(Component.text(modifier.getOperation().name())) + .lore(Collections.singletonList(Component.text("Modifier Operation")))) + .withSlot(30) + .build()); } if(receipt.get().getModifierFrom() != null && receipt.get().getFrom() != null) { @@ -172,73 +173,73 @@ public void handle(final PageOpenCallback callback) { } } - } catch(Exception ignore) {} + } catch(Exception ignore) { } callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("PLAYER_HEAD", 1) - .profile(profile) - .display(Component.text(name)) - .lore(Collections.singletonList(Component.text("From Account")))) - .withSlot(19) - .build()); + .profile(profile) + .display(Component.text(name)) + .lore(Collections.singletonList(Component.text("From Account")))) + .withSlot(19) + .build()); final Currency cur = TNECore.eco().currency().findOrDefault(modifier.getCurrency()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of(cur.getIconMaterial(), 1) - .display(Component.text(cur.getIdentifier())) - .lore(Collections.singletonList(Component.text("Modifier Currency")))) - .withSlot(32) - .build()); + .display(Component.text(cur.getIdentifier())) + .lore(Collections.singletonList(Component.text("Modifier Currency")))) + .withSlot(32) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("MAP", 1) - .display(Component.text(modifier.getRegion())) - .lore(Collections.singletonList(Component.text("Modifier Region")))) - .withSlot(33) - .build()); + .display(Component.text(modifier.getRegion())) + .lore(Collections.singletonList(Component.text("Modifier Region")))) + .withSlot(33) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("GOLD_INGOT", 1) - .display(Component.text(modifier.getModifier().toPlainString())) - .lore(Collections.singletonList(Component.text("Modifier Amount")))) - .withSlot(34) - .build()); + .display(Component.text(modifier.getModifier().toPlainString())) + .lore(Collections.singletonList(Component.text("Modifier Amount")))) + .withSlot(34) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("REDSTONE_TORCH", 1) - .display(Component.text(modifier.getOperation().name())) - .lore(Collections.singletonList(Component.text("Modifier Operation")))) - .withSlot(35) - .build()); + .display(Component.text(modifier.getOperation().name())) + .lore(Collections.singletonList(Component.text("Modifier Operation")))) + .withSlot(35) + .build()); } //barrier icons callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("WHITE_GLASS_PANE", 1) - .display(Component.text(""))) - .withSlot(18).build()); + .display(Component.text(""))) + .withSlot(18).build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("WHITE_GLASS_PANE", 1) - .display(Component.text(""))) - .withSlot(20).build()); + .display(Component.text(""))) + .withSlot(20).build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("WHITE_GLASS_PANE", 1) - .display(Component.text(""))) - .withSlot(21).build()); + .display(Component.text(""))) + .withSlot(21).build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("WHITE_GLASS_PANE", 1) - .display(Component.text(""))) - .withSlot(22).build()); + .display(Component.text(""))) + .withSlot(22).build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("WHITE_GLASS_PANE", 1) - .display(Component.text(""))) - .withSlot(31).build()); + .display(Component.text(""))) + .withSlot(31).build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("WHITE_GLASS_PANE", 1) - .display(Component.text(""))) - .withSlot(23).build()); + .display(Component.text(""))) + .withSlot(23).build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("WHITE_GLASS_PANE", 1) - .display(Component.text(""))) - .withSlot(25).build()); + .display(Component.text(""))) + .withSlot(25).build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("WHITE_GLASS_PANE", 1) - .display(Component.text(""))) - .withSlot(26).build()); + .display(Component.text(""))) + .withSlot(26).build()); } } catch(Exception ignore) { diff --git a/Core/src/net/tnemc/core/menu/page/top/BalTopPage.java b/Core/src/net/tnemc/core/menu/page/top/BalTopPage.java index 842affdc..605a1541 100644 --- a/Core/src/net/tnemc/core/menu/page/top/BalTopPage.java +++ b/Core/src/net/tnemc/core/menu/page/top/BalTopPage.java @@ -78,31 +78,30 @@ public void handle(final PageOpenCallback callback) { if(maxPages > 1) { callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("RED_WOOL", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.PreviousPageDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.PreviousPage"), id)))) - .withActions(new DataAction(menuName + "_PAGE", prev), new SwitchPageAction(menuName, menuPage)) - .withSlot(0) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.PreviousPageDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.PreviousPage"), id)))) + .withActions(new DataAction(menuName + "_PAGE", prev), new SwitchPageAction(menuName, menuPage)) + .withSlot(0) + .build()); callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("GREEN_WOOL", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.NextPageDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.NextPage"), id)))) - .withActions(new DataAction(menuName + "_PAGE", next), new SwitchPageAction(menuName, menuPage)) - .withSlot(8) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.NextPageDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.NextPage"), id)))) + .withActions(new DataAction(menuName + "_PAGE", next), new SwitchPageAction(menuName, menuPage)) + .withSlot(8) + .build()); } callback.getPage().addIcon(new IconBuilder(PluginCore.server().stackBuilder().of("BARRIER", 1) - .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.EscapeDisplay"), id)) - .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.Escape"), id)))) - .withActions(new SwitchPageAction(returnMenu, returnPage)) - .withSlot(3) - .build()); + .display(MessageHandler.grab(new MessageData("Messages.Menu.Shared.EscapeDisplay"), id)) + .lore(Collections.singletonList(MessageHandler.grab(new MessageData("Messages.Menu.Shared.Escape"), id)))) + .withActions(new SwitchPageAction(returnMenu, returnPage)) + .withSlot(3) + .build()); for(int i = start; i < start + items; i++) { - } } } diff --git a/Core/src/net/tnemc/core/region/RegionGroup.java b/Core/src/net/tnemc/core/region/RegionGroup.java index 082865b1..701e6295 100644 --- a/Core/src/net/tnemc/core/region/RegionGroup.java +++ b/Core/src/net/tnemc/core/region/RegionGroup.java @@ -31,19 +31,23 @@ * @since 0.1.2.0 */ public class RegionGroup { + private final Map currencies = new HashMap<>(); private String name; public RegionGroup(final String name) { + this.name = name; } public Map getCurrencies() { + return currencies; } public void setName(String name) { + this.name = name; } @@ -52,6 +56,7 @@ public void setName(String name) { */ @NotNull public String name() { + return name; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/region/RegionMode.java b/Core/src/net/tnemc/core/region/RegionMode.java index c353b506..c2ee6add 100644 --- a/Core/src/net/tnemc/core/region/RegionMode.java +++ b/Core/src/net/tnemc/core/region/RegionMode.java @@ -40,10 +40,12 @@ public interface RegionMode { List accepted(); default String defaultRegion() { + return TNECore.eco().region().defaultRegion(); } default String region(@NotNull final UUID player) { + final Optional provider = PluginCore.server().findPlayer(player); if(provider.isPresent()) { return region(provider.get()); diff --git a/Core/src/net/tnemc/core/region/RegionProvider.java b/Core/src/net/tnemc/core/region/RegionProvider.java index 74672e12..24916dd0 100644 --- a/Core/src/net/tnemc/core/region/RegionProvider.java +++ b/Core/src/net/tnemc/core/region/RegionProvider.java @@ -49,6 +49,7 @@ public class RegionProvider { private RegionMode mode; public RegionProvider(boolean realmSharing, final String mode) { + this.realmSharing = realmSharing; //add modes @@ -62,6 +63,7 @@ public RegionProvider(boolean realmSharing, final String mode) { } public void initializeRegion(final String name, final RegionType type) { + if(this.mode.accepted().contains(type)) { if(type.equals(RegionType.WORLD) && MainConfig.yaml().getBoolean("Core.Region.GroupRealms", true)) { @@ -86,23 +88,30 @@ public void initializeRegion(final String name, final RegionType type) { /** * Used to add a region group to our existing map of groups. - * @param name The name of the group + * + * @param name The name of the group * @param group The group instance. */ public void addGroup(final String name, final RegionGroup group) { + regions.put(name, group); } /** * Used to find a region group based on its name. + * * @param name The name of the group to find. - * @return An optional containing the {@link RegionGroup} if it exists, otherwise an empty optional. + * + * @return An optional containing the {@link RegionGroup} if it exists, otherwise an empty + * optional. */ public Optional retrieve(final String name) { + return Optional.ofNullable(regions.get(name)); } public boolean multiRegion() { + return MainConfig.yaml().getBoolean("Core.Region.MultiRegion"); } @@ -128,6 +137,7 @@ public String resolve(final String region) { } public String defaultRegion() { + final String configDefault = MainConfig.yaml().getString("Core.Region.DefaultRegion"); if(configDefault.equalsIgnoreCase("TNE_SYSTEM")) { return PluginCore.server().defaultWorld(); @@ -136,26 +146,32 @@ public String defaultRegion() { } public boolean isSharing() { + return realmSharing; } public void setRealmSharing(boolean realmSharing) { + this.realmSharing = realmSharing; } public RegionMode getMode() { + return mode; } public void setMode(final String mode) { + this.mode = modes.getOrDefault(mode, modes.get("world")); } public Map getRegions() { + return regions; } public List getDisabledRegions() { + return disabledRegions; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/region/mode/BiomeMode.java b/Core/src/net/tnemc/core/region/mode/BiomeMode.java index 70717831..a64d815e 100644 --- a/Core/src/net/tnemc/core/region/mode/BiomeMode.java +++ b/Core/src/net/tnemc/core/region/mode/BiomeMode.java @@ -32,18 +32,20 @@ * BiomeMode represents a {@link RegionMode} based on biomes. * * @author creatorfromhell - * @since 0.1.2.0 - * * @see RegionMode + * @since 0.1.2.0 */ public class BiomeMode implements RegionMode { + @Override public String name() { + return "biome"; } @Override public List accepted() { + return Collections.singletonList(RegionType.BIOME); } diff --git a/Core/src/net/tnemc/core/region/mode/WorldMode.java b/Core/src/net/tnemc/core/region/mode/WorldMode.java index 7d2e8de3..3c7d081f 100644 --- a/Core/src/net/tnemc/core/region/mode/WorldMode.java +++ b/Core/src/net/tnemc/core/region/mode/WorldMode.java @@ -32,18 +32,20 @@ * WorldMode represents a {@link RegionMode} based on worlds. * * @author creatorfromhell - * @since 0.1.2.0 - * * @see RegionMode + * @since 0.1.2.0 */ public class WorldMode implements RegionMode { + @Override public String name() { + return "world"; } @Override public List accepted() { + return Collections.singletonList(RegionType.WORLD); } diff --git a/Core/src/net/tnemc/core/transaction/Receipt.java b/Core/src/net/tnemc/core/transaction/Receipt.java index 57e67b76..4fa9227a 100644 --- a/Core/src/net/tnemc/core/transaction/Receipt.java +++ b/Core/src/net/tnemc/core/transaction/Receipt.java @@ -29,8 +29,8 @@ * Represents a record of a successful {@link Transaction transaction}. Similar to how in the real * world we get receipts for completed transactions, these are the same. * - * @see Transaction * @author creatorfromhell + * @see Transaction * @since 0.1.2.0 */ public class Receipt { @@ -51,12 +51,14 @@ public class Receipt { private boolean voided = false; public Receipt(final UUID id, final long time, final String type) { + this.id = id; this.time = time; this.type = type; } public Receipt(final UUID id, final long time, final Transaction transaction) { + this.id = id; this.time = time; this.type = transaction.getType(); @@ -69,6 +71,7 @@ public Receipt(final UUID id, final long time, final Transaction transaction) { } public boolean voidTransaction() { + if(voided) return false; Transaction transaction = new Transaction("void").source(source); @@ -77,7 +80,7 @@ public boolean voidTransaction() { final HoldingsModifier modifier = modifierFrom.counter(); final BigDecimal tax = (modifier.isRemoval())? from.getTax() - : from.getTax().negate(); + : from.getTax().negate(); modifier.modifier(tax); transaction = transaction.from(from.getId(), modifier); @@ -87,16 +90,16 @@ public boolean voidTransaction() { final HoldingsModifier modifier = modifierTo.counter(); final BigDecimal tax = (modifier.isRemoval())? to.getTax() - : to.getTax().negate(); + : to.getTax().negate(); modifier.modifier(tax); transaction = transaction.to(to.getId(), modifier); } try { - transaction.process((transactionResult -> { + transaction.process((transactionResult->{ if(transactionResult.isSuccessful()) { - this.voided = true; + this.voided = true; } })); } catch(InvalidTransactionException e) { @@ -106,70 +109,87 @@ public boolean voidTransaction() { } public UUID getId() { + return id; } public long getTime() { + return time; } public String getType() { + return type; } public ActionSource getSource() { + return source; } public void setSource(final ActionSource source) { + this.source = source; } public TransactionParticipant getFrom() { + return from; } public void setFrom(TransactionParticipant from) { + this.from = from; } public TransactionParticipant getTo() { + return to; } public void setTo(TransactionParticipant to) { + this.to = to; } public HoldingsModifier getModifierTo() { + return modifierTo; } public void setModifierTo(HoldingsModifier modifierTo) { + this.modifierTo = modifierTo; } public HoldingsModifier getModifierFrom() { + return modifierFrom; } public void setModifierFrom(HoldingsModifier modifierFrom) { + this.modifierFrom = modifierFrom; } public boolean isArchive() { + return archive; } public void setArchive(boolean archive) { + this.archive = archive; } public boolean isVoided() { + return voided; } public void setVoided(boolean voided) { + this.voided = voided; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/transaction/Transaction.java b/Core/src/net/tnemc/core/transaction/Transaction.java index 6915a4f5..d5964fcf 100644 --- a/Core/src/net/tnemc/core/transaction/Transaction.java +++ b/Core/src/net/tnemc/core/transaction/Transaction.java @@ -60,6 +60,7 @@ public class Transaction { private Consumer resultConsumer; public Transaction(String type) { + this.type = type; this.processor = EconomyManager.baseProcessor(); @@ -67,17 +68,21 @@ public Transaction(String type) { /** * Used to determine if the "to" participant is losing funds in this transaction. + * * @return True if the "to" participant is losing funds, otherwise false. */ public boolean isToLosing() { + return to != null && modifierTo != null && modifierTo.isRemoval(); } /** * Used to determine if the "from" participant is losing funds in this transaction. + * * @return True if the "from" participant is losing funds, otherwise false. */ public boolean isFromLosing() { + return from != null && modifierFrom.isRemoval(); } @@ -85,19 +90,21 @@ public boolean isFromLosing() { * Used to create a new Transaction object from the specified transaction type. * * @param type The identifier of the transaction type. + * * @return An instance of the Transaction object created with the specified type. */ public static Transaction of(final String type) { + return new Transaction(type); } /** * Used to set the {@link TransactionParticipant from} participant. * - * @param id The identifier of this participant. + * @param id The identifier of this participant. * @param modifier The {@link HoldingsModifier modifier} associated with this participant. - * @return An instance of the Transaction object with the new - * participant. + * + * @return An instance of the Transaction object with the new participant. */ public Transaction from(final UUID id, final HoldingsModifier modifier) { @@ -109,10 +116,10 @@ public Transaction from(final UUID id, final HoldingsModifier modifier) { /** * Used to set the {@link TransactionParticipant from} participant. * - * @param account The account reference of this participant. + * @param account The account reference of this participant. * @param modifier The {@link HoldingsModifier modifier} associated with this participant. - * @return An instance of the Transaction object with the new - * participant. + * + * @return An instance of the Transaction object with the new participant. */ public Transaction from(final Account account, final HoldingsModifier modifier) { @@ -120,7 +127,7 @@ public Transaction from(final Account account, final HoldingsModifier modifier) if(balances.isEmpty()) { balances.add(new HoldingsEntry(modifier.getRegion(), modifier.getCurrency(), - BigDecimal.ZERO, EconomyManager.NORMAL)); + BigDecimal.ZERO, EconomyManager.NORMAL)); } this.from = new TransactionParticipant(account.getIdentifier(), balances); @@ -143,7 +150,7 @@ public Transaction from(final Account account, final HoldingsModifier modifier) working = modifier.modify(total); total = null; } else { - working = modifier.getModifier().multiply(new BigDecimal(- 1)); + working = modifier.getModifier().multiply(new BigDecimal(-1)); } } @@ -203,10 +210,10 @@ public Transaction from(final Account account, final HoldingsModifier modifier) /** * Used to set the {@link TransactionParticipant to} participant. * - * @param id The identifier of this participant. + * @param id The identifier of this participant. * @param modifier The {@link HoldingsModifier modifier} associated with this participant. - * @return An instance of the Transaction object with the new - * participant. + * + * @return An instance of the Transaction object with the new participant. */ public Transaction to(final UUID id, final HoldingsModifier modifier) { @@ -218,11 +225,10 @@ public Transaction to(final UUID id, final HoldingsModifier modifier) { /** * Used to set the {@link TransactionParticipant to} participant. * - * - * @param account The account reference of this participant. + * @param account The account reference of this participant. * @param modifier The {@link HoldingsModifier modifier} associated with this participant. - * @return An instance of the Transaction object with the new - * participant. + * + * @return An instance of the Transaction object with the new participant. */ public Transaction to(final Account account, final HoldingsModifier modifier) { @@ -238,7 +244,7 @@ public Transaction to(final Account account, final HoldingsModifier modifier) { final Optional type = TNECore.eco().transaction().findType(this.type); final BigDecimal tax = (type.isPresent() && type.get().toTax().isPresent())? type.get().toTax().get() - .calculateTax(modifier.getModifier()) : BigDecimal.ZERO; + .calculateTax(modifier.getModifier()) : BigDecimal.ZERO; BigDecimal working = null; final boolean take = (modifier.getModifier().compareTo(BigDecimal.ZERO) < 0); @@ -253,7 +259,7 @@ public Transaction to(final Account account, final HoldingsModifier modifier) { working = modifier.modify(total); total = null; } else { - working = modifier.getModifier().multiply(new BigDecimal(- 1)); + working = modifier.getModifier().multiply(new BigDecimal(-1)); } } @@ -315,10 +321,13 @@ public Transaction to(final Account account, final HoldingsModifier modifier) { /** * Used to set {@link ActionSource source} of this transaction. + * * @param source The {@link ActionSource source} of this transaction. + * * @return An instance of the Transaction object with the new {@link ActionSource source}. */ public Transaction source(final ActionSource source) { + this.source = source; return this; } @@ -328,42 +337,52 @@ public Transaction source(final ActionSource source) { * things such as account statuses. * * @param admin If this transaction is an administrator transaction or not. + * * @return An instance of the Transaction object with the new {@link ActionSource source}. */ public Transaction admin(final boolean admin) { + this.admin = admin; return this; } /** * Used to set {@link TransactionProcessor processor} of this transaction. + * * @param processor The {@link TransactionProcessor processor} of this transaction. - * @return An instance of the Transaction object with the new {@link TransactionProcessor processor}. + * + * @return An instance of the Transaction object with the new + * {@link TransactionProcessor processor}. */ public Transaction processor(final TransactionProcessor processor) { + this.processor = processor; return this; } /** - * Processes the transaction and sends the result to the {@link Transaction#resultConsumer Result - * Handler}. + * Processes the transaction and sends the result to the + * {@link Transaction#resultConsumer Result Handler}. * - * @throws InvalidTransactionException If all required aspects of the transaction are not present. + * @throws InvalidTransactionException If all required aspects of the transaction are not + * present. */ public void process(Consumer resultConsumer) throws InvalidTransactionException { + this.resultConsumer = resultConsumer; process(); } /** - * Processes the transaction and sends the result to the {@link Transaction#resultConsumer Result - * Handler}. + * Processes the transaction and sends the result to the + * {@link Transaction#resultConsumer Result Handler}. * - * @throws InvalidTransactionException If all required aspects of the transaction are not present. + * @throws InvalidTransactionException If all required aspects of the transaction are not + * present. */ public TransactionResult process() throws InvalidTransactionException { + String missing = null; if(this.type == null) { @@ -409,6 +428,7 @@ public TransactionResult process() throws InvalidTransactionException { } public Optional getFromAccount() { + if(from != null) { return TNECore.eco().account().findAccount(from.getId()); } @@ -417,6 +437,7 @@ public Optional getFromAccount() { } public Optional getToAccount() { + if(to != null) { return TNECore.eco().account().findAccount(to.getId()); } @@ -425,46 +446,57 @@ public Optional getToAccount() { } public TransactionProcessor getProcessor() { + return processor; } public String getType() { + return type; } public ActionSource getSource() { + return source; } public TransactionParticipant getFrom() { + return from; } public TransactionParticipant getTo() { + return to; } public HoldingsModifier getModifierTo() { + return modifierTo; } public HoldingsModifier getModifierFrom() { + return modifierFrom; } public boolean isAdmin() { + return admin; } public boolean isTrack() { + return track; } public void setTrack(boolean track) { + this.track = track; } public Consumer getResultConsumer() { + return resultConsumer; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/transaction/TransactionCheck.java b/Core/src/net/tnemc/core/transaction/TransactionCheck.java index 028d0587..cc45a8a1 100644 --- a/Core/src/net/tnemc/core/transaction/TransactionCheck.java +++ b/Core/src/net/tnemc/core/transaction/TransactionCheck.java @@ -25,11 +25,11 @@ import org.jetbrains.annotations.NotNull; /** - * Represents a check that happens during the processing of a {@link Transaction transaction}. - * These could be anything from validating balances, to validating inventory space if required. + * Represents a check that happens during the processing of a {@link Transaction transaction}. These + * could be anything from validating balances, to validating inventory space if required. * - * @see Transaction * @author creatorfromhell + * @see Transaction * @since 0.1.2.0 */ public interface TransactionCheck { @@ -50,9 +50,10 @@ public interface TransactionCheck { * {@link EconomyResponse response}. * * @param transaction The {@link Transaction transaction} to perform the check on. + * * @return The {@link EconomyResponse response} for this check. This should include a success or - * failure boolean along with a message for why it failed if it did. The messages for this response - * are ignored if the check was successful. + * failure boolean along with a message for why it failed if it did. The messages for this + * response are ignored if the check was successful. */ default EconomyResponse process(final Transaction transaction) { @@ -80,15 +81,17 @@ default EconomyResponse process(final Transaction transaction) { } /** - * This method is utilized to run the check on specific {@link TransactionParticipant participants}. - * This should return an {@link EconomyResponse response}. + * This method is utilized to run the check on specific + * {@link TransactionParticipant participants}. This should return an + * {@link EconomyResponse response}. * * @param transaction The {@link Transaction transaction} to perform the check on. * @param participant The {@link TransactionParticipant participant} to perform the check on. - * @param modifier The {@link HoldingsModifier modifier} related to the specific participant. + * @param modifier The {@link HoldingsModifier modifier} related to the specific participant. + * * @return The {@link EconomyResponse response} for this check. This should include a success or - * failure boolean along with a message for why it failed if it did. The messages for this response - * are ignored if the check was successful. + * failure boolean along with a message for why it failed if it did. The messages for this + * response are ignored if the check was successful. */ EconomyResponse checkParticipant(Transaction transaction, @NotNull TransactionParticipant participant, diff --git a/Core/src/net/tnemc/core/transaction/TransactionCheckGroup.java b/Core/src/net/tnemc/core/transaction/TransactionCheckGroup.java index c9bb7317..3e0ef6c1 100644 --- a/Core/src/net/tnemc/core/transaction/TransactionCheckGroup.java +++ b/Core/src/net/tnemc/core/transaction/TransactionCheckGroup.java @@ -26,8 +26,8 @@ * Represents a group of transaction checks. This is used for easily adding multiple checks to a * transaction without needing to list them all individually. * - * @see TransactionCheck * @author creatorfromhell + * @see TransactionCheck * @since 0.1.2.0 */ public class TransactionCheckGroup { @@ -37,27 +37,33 @@ public class TransactionCheckGroup { private final String identifier; public TransactionCheckGroup(String identifier) { + this.identifier = identifier; } public void addCheck(final String identifier) { + checks.add(identifier); } public void removeCheck(final String identifier) { + checks.remove(identifier); } @MapKey public String getIdentifier() { + return identifier; } public LinkedList getChecks() { + return checks; } public void setChecks(final LinkedList replacements) { + checks.clear(); checks.addAll(replacements); } diff --git a/Core/src/net/tnemc/core/transaction/TransactionParticipant.java b/Core/src/net/tnemc/core/transaction/TransactionParticipant.java index 1c97e991..163c9232 100644 --- a/Core/src/net/tnemc/core/transaction/TransactionParticipant.java +++ b/Core/src/net/tnemc/core/transaction/TransactionParticipant.java @@ -31,8 +31,8 @@ /** * Represents a participant in a {@link Transaction transaction}. * - * @see Transaction * @author creatorfromhell + * @see Transaction * @since 0.1.2.0 */ public class TransactionParticipant { @@ -44,36 +44,44 @@ public class TransactionParticipant { private BigDecimal tax; public TransactionParticipant(final UUID id, List startBalances) { + this.id = id; this.startingBalances.addAll(startBalances); this.tax = BigDecimal.ZERO; } public Optional asAccount() { + return TNECore.eco().account().findAccount(id); } public UUID getId() { + return id; } public BigDecimal getTax() { + return tax; } public void setTax(BigDecimal tax) { + this.tax = tax; } public List getStartingBalances() { + return startingBalances; } public List getEndingBalances() { + return endingBalances; } public BigDecimal getCombinedEnding() { + BigDecimal combined = BigDecimal.ZERO; for(HoldingsEntry entry : getEndingBalances()) { diff --git a/Core/src/net/tnemc/core/transaction/TransactionProcessor.java b/Core/src/net/tnemc/core/transaction/TransactionProcessor.java index 9488d6aa..bf50984d 100644 --- a/Core/src/net/tnemc/core/transaction/TransactionProcessor.java +++ b/Core/src/net/tnemc/core/transaction/TransactionProcessor.java @@ -33,18 +33,21 @@ /** * This is a class that handles the actual processing of a transaction. * - * @see Transaction * @author creatorfromhell + * @see Transaction * @since 0.1.2.0 */ public interface TransactionProcessor { /** * Processes a transaction. + * * @param transaction The {@link Transaction transaction} to handle. + * * @return The {@link TransactionResult result} from performing the transaction. */ default TransactionResult process(Transaction transaction) { + final Optional response = processChecks(transaction); if(response.isPresent() && !response.get().success()) { @@ -81,6 +84,7 @@ default TransactionResult process(Transaction transaction) { } default Optional processChecks(Transaction transaction) { + EconomyResponse response = null; for(final String str : getChecks()) { @@ -90,8 +94,7 @@ default Optional processChecks(Transaction transaction) { PluginCore.log().debug("Check: " + check.get().identifier() + " Result: " + response.success(), DebugLevel.DEVELOPER); - if(!response.success()) - break; + if(!response.success()) { break; } } } @@ -100,18 +103,21 @@ default Optional processChecks(Transaction transaction) { /** * Used to get the checks for this processor. + * * @return The checks for this processor. */ LinkedList getChecks(); /** * Used to add {@link TransactionCheck check} to this processor. + * * @param check The check to add. */ void addCheck(final TransactionCheck check); /** * Used to add {@link TransactionCheck checks} from a group to this processor. + * * @param group The group to add. */ void addGroup(final TransactionCheckGroup group); diff --git a/Core/src/net/tnemc/core/transaction/TransactionResult.java b/Core/src/net/tnemc/core/transaction/TransactionResult.java index 3c8029b8..b5790c9f 100644 --- a/Core/src/net/tnemc/core/transaction/TransactionResult.java +++ b/Core/src/net/tnemc/core/transaction/TransactionResult.java @@ -25,8 +25,8 @@ /** * Represents the result of a {@link Transaction}. * - * @see Transaction * @author creatorfromhell + * @see Transaction * @since 0.1.2.0 */ public class TransactionResult { @@ -36,6 +36,7 @@ public class TransactionResult { private String message; public TransactionResult(boolean successful, String message) { + this.successful = successful; this.message = message; } @@ -44,30 +45,36 @@ public TransactionResult(boolean successful, String message) { * The receipt for the {@link Transaction transaction} if it was successful, otherwise an empty * Optional. * - * @return The receipt for the {@link Transaction transaction} if it was successful, otherwise an empty - * Optional. + * @return The receipt for the {@link Transaction transaction} if it was successful, otherwise an + * empty Optional. */ public Optional getReceipt() { + return Optional.ofNullable(receipt); } public void setReceipt(@Nullable Receipt receipt) { + this.receipt = receipt; } public boolean isSuccessful() { + return successful; } public void setSuccessful(boolean successful) { + this.successful = successful; } public String getMessage() { + return message; } public void setMessage(String message) { + this.message = message; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/transaction/TransactionType.java b/Core/src/net/tnemc/core/transaction/TransactionType.java index 413872ab..1b3710c7 100644 --- a/Core/src/net/tnemc/core/transaction/TransactionType.java +++ b/Core/src/net/tnemc/core/transaction/TransactionType.java @@ -27,22 +27,24 @@ * Represents a type of {@link Transaction}. This is used to hold basic options surrounding * transaction types. * - * @see Transaction * @author creatorfromhell + * @see Transaction * @since 0.1.2.0 */ public interface TransactionType { /** * The identifier of this transaction type. + * * @return The unique identifier for this transaction type. Should be human-friendly. */ @MapKey String identifier(); /** - * The taxation amount to be assessed on the recipient of the transaction. This will take the amount - * from the amount being sent to the account, and send it to the server account. + * The taxation amount to be assessed on the recipient of the transaction. This will take the + * amount from the amount being sent to the account, and send it to the server account. + * * @return The {@link TaxEntry} related to the taxation amount for the recipient, if applicable, * otherwise an empty optional. */ @@ -51,6 +53,7 @@ public interface TransactionType { /** * The taxation amount to be assessed on the sender of the transaction. This will add the amount * to the amount being sent to the account, and send it to the server account. + * * @return The {@link TaxEntry} related to the taxation amount for the sender, if applicable, * otherwise an empty optional. */ diff --git a/Core/src/net/tnemc/core/transaction/check/MaximumBalanceCheck.java b/Core/src/net/tnemc/core/transaction/check/MaximumBalanceCheck.java index 832e1c30..abfad34c 100644 --- a/Core/src/net/tnemc/core/transaction/check/MaximumBalanceCheck.java +++ b/Core/src/net/tnemc/core/transaction/check/MaximumBalanceCheck.java @@ -40,6 +40,7 @@ * @since 0.1.2.0 */ public class MaximumBalanceCheck implements TransactionCheck { + /** * The unique string-based identifier for this check in order to be able to allow control over * what checks are running, and which ones may not have to be utilized. For instance, we don't @@ -51,20 +52,22 @@ public class MaximumBalanceCheck implements TransactionCheck { @Override @MapKey public String identifier() { + return "maxbal"; } /** - * This method is utilized to run the check on specific {@link TransactionParticipant participants}. - * This should return an {@link EconomyResponse response}. + * This method is utilized to run the check on specific + * {@link TransactionParticipant participants}. This should return an + * {@link EconomyResponse response}. * * @param transaction The {@link Transaction transaction} to perform the check on. * @param participant The {@link TransactionParticipant participant} to perform the check on. * @param modifier The {@link HoldingsModifier modifier} related to the specific participant. * * @return The {@link EconomyResponse response} for this check. This should include a success or - * failure boolean along with a message for why it failed if it did. The messages for this response - * are ignored if the check was successful. + * failure boolean along with a message for why it failed if it did. The messages for this + * response are ignored if the check was successful. */ @Override public EconomyResponse checkParticipant(Transaction transaction, @NotNull TransactionParticipant participant, HoldingsModifier modifier) { @@ -75,7 +78,7 @@ public EconomyResponse checkParticipant(Transaction transaction, @NotNull Transa final Optional currency = TNECore.eco().currency().findCurrency(modifier.getCurrency()); if(currency.isPresent() && - participant.getCombinedEnding().compareTo(currency.get().getMaxBalance()) > 0) { + participant.getCombinedEnding().compareTo(currency.get().getMaxBalance()) > 0) { return HoldingsResponse.MAX_HOLDINGS; } } diff --git a/Core/src/net/tnemc/core/transaction/check/MinimumBalanceCheck.java b/Core/src/net/tnemc/core/transaction/check/MinimumBalanceCheck.java index 3392362b..aa5582de 100644 --- a/Core/src/net/tnemc/core/transaction/check/MinimumBalanceCheck.java +++ b/Core/src/net/tnemc/core/transaction/check/MinimumBalanceCheck.java @@ -40,6 +40,7 @@ * @since 0.1.2.0 */ public class MinimumBalanceCheck implements TransactionCheck { + /** * The unique string-based identifier for this check in order to be able to allow control over * what checks are running, and which ones may not have to be utilized. For instance, we don't @@ -51,20 +52,22 @@ public class MinimumBalanceCheck implements TransactionCheck { @Override @MapKey public String identifier() { + return "minbal"; } /** - * This method is utilized to run the check on specific {@link TransactionParticipant participants}. - * This should return an {@link EconomyResponse response}. + * This method is utilized to run the check on specific + * {@link TransactionParticipant participants}. This should return an + * {@link EconomyResponse response}. * * @param transaction The {@link Transaction transaction} to perform the check on. * @param participant The {@link TransactionParticipant participant} to perform the check on. * @param modifier The {@link HoldingsModifier modifier} related to the specific participant. * * @return The {@link EconomyResponse response} for this check. This should include a success or - * failure boolean along with a message for why it failed if it did. The messages for this response - * are ignored if the check was successful. + * failure boolean along with a message for why it failed if it did. The messages for this + * response are ignored if the check was successful. */ @Override public EconomyResponse checkParticipant(Transaction transaction, @NotNull TransactionParticipant participant, HoldingsModifier modifier) { @@ -75,7 +78,7 @@ public EconomyResponse checkParticipant(Transaction transaction, @NotNull Transa final Optional currency = TNECore.eco().currency().findCurrency(modifier.getCurrency()); if(currency.isPresent() && - participant.getCombinedEnding().compareTo(currency.get().getMinBalance()) < 0) { + participant.getCombinedEnding().compareTo(currency.get().getMinBalance()) < 0) { return HoldingsResponse.MIN_HOLDINGS; } diff --git a/Core/src/net/tnemc/core/transaction/check/MinimumDenomCheck.java b/Core/src/net/tnemc/core/transaction/check/MinimumDenomCheck.java index 04d1e1bf..474eacb9 100644 --- a/Core/src/net/tnemc/core/transaction/check/MinimumDenomCheck.java +++ b/Core/src/net/tnemc/core/transaction/check/MinimumDenomCheck.java @@ -24,7 +24,6 @@ import net.tnemc.core.actions.EconomyResponse; import net.tnemc.core.actions.response.GeneralResponse; import net.tnemc.core.actions.response.HoldingsResponse; -import net.tnemc.core.actions.source.PlayerSource; import net.tnemc.core.currency.Currency; import net.tnemc.core.transaction.Transaction; import net.tnemc.core.transaction.TransactionCheck; @@ -42,6 +41,7 @@ * @since 0.1.2.9 */ public class MinimumDenomCheck implements TransactionCheck { + /** * The unique string-based identifier for this check in order to be able to allow control over * what checks are running, and which ones may not have to be utilized. For instance, we don't @@ -53,20 +53,22 @@ public class MinimumDenomCheck implements TransactionCheck { @Override @MapKey public String identifier() { + return "mindenom"; } /** - * This method is utilized to run the check on specific {@link TransactionParticipant participants}. - * This should return an {@link EconomyResponse response}. + * This method is utilized to run the check on specific + * {@link TransactionParticipant participants}. This should return an + * {@link EconomyResponse response}. * * @param transaction The {@link Transaction transaction} to perform the check on. * @param participant The {@link TransactionParticipant participant} to perform the check on. * @param modifier The {@link HoldingsModifier modifier} related to the specific participant. * * @return The {@link EconomyResponse response} for this check. This should include a success or - * failure boolean along with a message for why it failed if it did. The messages for this response - * are ignored if the check was successful. + * failure boolean along with a message for why it failed if it did. The messages for this + * response are ignored if the check was successful. */ @Override public EconomyResponse checkParticipant(Transaction transaction, @NotNull TransactionParticipant participant, HoldingsModifier modifier) { diff --git a/Core/src/net/tnemc/core/transaction/check/NegativeBalanceCheck.java b/Core/src/net/tnemc/core/transaction/check/NegativeBalanceCheck.java index 2ce1d7f0..836e47ca 100644 --- a/Core/src/net/tnemc/core/transaction/check/NegativeBalanceCheck.java +++ b/Core/src/net/tnemc/core/transaction/check/NegativeBalanceCheck.java @@ -42,6 +42,7 @@ * @since 0.1.2.9 */ public class NegativeBalanceCheck implements TransactionCheck { + /** * The unique string-based identifier for this check in order to be able to allow control over * what checks are running, and which ones may not have to be utilized. For instance, we don't @@ -53,20 +54,22 @@ public class NegativeBalanceCheck implements TransactionCheck { @Override @MapKey public String identifier() { + return "negbal"; } /** - * This method is utilized to run the check on specific {@link TransactionParticipant participants}. - * This should return an {@link EconomyResponse response}. + * This method is utilized to run the check on specific + * {@link TransactionParticipant participants}. This should return an + * {@link EconomyResponse response}. * * @param transaction The {@link Transaction transaction} to perform the check on. * @param participant The {@link TransactionParticipant participant} to perform the check on. * @param modifier The {@link HoldingsModifier modifier} related to the specific participant. * * @return The {@link EconomyResponse response} for this check. This should include a success or - * failure boolean along with a message for why it failed if it did. The messages for this response - * are ignored if the check was successful. + * failure boolean along with a message for why it failed if it did. The messages for this + * response are ignored if the check was successful. */ @Override public EconomyResponse checkParticipant(Transaction transaction, @NotNull TransactionParticipant participant, HoldingsModifier modifier) { @@ -77,7 +80,7 @@ public EconomyResponse checkParticipant(Transaction transaction, @NotNull Transa final Optional currency = TNECore.eco().currency().findCurrency(modifier.getCurrency()); if(currency.isPresent() && !currency.get().negativeSupport() && - participant.getCombinedEnding().compareTo(BigDecimal.ZERO) < 0) { + participant.getCombinedEnding().compareTo(BigDecimal.ZERO) < 0) { if(transaction.getSource() instanceof PlayerSource source) { if(!source.id().equals(participant.getId())) { diff --git a/Core/src/net/tnemc/core/transaction/check/PreCallbackCheck.java b/Core/src/net/tnemc/core/transaction/check/PreCallbackCheck.java index 1d0a825e..9bb5122c 100644 --- a/Core/src/net/tnemc/core/transaction/check/PreCallbackCheck.java +++ b/Core/src/net/tnemc/core/transaction/check/PreCallbackCheck.java @@ -36,6 +36,7 @@ * @since 0.1.2.0 */ public class PreCallbackCheck implements TransactionCheck { + /** * The unique string-based identifier for this check in order to be able to allow control over * what checks are running, and which ones may not have to be utilized. For instance, we don't @@ -47,20 +48,22 @@ public class PreCallbackCheck implements TransactionCheck { @Override @MapKey public String identifier() { + return "pre-check"; } /** - * This method is utilized to run the check on specific {@link TransactionParticipant participants}. - * This should return an {@link EconomyResponse response}. + * This method is utilized to run the check on specific + * {@link TransactionParticipant participants}. This should return an + * {@link EconomyResponse response}. * * @param transaction The {@link Transaction transaction} to perform the check on. * @param participant The {@link TransactionParticipant participant} to perform the check on. * @param modifier The {@link HoldingsModifier modifier} related to the specific participant. * * @return The {@link EconomyResponse response} for this check. This should include a success or - * failure boolean along with a message for why it failed if it did. The messages for this response - * are ignored if the check was successful. + * failure boolean along with a message for why it failed if it did. The messages for this + * response are ignored if the check was successful. */ @Override public EconomyResponse checkParticipant(Transaction transaction, @NotNull TransactionParticipant participant, HoldingsModifier modifier) { diff --git a/Core/src/net/tnemc/core/transaction/check/RegionCheck.java b/Core/src/net/tnemc/core/transaction/check/RegionCheck.java index a5928144..32c4464c 100644 --- a/Core/src/net/tnemc/core/transaction/check/RegionCheck.java +++ b/Core/src/net/tnemc/core/transaction/check/RegionCheck.java @@ -39,6 +39,7 @@ * @since 0.1.2.0 */ public class RegionCheck implements TransactionCheck { + /** * The unique string-based identifier for this check in order to be able to allow control over * what checks are running, and which ones may not have to be utilized. For instance, we don't @@ -50,20 +51,22 @@ public class RegionCheck implements TransactionCheck { @Override @MapKey public String identifier() { + return "region"; } /** - * This method is utilized to run the check on specific {@link TransactionParticipant participants}. - * This should return an {@link EconomyResponse response}. + * This method is utilized to run the check on specific + * {@link TransactionParticipant participants}. This should return an + * {@link EconomyResponse response}. * * @param transaction The {@link Transaction transaction} to perform the check on. * @param participant The {@link TransactionParticipant participant} to perform the check on. * @param modifier The {@link HoldingsModifier modifier} related to the specific participant. * * @return The {@link EconomyResponse response} for this check. This should include a success or - * failure boolean along with a message for why it failed if it did. The messages for this response - * are ignored if the check was successful. + * failure boolean along with a message for why it failed if it did. The messages for this + * response are ignored if the check was successful. */ @Override public EconomyResponse checkParticipant(Transaction transaction, @NotNull TransactionParticipant participant, HoldingsModifier modifier) { diff --git a/Core/src/net/tnemc/core/transaction/check/RestrictedCurrencyCheck.java b/Core/src/net/tnemc/core/transaction/check/RestrictedCurrencyCheck.java index 7a2e3e1b..ee673446 100644 --- a/Core/src/net/tnemc/core/transaction/check/RestrictedCurrencyCheck.java +++ b/Core/src/net/tnemc/core/transaction/check/RestrictedCurrencyCheck.java @@ -42,6 +42,7 @@ * @since 0.1.2.9 */ public class RestrictedCurrencyCheck implements TransactionCheck { + /** * The unique string-based identifier for this check in order to be able to allow control over * what checks are running, and which ones may not have to be utilized. For instance, we don't @@ -53,20 +54,22 @@ public class RestrictedCurrencyCheck implements TransactionCheck { @Override @MapKey public String identifier() { + return "restrictbal"; } /** - * This method is utilized to run the check on specific {@link TransactionParticipant participants}. - * This should return an {@link EconomyResponse response}. + * This method is utilized to run the check on specific + * {@link TransactionParticipant participants}. This should return an + * {@link EconomyResponse response}. * * @param transaction The {@link Transaction transaction} to perform the check on. * @param participant The {@link TransactionParticipant participant} to perform the check on. * @param modifier The {@link HoldingsModifier modifier} related to the specific participant. * * @return The {@link EconomyResponse response} for this check. This should include a success or - * failure boolean along with a message for why it failed if it did. The messages for this response - * are ignored if the check was successful. + * failure boolean along with a message for why it failed if it did. The messages for this + * response are ignored if the check was successful. */ @Override public EconomyResponse checkParticipant(Transaction transaction, @NotNull TransactionParticipant participant, HoldingsModifier modifier) { @@ -78,8 +81,8 @@ public EconomyResponse checkParticipant(Transaction transaction, @NotNull Transa final Optional provider = player.getPlayer(); if(currency.isPresent() && provider.isPresent() && provider.get().hasPermission("tne.money.restricted") - && !provider.get().hasPermission("tne.money.restricted.override") - && provider.get().hasPermission("tne.money.restricted." + currency.get().getIdentifier())) { + && !provider.get().hasPermission("tne.money.restricted.override") + && provider.get().hasPermission("tne.money.restricted." + currency.get().getIdentifier())) { return HoldingsResponse.RESTRICTED; } } diff --git a/Core/src/net/tnemc/core/transaction/check/StatusCheck.java b/Core/src/net/tnemc/core/transaction/check/StatusCheck.java index 843ec662..486bad69 100644 --- a/Core/src/net/tnemc/core/transaction/check/StatusCheck.java +++ b/Core/src/net/tnemc/core/transaction/check/StatusCheck.java @@ -38,6 +38,7 @@ * @since 0.1.2.0 */ public class StatusCheck implements TransactionCheck { + /** * The unique string-based identifier for this check in order to be able to allow control over * what checks are running, and which ones may not have to be utilized. For instance, we don't @@ -49,20 +50,22 @@ public class StatusCheck implements TransactionCheck { @Override @MapKey public String identifier() { + return "status"; } /** - * This method is utilized to run the check on specific {@link TransactionParticipant participants}. - * This should return an {@link EconomyResponse response}. + * This method is utilized to run the check on specific + * {@link TransactionParticipant participants}. This should return an + * {@link EconomyResponse response}. * * @param transaction The {@link Transaction transaction} to perform the check on. * @param participant The {@link TransactionParticipant participant} to perform the check on. * @param modifier The {@link HoldingsModifier modifier} related to the specific participant. * * @return The {@link EconomyResponse response} for this check. This should include a success or - * failure boolean along with a message for why it failed if it did. The messages for this response - * are ignored if the check was successful. + * failure boolean along with a message for why it failed if it did. The messages for this + * response are ignored if the check was successful. */ @Override public EconomyResponse checkParticipant(Transaction transaction, @NotNull TransactionParticipant participant, HoldingsModifier modifier) { diff --git a/Core/src/net/tnemc/core/transaction/check/TrackingCheck.java b/Core/src/net/tnemc/core/transaction/check/TrackingCheck.java index d99bcc49..962e6717 100644 --- a/Core/src/net/tnemc/core/transaction/check/TrackingCheck.java +++ b/Core/src/net/tnemc/core/transaction/check/TrackingCheck.java @@ -35,6 +35,7 @@ * @since 0.1.2.0 */ public class TrackingCheck implements TransactionCheck { + /** * The unique string-based identifier for this check in order to be able to allow control over * what checks are running, and which ones may not have to be utilized. For instance, we don't @@ -46,26 +47,28 @@ public class TrackingCheck implements TransactionCheck { @Override @MapKey public String identifier() { + return "track"; } /** - * This method is utilized to run the check on specific {@link TransactionParticipant participants}. - * This should return an {@link EconomyResponse response}. + * This method is utilized to run the check on specific + * {@link TransactionParticipant participants}. This should return an + * {@link EconomyResponse response}. * * @param transaction The {@link Transaction transaction} to perform the check on. * @param participant The {@link TransactionParticipant participant} to perform the check on. * @param modifier The {@link HoldingsModifier modifier} related to the specific participant. * * @return The {@link EconomyResponse response} for this check. This should include a success or - * failure boolean along with a message for why it failed if it did. The messages for this response - * are ignored if the check was successful. + * failure boolean along with a message for why it failed if it did. The messages for this + * response are ignored if the check was successful. */ @Override public EconomyResponse checkParticipant(Transaction transaction, @NotNull TransactionParticipant participant, HoldingsModifier modifier) { if(TNECore.eco().transaction().isTrack() && - modifier.getModifier().compareTo(TNECore.eco().transaction().getAmount()) >= 0) { + modifier.getModifier().compareTo(TNECore.eco().transaction().getAmount()) >= 0) { transaction.setTrack(true); } diff --git a/Core/src/net/tnemc/core/transaction/history/AwayHistory.java b/Core/src/net/tnemc/core/transaction/history/AwayHistory.java index 3f2f3668..fba88cf7 100644 --- a/Core/src/net/tnemc/core/transaction/history/AwayHistory.java +++ b/Core/src/net/tnemc/core/transaction/history/AwayHistory.java @@ -36,23 +36,27 @@ public class AwayHistory { private final UUID account; public AwayHistory(UUID account) { + this.account = account; } public NavigableMap getReceipts() { + return receipts; } public UUID getAccount() { + return account; } public NavigableMap getPage(int page) { + if(page > maxPages()) page = 1; final NavigableMap values = new TreeMap<>(); final int start = ((page * 5) - 5) + 1; - final int end = start + 5; + final int end = start + 5; int i = 1; for(Map.Entry entry : receipts.entrySet()) { @@ -66,6 +70,7 @@ public NavigableMap getPage(int page) { } public int maxPages() { + int max = receipts.size() / 5; if((receipts.size() % 5) > 0) { diff --git a/Core/src/net/tnemc/core/transaction/history/SortedHistory.java b/Core/src/net/tnemc/core/transaction/history/SortedHistory.java index 1309e228..eeabddee 100644 --- a/Core/src/net/tnemc/core/transaction/history/SortedHistory.java +++ b/Core/src/net/tnemc/core/transaction/history/SortedHistory.java @@ -45,6 +45,7 @@ public class SortedHistory { private long lastSort; public SortedHistory(UUID account) { + this.account = account; this.lastSort = -1; @@ -77,13 +78,14 @@ public void sort() { } public NavigableMap getPage(int page) { + sort(); if(page > maxPages()) page = 1; final NavigableMap values = new TreeMap<>(); final int start = ((page * 5) - 5) + 1; - final int end = start + 5; + final int end = start + 5; int i = 1; for(Map.Entry entry : receipts.entrySet()) { @@ -97,6 +99,7 @@ public NavigableMap getPage(int page) { } public int maxPages() { + int max = receipts.size() / 5; if((receipts.size() % 5) > 0) { @@ -106,6 +109,7 @@ public int maxPages() { } public NavigableMap getReceipts() { + return receipts; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/transaction/processor/BaseTransactionProcessor.java b/Core/src/net/tnemc/core/transaction/processor/BaseTransactionProcessor.java index fbc9a747..04ea35b4 100644 --- a/Core/src/net/tnemc/core/transaction/processor/BaseTransactionProcessor.java +++ b/Core/src/net/tnemc/core/transaction/processor/BaseTransactionProcessor.java @@ -35,6 +35,7 @@ public class BaseTransactionProcessor implements TransactionProcessor { private final LinkedList checks = new LinkedList<>(); public BaseTransactionProcessor(LinkedList checks) { + this.checks.addAll(checks); } @@ -45,6 +46,7 @@ public BaseTransactionProcessor(LinkedList checks) { */ @Override public LinkedList getChecks() { + return checks; } @@ -55,6 +57,7 @@ public LinkedList getChecks() { */ @Override public void addCheck(TransactionCheck check) { + checks.add(check.identifier()); } @@ -65,6 +68,7 @@ public void addCheck(TransactionCheck check) { */ @Override public void addGroup(TransactionCheckGroup group) { + checks.addAll(group.getChecks()); } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/transaction/receipt/ReceiptBox.java b/Core/src/net/tnemc/core/transaction/receipt/ReceiptBox.java index c12f82f6..573ddc85 100644 --- a/Core/src/net/tnemc/core/transaction/receipt/ReceiptBox.java +++ b/Core/src/net/tnemc/core/transaction/receipt/ReceiptBox.java @@ -39,8 +39,8 @@ * ReceiptBox represents an object that can hold receipts. * * @author creatorfromhell - * @since 0.1.2.0 * @see Receipt + * @since 0.1.2.0 */ public class ReceiptBox { @@ -53,12 +53,15 @@ public class ReceiptBox { private final UUID owner; public ReceiptBox(UUID owner) { + this.owner = owner; } /** * Used to calculate transactions that happened while an account owner was away. + * * @param account The identifier of the account. + * * @return An Optional containing the account history if applicable, otherwise an empty Optional. */ public Optional away(final UUID account) { @@ -87,7 +90,7 @@ public Optional away(final UUID account) { final Receipt receipt = entry.getValue(); if(receipt.getFrom() != null && receipt.getFrom().getId().equals(account) - || receipt.getTo() != null && receipt.getTo().getId().equals(account)) { + || receipt.getTo() != null && receipt.getTo().getId().equals(account)) { history.getReceipts().put(receipt.getTime(), receipt.getId()); i++; } @@ -102,6 +105,7 @@ public Optional away(final UUID account) { } public SortedHistory getSorted(final UUID identifier) { + if(sorted == null) { sorted = new SortedHistory(identifier); } @@ -112,37 +116,46 @@ public SortedHistory getSorted(final UUID identifier) { * Used to clear the AwayHistory instance. */ public void clearAwayReceipts() { + away = null; checked = false; } /** * Logs a receipt reference to this receipt box. + * * @param receipt The {@link Receipt} to log. */ public void logReference(final Receipt receipt) { + receipts.add(receipt.getId()); } /** * Used to destroy a receipt based on the time it occurred. + * * @param time The time to use for the destruction. */ public void destroy(final long time) { + TransactionManager.receipts().removeReceiptsByTimeAndParticipant(time, owner); } /** * Used to destroy a receipt based on the {@link UUID} it occurred. + * * @param identifier The identifier to use for the destruction. */ public void destroy(final UUID identifier) { + receipts.remove(identifier); } /** * Used to find a receipt based on the time it occurred. + * * @param time The time to use for the search. + * * @return An optional with the {@link Receipt} if it exists, otherwise an empty Optional. */ public List findReceipts(final long time) { @@ -152,17 +165,22 @@ public List findReceipts(final long time) { /** * Used to find a receipt based on the {@link UUID} it occurred. + * * @param identifier The {@link UUID} to use for the search. + * * @return An optional with the {@link Receipt} if it exists, otherwise an empty Optional. */ public Optional findReceipt(final UUID identifier) { + return TransactionManager.receipts().getReceiptByUUID(identifier); } /** * This is used to return a range of {@link Receipt receipts}, based on a time range. + * * @param start The start of the time to use for the range. - * @param end The end of the time to use for the range. + * @param end The end of the time to use for the range. + * * @return A {@link TreeMap} of the receipts that occurred during the time range. */ public TreeMap range(final long start, final long end) { @@ -171,6 +189,7 @@ public TreeMap range(final long start, final long end) { } public Queue getReceipts() { + return receipts; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/transaction/tax/type/FlatType.java b/Core/src/net/tnemc/core/transaction/tax/type/FlatType.java index 3bb898f4..e3815589 100644 --- a/Core/src/net/tnemc/core/transaction/tax/type/FlatType.java +++ b/Core/src/net/tnemc/core/transaction/tax/type/FlatType.java @@ -26,24 +26,28 @@ /** * Represents a flat taxation type. This is simply the taxation amount taken as is. * - * @see TaxType * @author creatorfromhell + * @see TaxType * @since 0.1.2.0 */ public class FlatType implements TaxType { + @Override @MapKey public String name() { + return "flat"; } @Override public String asString(final BigDecimal tax) { + return "" + tax; } @Override public BigDecimal handleTaxation(final BigDecimal amount, final BigDecimal tax) { + return tax; } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/transaction/tax/type/PercentileType.java b/Core/src/net/tnemc/core/transaction/tax/type/PercentileType.java index 1f275064..8b9ec748 100644 --- a/Core/src/net/tnemc/core/transaction/tax/type/PercentileType.java +++ b/Core/src/net/tnemc/core/transaction/tax/type/PercentileType.java @@ -26,24 +26,28 @@ /** * Represents a percentile taxation type. This is taken as a percentage of the total amount. * - * @see TaxType * @author creatorfromhell + * @see TaxType * @since 0.1.2.0 */ public class PercentileType implements TaxType { + @Override @MapKey public String name() { + return "percent"; } @Override public String asString(final BigDecimal tax) { + return tax.multiply(new BigDecimal(100)).toPlainString() + "%"; } @Override public BigDecimal handleTaxation(final BigDecimal amount, final BigDecimal tax) { + return amount.multiply(tax); } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/transaction/type/ConversionType.java b/Core/src/net/tnemc/core/transaction/type/ConversionType.java index 5ab9bb1b..b5e28466 100644 --- a/Core/src/net/tnemc/core/transaction/type/ConversionType.java +++ b/Core/src/net/tnemc/core/transaction/type/ConversionType.java @@ -32,6 +32,7 @@ * @since 0.1.2.0 */ public class ConversionType implements TransactionType { + /** * The identifier of this transaction type. * @@ -40,18 +41,20 @@ public class ConversionType implements TransactionType { @Override @MapKey public String identifier() { + return "conversion"; } /** - * The taxation amount to be assessed on the recipient of the transaction. This will take the amount - * from the amount being sent to the account, and send it to the server account. + * The taxation amount to be assessed on the recipient of the transaction. This will take the + * amount from the amount being sent to the account, and send it to the server account. * * @return The {@link TaxEntry} related to the taxation amount for the recipient, if applicable, * otherwise an empty optional. */ @Override public Optional toTax() { + return Optional.empty(); } @@ -64,6 +67,7 @@ public Optional toTax() { */ @Override public Optional fromTax() { + if(MainConfig.yaml().getBoolean("Core.Transactions.Conversion.Tax.Enabled")) { final String tax = MainConfig.yaml().getString("Core.Transactions.Conversion.Tax.Rate"); TaxEntry entry; diff --git a/Core/src/net/tnemc/core/transaction/type/DepositType.java b/Core/src/net/tnemc/core/transaction/type/DepositType.java index b05b66d9..b8e3d6b2 100644 --- a/Core/src/net/tnemc/core/transaction/type/DepositType.java +++ b/Core/src/net/tnemc/core/transaction/type/DepositType.java @@ -32,48 +32,52 @@ * @since 0.1.2.0 */ public class DepositType implements TransactionType { - /** - * The identifier of this transaction type. - * - * @return The unique identifier for this transaction type. Should be human-friendly. - */ - @Override - @MapKey - public String identifier() { - return "deposit"; - } - /** - * The taxation amount to be assessed on the recipient of the transaction. This will take the amount - * from the amount being sent to the account, and send it to the server account. - * - * @return The {@link TaxEntry} related to the taxation amount for the recipient, if applicable, - * otherwise an empty optional. - */ - @Override - public Optional toTax() { - return Optional.empty(); - } + /** + * The identifier of this transaction type. + * + * @return The unique identifier for this transaction type. Should be human-friendly. + */ + @Override + @MapKey + public String identifier() { + + return "deposit"; + } + + /** + * The taxation amount to be assessed on the recipient of the transaction. This will take the + * amount from the amount being sent to the account, and send it to the server account. + * + * @return The {@link TaxEntry} related to the taxation amount for the recipient, if applicable, + * otherwise an empty optional. + */ + @Override + public Optional toTax() { + + return Optional.empty(); + } + + /** + * The taxation amount to be assessed on the sender of the transaction. This will add the amount + * to the amount being sent to the account, and send it to the server account. + * + * @return The {@link TaxEntry} related to the taxation amount for the sender, if applicable, + * otherwise an empty optional. + */ + @Override + public Optional fromTax() { - /** - * The taxation amount to be assessed on the sender of the transaction. This will add the amount - * to the amount being sent to the account, and send it to the server account. - * - * @return The {@link TaxEntry} related to the taxation amount for the sender, if applicable, - * otherwise an empty optional. - */ - @Override - public Optional fromTax() { - if(MainConfig.yaml().getBoolean("Core.Transactions.Deposit.Tax.Enabled", false)) { - final String tax = MainConfig.yaml().getString("Core.Transactions.Deposit.Tax.Rate"); - TaxEntry entry; - if(tax.contains("%")) { - entry = new TaxEntry("percent", Double.parseDouble(tax.replace("%", "")) / 100); - } else { - entry = new TaxEntry("flat", Double.parseDouble(tax)); - } - return Optional.of(entry); - } - return Optional.empty(); + if(MainConfig.yaml().getBoolean("Core.Transactions.Deposit.Tax.Enabled", false)) { + final String tax = MainConfig.yaml().getString("Core.Transactions.Deposit.Tax.Rate"); + TaxEntry entry; + if(tax.contains("%")) { + entry = new TaxEntry("percent", Double.parseDouble(tax.replace("%", "")) / 100); + } else { + entry = new TaxEntry("flat", Double.parseDouble(tax)); + } + return Optional.of(entry); } + return Optional.empty(); + } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/transaction/type/PayType.java b/Core/src/net/tnemc/core/transaction/type/PayType.java index 47b8bb78..744464c6 100644 --- a/Core/src/net/tnemc/core/transaction/type/PayType.java +++ b/Core/src/net/tnemc/core/transaction/type/PayType.java @@ -32,6 +32,7 @@ * @since 0.1.2.0 */ public class PayType implements TransactionType { + /** * The identifier of this transaction type. * @@ -40,18 +41,20 @@ public class PayType implements TransactionType { @Override @MapKey public String identifier() { + return "pay"; } /** - * The taxation amount to be assessed on the recipient of the transaction. This will take the amount - * from the amount being sent to the account, and send it to the server account. + * The taxation amount to be assessed on the recipient of the transaction. This will take the + * amount from the amount being sent to the account, and send it to the server account. * * @return The {@link TaxEntry} related to the taxation amount for the recipient, if applicable, * otherwise an empty optional. */ @Override public Optional toTax() { + if(MainConfig.yaml().getBoolean("Core.Transactions.Pay.Tax.Enabled", false)) { final String tax = MainConfig.yaml().getString("Core.Transactions.Pay.Tax.Receiver"); TaxEntry entry; @@ -74,6 +77,7 @@ public Optional toTax() { */ @Override public Optional fromTax() { + if(MainConfig.yaml().getBoolean("Core.Transactions.Pay.Tax.Enabled", false)) { final String tax = MainConfig.yaml().getString("Core.Transactions.Pay.Tax.Sender"); TaxEntry entry; diff --git a/Core/src/net/tnemc/core/transaction/type/WithdrawType.java b/Core/src/net/tnemc/core/transaction/type/WithdrawType.java index 0e85b910..dff851f6 100644 --- a/Core/src/net/tnemc/core/transaction/type/WithdrawType.java +++ b/Core/src/net/tnemc/core/transaction/type/WithdrawType.java @@ -32,48 +32,52 @@ * @since 0.1.2.0 */ public class WithdrawType implements TransactionType { - /** - * The identifier of this transaction type. - * - * @return The unique identifier for this transaction type. Should be human-friendly. - */ - @Override - @MapKey - public String identifier() { - return "withdraw"; - } - /** - * The taxation amount to be assessed on the recipient of the transaction. This will take the amount - * from the amount being sent to the account, and send it to the server account. - * - * @return The {@link TaxEntry} related to the taxation amount for the recipient, if applicable, - * otherwise an empty optional. - */ - @Override - public Optional toTax() { - return Optional.empty(); - } + /** + * The identifier of this transaction type. + * + * @return The unique identifier for this transaction type. Should be human-friendly. + */ + @Override + @MapKey + public String identifier() { + + return "withdraw"; + } + + /** + * The taxation amount to be assessed on the recipient of the transaction. This will take the + * amount from the amount being sent to the account, and send it to the server account. + * + * @return The {@link TaxEntry} related to the taxation amount for the recipient, if applicable, + * otherwise an empty optional. + */ + @Override + public Optional toTax() { + + return Optional.empty(); + } + + /** + * The taxation amount to be assessed on the sender of the transaction. This will add the amount + * to the amount being sent to the account, and send it to the server account. + * + * @return The {@link TaxEntry} related to the taxation amount for the sender, if applicable, + * otherwise an empty optional. + */ + @Override + public Optional fromTax() { - /** - * The taxation amount to be assessed on the sender of the transaction. This will add the amount - * to the amount being sent to the account, and send it to the server account. - * - * @return The {@link TaxEntry} related to the taxation amount for the sender, if applicable, - * otherwise an empty optional. - */ - @Override - public Optional fromTax() { - if(MainConfig.yaml().getBoolean("Core.Transactions.Withdraw.Tax.Enabled", false)) { - final String tax = MainConfig.yaml().getString("Core.Transactions.Withdraw.Tax.Rate"); - TaxEntry entry; - if(tax.contains("%")) { - entry = new TaxEntry("percent", Double.parseDouble(tax.replace("%", "")) / 100); - } else { - entry = new TaxEntry("flat", Double.parseDouble(tax)); - } - return Optional.of(entry); - } - return Optional.empty(); + if(MainConfig.yaml().getBoolean("Core.Transactions.Withdraw.Tax.Enabled", false)) { + final String tax = MainConfig.yaml().getString("Core.Transactions.Withdraw.Tax.Rate"); + TaxEntry entry; + if(tax.contains("%")) { + entry = new TaxEntry("percent", Double.parseDouble(tax.replace("%", "")) / 100); + } else { + entry = new TaxEntry("flat", Double.parseDouble(tax)); + } + return Optional.of(entry); } + return Optional.empty(); + } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/utils/Extractor.java b/Core/src/net/tnemc/core/utils/Extractor.java index b204d362..454dabbb 100644 --- a/Core/src/net/tnemc/core/utils/Extractor.java +++ b/Core/src/net/tnemc/core/utils/Extractor.java @@ -45,6 +45,7 @@ public class Extractor { public static boolean extract() { + final File file = new File(PluginCore.directory(), "extracted.yml"); //check to see if file exists, if it does we are going to move it to the extracts directory. @@ -86,10 +87,10 @@ public static boolean extract() { String username = account.getName(); username = username.replaceAll("\\.", "!").replaceAll("\\-", "@") - .replaceAll("\\_", "%"); + .replaceAll("\\_", "%"); yaml.set("Accounts." + username + ".Balances." + entry.getRegion() + "." - + entry.getCurrency() + "." + entry.getHandler().asID(), entry.getAmount().toPlainString()); + + entry.getCurrency() + "." + entry.getHandler().asID(), entry.getAmount().toPlainString()); yaml.set("Accounts." + username + ".id", account.getIdentifier()); } @@ -97,11 +98,11 @@ public static boolean extract() { try { final boolean message = (number % frequency == 0); - if (message) { + if(message) { final int progress = (number * 100) / total; PluginCore.log().inform("Extraction Progress: " + progress); } - } catch(Exception ignore) {} + } catch(Exception ignore) { } } try { @@ -115,6 +116,7 @@ public static boolean extract() { } public static boolean restore(@Nullable final Integer extraction) { + File file; if(extraction != null && extraction > 0) { @@ -168,7 +170,7 @@ public static boolean restore(@Nullable final Integer extraction) { final String currency = (String)currencyObj; if(!recode) { - final String finalCurrency = (currency.equalsIgnoreCase("default")) ? TNECore.eco().currency().getDefaultCurrency(region).getIdentifier() : currency; + final String finalCurrency = (currency.equalsIgnoreCase("default"))? TNECore.eco().currency().getDefaultCurrency(region).getIdentifier() : currency; Optional cur = TNECore.eco().currency().findCurrency(finalCurrency); PluginCore.log().inform("Currency avail: " + cur.isPresent()); @@ -184,7 +186,7 @@ public static boolean restore(@Nullable final Integer extraction) { PluginCore.log().inform("Use default currency"); PluginCore.log().inform("Set Balance to: " + amount.toPlainString()); response.getAccount().get().setHoldings(new HoldingsEntry(region, TNECore.eco().currency().getDefaultCurrency(region).getUid(), - amount, EconomyManager.NORMAL)); + amount, EconomyManager.NORMAL)); } } else { @@ -193,9 +195,9 @@ public static boolean restore(@Nullable final Integer extraction) { final String type = (String)typeObj; final BigDecimal amount = new BigDecimal(extracted.getString("Accounts." + name - + ".Balances." + region - + "." + currency + "." - + type)); + + ".Balances." + region + + "." + currency + "." + + type)); response.getAccount().get().setHoldings(new HoldingsEntry(region, UUID.fromString(currency), amount, Identifier.fromID(type))); @@ -205,11 +207,11 @@ public static boolean restore(@Nullable final Integer extraction) { try { final boolean message = (number % frequency == 0); - if (message) { + if(message) { final int progress = (number * 100) / accounts.size(); PluginCore.log().inform("Restoration Progress: " + progress); } - } catch(Exception ignore) {} + } catch(Exception ignore) { } } } } diff --git a/Core/src/net/tnemc/core/utils/Identifier.java b/Core/src/net/tnemc/core/utils/Identifier.java index 11efc7d8..ffd92dbd 100644 --- a/Core/src/net/tnemc/core/utils/Identifier.java +++ b/Core/src/net/tnemc/core/utils/Identifier.java @@ -31,6 +31,7 @@ public record Identifier(String plugin, String id) { public String asID() { + return plugin + ":" + id; } @@ -58,6 +59,7 @@ public static Identifier fromID(final String id) { */ @Override public boolean equals(Object obj) { + if(obj instanceof Identifier) { return ((Identifier)obj).asID().equalsIgnoreCase(asID()); } diff --git a/Core/src/net/tnemc/core/utils/MISCUtils.java b/Core/src/net/tnemc/core/utils/MISCUtils.java index 8b387c76..6611f36b 100644 --- a/Core/src/net/tnemc/core/utils/MISCUtils.java +++ b/Core/src/net/tnemc/core/utils/MISCUtils.java @@ -40,10 +40,12 @@ public class MISCUtils { public static String worldFormatted(final String world) { + return MessageConfig.yaml().getString("Messages.Worlds." + world, world); } public static void setComment(YamlDocument yaml, String route, String comment) { + setComment(yaml, route, Collections.singletonList(comment)); } @@ -55,6 +57,7 @@ public static void setComment(YamlDocument yaml, String route, List comm } public static String randomString(final int length) { + final Random rand = new Random(); final StringBuilder identifierBuilder = new StringBuilder(); for(int i = 0; i < length; i++) { @@ -65,9 +68,10 @@ public static String randomString(final int length) { } public static void deleteFolder(File folder) { + File[] files = folder.listFiles(); - if(files!=null) { //some JVMs return null for empty dirs - for(File f: files) { + if(files != null) { //some JVMs return null for empty dirs + for(File f : files) { if(f.isDirectory()) { deleteFolder(f); } else { @@ -79,6 +83,7 @@ public static void deleteFolder(File folder) { } public static void zipFolder(File sourceFolder, String destinationZipFile) throws IOException { + try(FileOutputStream fos = new FileOutputStream(destinationZipFile); ZipOutputStream zos = new ZipOutputStream(fos)) { @@ -95,6 +100,7 @@ public static void zipFolder(File sourceFolder, String destinationZipFile) throw } public static void zipFile(File fileToZip, String fileName, ZipOutputStream zipOut) throws IOException { + if(fileToZip.isHidden()) { return; } @@ -146,8 +152,8 @@ public static void zipFolder(final File folder, final String parentFolder, final return; } - for (File file : files) { - if (file.isDirectory()) { + for(File file : files) { + if(file.isDirectory()) { zipFolder(file, parentFolder + File.separator + file.getName(), zos); continue; } @@ -155,10 +161,10 @@ public static void zipFolder(final File folder, final String parentFolder, final final ZipEntry zipEntry = new ZipEntry(parentFolder + File.separator + file.getName()); zos.putNextEntry(zipEntry); - try (FileInputStream fis = new FileInputStream(file)) { + try(FileInputStream fis = new FileInputStream(file)) { final byte[] buffer = new byte[1024]; int length; - while ((length = fis.read(buffer)) > 0) { + while((length = fis.read(buffer)) > 0) { zos.write(buffer, 0, length); } } diff --git a/Core/src/net/tnemc/core/utils/Monetary.java b/Core/src/net/tnemc/core/utils/Monetary.java index 9b68566f..b53663ff 100644 --- a/Core/src/net/tnemc/core/utils/Monetary.java +++ b/Core/src/net/tnemc/core/utils/Monetary.java @@ -38,6 +38,7 @@ public class Monetary { String minor = "0"; public Monetary(final BigDecimal decimal, final int scale) { + this.scale = scale; calculate(decimal, scale); } @@ -58,18 +59,22 @@ private void calculate(final BigDecimal decimal, } public BigInteger major() { + return major; } public String minor() { + return minor; } public BigInteger minorAsInt() { + return new BigInteger(minor); } public int scale() { + return scale; } } diff --git a/Core/src/net/tnemc/core/utils/exceptions/InvalidAccountException.java b/Core/src/net/tnemc/core/utils/exceptions/InvalidAccountException.java index 2b5707ef..7695bbf1 100644 --- a/Core/src/net/tnemc/core/utils/exceptions/InvalidAccountException.java +++ b/Core/src/net/tnemc/core/utils/exceptions/InvalidAccountException.java @@ -27,11 +27,11 @@ public class InvalidAccountException extends Exception { /** - * Constructs a new exception with {@code null} as its detail message. - * The cause is not initialized, and may subsequently be initialized by a - * call to {@link #initCause}. + * Constructs a new exception with {@code null} as its detail message. The cause is not + * initialized, and may subsequently be initialized by a call to {@link #initCause}. */ public InvalidAccountException(String missing) { + super("The account specified does not exist. Name: " + missing); } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/utils/exceptions/InvalidStatusException.java b/Core/src/net/tnemc/core/utils/exceptions/InvalidStatusException.java index 2e38afc7..3fcd4051 100644 --- a/Core/src/net/tnemc/core/utils/exceptions/InvalidStatusException.java +++ b/Core/src/net/tnemc/core/utils/exceptions/InvalidStatusException.java @@ -27,11 +27,11 @@ public class InvalidStatusException extends Exception { /** - * Constructs a new exception with {@code null} as its detail message. - * The cause is not initialized, and may subsequently be initialized by a - * call to {@link #initCause}. + * Constructs a new exception with {@code null} as its detail message. The cause is not + * initialized, and may subsequently be initialized by a call to {@link #initCause}. */ public InvalidStatusException(String missing) { + super("The account status specified does not exist. Status: " + missing); } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/utils/exceptions/InvalidTransactionException.java b/Core/src/net/tnemc/core/utils/exceptions/InvalidTransactionException.java index f4075ff8..a901ac08 100644 --- a/Core/src/net/tnemc/core/utils/exceptions/InvalidTransactionException.java +++ b/Core/src/net/tnemc/core/utils/exceptions/InvalidTransactionException.java @@ -27,12 +27,12 @@ public class InvalidTransactionException extends Exception { /** - * Constructs a new exception with {@code null} as its detail message. - * The cause is not initialized, and may subsequently be initialized by a - * call to {@link #initCause}. + * Constructs a new exception with {@code null} as its detail message. The cause is not + * initialized, and may subsequently be initialized by a call to {@link #initCause}. */ public InvalidTransactionException(String missing) { + super("The transaction attempted was missing a requirement and could not be processed!" + - "Missing: " + missing); + "Missing: " + missing); } } \ No newline at end of file diff --git a/Core/src/net/tnemc/core/utils/exceptions/NoValidCurrenciesException.java b/Core/src/net/tnemc/core/utils/exceptions/NoValidCurrenciesException.java index a1d67a44..b88aba52 100644 --- a/Core/src/net/tnemc/core/utils/exceptions/NoValidCurrenciesException.java +++ b/Core/src/net/tnemc/core/utils/exceptions/NoValidCurrenciesException.java @@ -27,11 +27,11 @@ public class NoValidCurrenciesException extends Exception { /** - * Constructs a new exception with {@code null} as its detail message. - * The cause is not initialized, and may subsequently be initialized by a - * call to {@link #initCause}. + * Constructs a new exception with {@code null} as its detail message. The cause is not + * initialized, and may subsequently be initialized by a call to {@link #initCause}. */ public NoValidCurrenciesException() { + super("No valid currencies could be found!"); } } \ No newline at end of file diff --git a/Core/walkthrough.md b/Core/walkthrough.md index 584847a7..a5baf0d5 100644 --- a/Core/walkthrough.md +++ b/Core/walkthrough.md @@ -1,18 +1,20 @@ # About -This file outlines what features are done/in progress/ etc. It also outlines a step-by-step outline of what features are +This file outlines what features are done/in progress/ etc. It also outlines a step-by-step outline +of what features are complete as it relates to the player cycle, so log in until log off. # Walk Through + - Log IN - Does Account Exist?(done) - - Yes? - - Update Item Currencies - - Send transactions that happened while offline - - if admin - - update check - - any concerning transactions that they should be aware of? - - No? - - Create Account(done) - - Set default currency balances. + - Yes? + - Update Item Currencies + - Send transactions that happened while offline + - if admin + - update check + - any concerning transactions that they should be aware of? + - No? + - Create Account(done) + - Set default currency balances. - \ No newline at end of file diff --git a/Folia/pom.xml b/Folia/pom.xml index 51ab2475..59d7a5a4 100644 --- a/Folia/pom.xml +++ b/Folia/pom.xml @@ -1,4 +1,6 @@ - + 4.0.0 Folia jar @@ -91,7 +93,9 @@ - ${project.build.directory}/dependency-reduced-pom.xml + + ${project.build.directory}/dependency-reduced-pom.xml + net.tnemc:* diff --git a/Folia/src/net/tnemc/folia/FoliaCore.java b/Folia/src/net/tnemc/folia/FoliaCore.java index 02109225..8f8baee9 100644 --- a/Folia/src/net/tnemc/folia/FoliaCore.java +++ b/Folia/src/net/tnemc/folia/FoliaCore.java @@ -30,11 +30,13 @@ public class FoliaCore extends PaperCore { public FoliaCore(JavaPlugin plugin) { + super(plugin); } @Override public void registerMenuHandler() { + this.menuHandler = new FoliaMenuHandler(plugin, true); } } \ No newline at end of file diff --git a/Folia/src/net/tnemc/folia/TNE.java b/Folia/src/net/tnemc/folia/TNE.java index ee3a0733..cd52aba0 100644 --- a/Folia/src/net/tnemc/folia/TNE.java +++ b/Folia/src/net/tnemc/folia/TNE.java @@ -34,16 +34,19 @@ public class TNE extends JavaPlugin { @Override public void onLoad() { + this.paper.load(this, new FoliaCore(this), new FoliaServerProvider()); } @Override public void onEnable() { + this.paper.enable(this); } @Override public void onDisable() { + this.paper.disable(this); } } \ No newline at end of file diff --git a/Folia/src/net/tnemc/folia/impl/FoliaInventoryProvider.java b/Folia/src/net/tnemc/folia/impl/FoliaInventoryProvider.java index 347de173..f4575f14 100644 --- a/Folia/src/net/tnemc/folia/impl/FoliaInventoryProvider.java +++ b/Folia/src/net/tnemc/folia/impl/FoliaInventoryProvider.java @@ -36,6 +36,7 @@ public class FoliaInventoryProvider extends FoliaInventory implements InventoryProvider { public FoliaInventoryProvider(UUID id, JavaPlugin plugin) { + super(id, plugin); } @@ -48,6 +49,7 @@ public FoliaInventoryProvider(UUID id, JavaPlugin plugin) { */ @Override public Inventory getInventory(boolean ender) { + final OfflinePlayer player = Bukkit.getOfflinePlayer(player()); if(player.getPlayer() == null) return null; diff --git a/Folia/src/net/tnemc/folia/impl/FoliaPlayerProvider.java b/Folia/src/net/tnemc/folia/impl/FoliaPlayerProvider.java index 67b2d8db..7520702c 100644 --- a/Folia/src/net/tnemc/folia/impl/FoliaPlayerProvider.java +++ b/Folia/src/net/tnemc/folia/impl/FoliaPlayerProvider.java @@ -43,6 +43,7 @@ public class FoliaPlayerProvider extends FoliaPlayer implements PlayerProvider { private final OfflinePlayer player; public FoliaPlayerProvider(OfflinePlayer player) { + super(player, PaperCore.instance().getPlugin()); this.player = player; } @@ -54,6 +55,7 @@ public FoliaPlayerProvider(OfflinePlayer player) { */ @Override public UUID identifier() { + return player.getUniqueId(); } @@ -64,6 +66,7 @@ public UUID identifier() { */ @Override public String getName() { + return player.getName(); } @@ -74,6 +77,7 @@ public String getName() { */ @Override public Optional getLocation() { + if(player.getPlayer() == null) { return Optional.empty(); } @@ -93,6 +97,7 @@ public Optional getLocation() { */ @Override public String world() { + String world = TNECore.eco().region().defaultRegion(); if(player.getPlayer() != null) { @@ -108,6 +113,7 @@ public String world() { */ @Override public String biome() { + String biome = TNECore.eco().region().defaultRegion(); if(player.getPlayer() != null) { @@ -123,6 +129,7 @@ public String biome() { */ @Override public int getExp() { + if(player.getPlayer() == null) { return 0; } @@ -136,6 +143,7 @@ public int getExp() { */ @Override public void setExp(int exp) { + if(player.getPlayer() != null) { player.getPlayer().setTotalExperience(exp); } @@ -148,6 +156,7 @@ public void setExp(int exp) { */ @Override public int getExpLevel() { + if(player.getPlayer() == null) { return 0; } @@ -161,6 +170,7 @@ public int getExpLevel() { */ @Override public void setExpLevel(int level) { + if(player.getPlayer() != null) { player.getPlayer().setLevel(level); } @@ -168,6 +178,7 @@ public void setExpLevel(int level) { @Override public FoliaInventoryProvider inventory() { + return new FoliaInventoryProvider(identifier(), PaperCore.instance().getPlugin()); } @@ -180,6 +191,7 @@ public FoliaInventoryProvider inventory() { */ @Override public boolean hasPermission(String permission) { + if(player.getPlayer() == null) { return false; } @@ -188,6 +200,7 @@ public boolean hasPermission(String permission) { @Override public void message(String message) { + if(player.getPlayer() != null) { message(new MessageData(message)); } @@ -200,6 +213,7 @@ public void message(String message) { */ @Override public void message(final MessageData messageData) { + if(player.getPlayer() == null) { return; } @@ -210,13 +224,15 @@ public void message(final MessageData messageData) { } public OfflinePlayer getPlayer() { + return player; } public static FoliaPlayerProvider find(final String identifier) { + try { return new FoliaPlayerProvider(Bukkit.getOfflinePlayer(UUID.fromString(identifier))); - } catch (Exception ignore) { + } catch(Exception ignore) { return new FoliaPlayerProvider(Bukkit.getOfflinePlayer(identifier)); } } diff --git a/Folia/src/net/tnemc/folia/impl/FoliaServerProvider.java b/Folia/src/net/tnemc/folia/impl/FoliaServerProvider.java index 549c7da0..4bf1ea0f 100644 --- a/Folia/src/net/tnemc/folia/impl/FoliaServerProvider.java +++ b/Folia/src/net/tnemc/folia/impl/FoliaServerProvider.java @@ -68,27 +68,30 @@ public class FoliaServerProvider implements ServerConnector { protected String world = null; public FoliaServerProvider() { + this.scheduler = new FoliaScheduler(); } @Override public String name() { + return "folia"; } /** * Used to replace placeholders from a string. * - * @param player The player to use for the placeholder replacement. + * @param player The player to use for the placeholder replacement. * @param message The message to replace placeholders in. * * @return The string after placeholders have been replaced. */ @Override public String replacePlaceholder(UUID player, String message) { + final Optional playerOpt = PluginCore.server().findPlayer(player); if(Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI") && playerOpt.isPresent() - && playerOpt.get() instanceof BukkitPlayerProvider bukkitPlayer) { + && playerOpt.get() instanceof BukkitPlayerProvider bukkitPlayer) { return PAPIParser.parse(bukkitPlayer, message); } return message; @@ -101,6 +104,7 @@ public String replacePlaceholder(UUID player, String message) { */ @Override public ProxyProvider proxy() { + return proxy; } @@ -113,6 +117,7 @@ public ProxyProvider proxy() { */ @Override public CmdSource source(@NotNull CommandActor actor) { + return null; } @@ -123,6 +128,7 @@ public CmdSource source(@NotNull CommandActor actor) { */ @Override public int onlinePlayers() { + return Bukkit.getOnlinePlayers().size(); } @@ -131,8 +137,8 @@ public int onlinePlayers() { * * @param identifier The identifier * - * @return An Optional containing the located {@link PlayerProvider player}, or an empty - * Optional if no player is located. + * @return An Optional containing the located {@link PlayerProvider player}, or an empty Optional + * if no player is located. */ @Override public Optional findPlayer(@NotNull UUID identifier) { @@ -150,6 +156,7 @@ public Optional findPlayer(@NotNull UUID identifier) { */ @Override public PlayerProvider initializePlayer(@NotNull Object player) { + if(player instanceof Player playerObj) { return new FoliaPlayerProvider(playerObj); } @@ -165,20 +172,20 @@ public PlayerProvider initializePlayer(@NotNull Object player) { */ @Override public boolean playedBefore(UUID uuid) { + return false; } /** - * Used to determine if a player with the specified username has played - * before. + * Used to determine if a player with the specified username has played before. * * @param name The username to search for. * - * @return True if someone with the specified username has played before, - * otherwise false. + * @return True if someone with the specified username has played before, otherwise false. */ @Override public boolean playedBefore(String name) { + return false; } @@ -191,6 +198,7 @@ public boolean playedBefore(String name) { */ @Override public boolean online(String name) { + try { final UUID id = UUID.fromString(name); @@ -222,6 +230,7 @@ public Optional fromName(String name) { */ @Override public Optional fromID(UUID id) { + for(OfflinePlayer player : Bukkit.getServer().getOfflinePlayers()) { if(player.getUniqueId().equals(id)) { return Optional.ofNullable(player.getName()); @@ -232,6 +241,7 @@ public Optional fromID(UUID id) { @Override public String defaultWorld() { + if(world == null) { world = Bukkit.getServer().getWorlds().get(0).getName(); } @@ -247,11 +257,13 @@ public String defaultWorld() { */ @Override public boolean pluginAvailable(String name) { + return Bukkit.getPluginManager().isPluginEnabled(name); } @Override public String replaceColours(String string, boolean strip) { + if(strip) { return ChatColor.stripColor(string); } @@ -260,16 +272,19 @@ public String replaceColours(String string, boolean strip) { @Override public AbstractItemStack stackBuilder() { + return new BukkitItemStack(); } @Override public void saveResource(String path, boolean replace) { + PaperCore.instance().getPlugin().saveResource(path, replace); } @Override public @Nullable InputStream getResource(@NotNull String s) { + return null; } @@ -280,6 +295,7 @@ public void saveResource(String path, boolean replace) { */ @Override public FoliaScheduler scheduler() { + return scheduler; } @@ -291,41 +307,43 @@ public FoliaScheduler scheduler() { * @see CraftingRecipe */ @Override - public void registerCrafting(@NotNull final String key, @NotNull CraftingRecipe recipe) {if(recipe.isShaped()) { - ShapedRecipe shaped; + public void registerCrafting(@NotNull final String key, @NotNull CraftingRecipe recipe) { - try { - shaped = new ShapedRecipe(new NamespacedKey(PaperCore.instance().getPlugin(), key), (ItemStack)recipe.getResult().locale()); - } catch(Exception ignore) { - shaped = new ShapedRecipe((ItemStack)recipe.getResult().locale()); - } + if(recipe.isShaped()) { + ShapedRecipe shaped; - shaped.shape(recipe.getRows()); + try { + shaped = new ShapedRecipe(new NamespacedKey(PaperCore.instance().getPlugin(), key), (ItemStack)recipe.getResult().locale()); + } catch(Exception ignore) { + shaped = new ShapedRecipe((ItemStack)recipe.getResult().locale()); + } - for(Map.Entry ingredient : recipe.getIngredients().entrySet()) { - shaped.setIngredient(ingredient.getKey(), Material.valueOf(ingredient.getValue())); - } - Bukkit.getServer().addRecipe(shaped); - } else { - ShapelessRecipe shapeless; + shaped.shape(recipe.getRows()); - try { - shapeless = new ShapelessRecipe(new NamespacedKey(PaperCore.instance().getPlugin(), key), (ItemStack)recipe.getResult().locale()); - } catch(Exception ignore) { - shapeless = new ShapelessRecipe((ItemStack)recipe.getResult().locale()); - } + for(Map.Entry ingredient : recipe.getIngredients().entrySet()) { + shaped.setIngredient(ingredient.getKey(), Material.valueOf(ingredient.getValue())); + } + Bukkit.getServer().addRecipe(shaped); + } else { + ShapelessRecipe shapeless; + + try { + shapeless = new ShapelessRecipe(new NamespacedKey(PaperCore.instance().getPlugin(), key), (ItemStack)recipe.getResult().locale()); + } catch(Exception ignore) { + shapeless = new ShapelessRecipe((ItemStack)recipe.getResult().locale()); + } - for(Map.Entry ingredient : recipe.getIngredients().entrySet()) { - shapeless.addIngredient(1, Material.valueOf(ingredient.getValue())); + for(Map.Entry ingredient : recipe.getIngredients().entrySet()) { + shapeless.addIngredient(1, Material.valueOf(ingredient.getValue())); + } + Bukkit.getServer().addRecipe(shapeless); } - Bukkit.getServer().addRecipe(shapeless); - } } @Override public PaperCalculationsProvider calculations() { + return calc; } - } \ No newline at end of file diff --git a/Folia/src/net/tnemc/folia/impl/scheduler/FoliaChore.java b/Folia/src/net/tnemc/folia/impl/scheduler/FoliaChore.java index 5a160897..4d123e81 100644 --- a/Folia/src/net/tnemc/folia/impl/scheduler/FoliaChore.java +++ b/Folia/src/net/tnemc/folia/impl/scheduler/FoliaChore.java @@ -31,6 +31,7 @@ public class FoliaChore extends Chore { public FoliaChore(ScheduledTask task, ChoreExecution execution) { + super(task, execution); } @@ -39,6 +40,7 @@ public FoliaChore(ScheduledTask task, ChoreExecution execution) { */ @Override public void cancel() { + task.cancel(); } } \ No newline at end of file diff --git a/Folia/src/net/tnemc/folia/impl/scheduler/FoliaScheduler.java b/Folia/src/net/tnemc/folia/impl/scheduler/FoliaScheduler.java index e37b7fb8..da742795 100644 --- a/Folia/src/net/tnemc/folia/impl/scheduler/FoliaScheduler.java +++ b/Folia/src/net/tnemc/folia/impl/scheduler/FoliaScheduler.java @@ -34,34 +34,36 @@ * @since 0.1.2.0 */ public class FoliaScheduler extends SchedulerProvider { + /** * Used to create a task, which will execute after the specified delay. * - * @param task The task to run. - * @param delay The delay, in ticks. + * @param task The task to run. + * @param delay The delay, in ticks. * @param environment The execution environment for the task. */ @Override public void createDelayedTask(Runnable task, ChoreTime delay, ChoreExecution environment) { //we divide the delay by 20 because Folia uses seconds, and the delay is sent in ticks. - Bukkit.getAsyncScheduler().runDelayed(PaperCore.instance().getPlugin(), (scheduledTask) -> task.run(), delay.asSeconds(), TimeUnit.SECONDS); + Bukkit.getAsyncScheduler().runDelayed(PaperCore.instance().getPlugin(), (scheduledTask)->task.run(), delay.asSeconds(), TimeUnit.SECONDS); } /** * Used to create a task, which repeats after a specified period. * - * @param task The task to run. - * @param delay The delay to run the task, in ticks. - * @param period The period to run the task. + * @param task The task to run. + * @param delay The delay to run the task, in ticks. + * @param period The period to run the task. * @param environment The execution environment for the task. * * @return The associated {@link Chore} with this task. */ @Override public FoliaChore createRepeatingTask(Runnable task, ChoreTime delay, ChoreTime period, ChoreExecution environment) { + return new FoliaChore(Bukkit.getAsyncScheduler() - .runAtFixedRate(PaperCore.instance().getPlugin(), (scheduledTask)->task.run(), - delay.asSeconds(), period.asSeconds(), TimeUnit.SECONDS), - environment); + .runAtFixedRate(PaperCore.instance().getPlugin(), (scheduledTask)->task.run(), + delay.asSeconds(), period.asSeconds(), TimeUnit.SECONDS), + environment); } } diff --git a/PaperCore/pom.xml b/PaperCore/pom.xml index 44ff4890..461d8495 100644 --- a/PaperCore/pom.xml +++ b/PaperCore/pom.xml @@ -1,4 +1,6 @@ - + 4.0.0 Paper jar @@ -20,7 +22,6 @@ - clean package target @@ -77,7 +78,9 @@ - ${project.build.directory}/dependency-reduced-pom.xml + + ${project.build.directory}/dependency-reduced-pom.xml + net.tnemc:* diff --git a/PaperCore/src/net/tnemc/paper/PaperCore.java b/PaperCore/src/net/tnemc/paper/PaperCore.java index fcaf189d..6505a3c1 100644 --- a/PaperCore/src/net/tnemc/paper/PaperCore.java +++ b/PaperCore/src/net/tnemc/paper/PaperCore.java @@ -50,26 +50,31 @@ public class PaperCore extends TNECore { private BukkitConfig bukkitConfig; public PaperCore(JavaPlugin plugin) { + this.plugin = plugin; } @Override public void registerMenuHandler() { + this.menuHandler = new PaperMenuHandler(plugin, true); } @Override public void registerCommandHandler() { + command = BukkitCommandHandler.create(plugin); } @Override public String commandHelpWriter(ExecutableCommand executableCommand, CommandActor commandActor) { + return ""; } @Override public void registerConfigs() { + super.registerConfigs(); this.bukkitConfig = new BukkitConfig(); @@ -80,6 +85,7 @@ public void registerConfigs() { @Override public void registerCommands() { + super.registerCommands(); //Register our commands @@ -92,6 +98,7 @@ public void registerCommands() { @Override public void registerCallbacks(CallbackManager callbackManager) { + super.registerCallbacks(callbackManager); callbackManager.addConsumer(TNECallbacks.ACCOUNT_TYPES.toString(), (callback->{ @@ -112,14 +119,17 @@ public void registerCallbacks(CallbackManager callbackManager) { @Override public BukkitItemCalculations itemCalculations() { + return new BukkitItemCalculations(); } public static PaperCore instance() { + return (PaperCore)TNECore.instance(); } public JavaPlugin getPlugin() { + return plugin; } } \ No newline at end of file diff --git a/PaperCore/src/net/tnemc/paper/PaperDebugCalculations.java b/PaperCore/src/net/tnemc/paper/PaperDebugCalculations.java index ac57129e..77bccb0d 100644 --- a/PaperCore/src/net/tnemc/paper/PaperDebugCalculations.java +++ b/PaperCore/src/net/tnemc/paper/PaperDebugCalculations.java @@ -54,13 +54,14 @@ public class PaperDebugCalculations extends PaperCalculationsProvider { /** * Used to drop items near a player. * - * @param left A Collection containing the items to drop. + * @param left A Collection containing the items to drop. * @param player The UUID of the player to drop the items near. * * @return True if the items were successfully dropped, otherwise false. */ @Override public boolean drop(Collection left, UUID player) { + final Player playerObj = Bukkit.getPlayer(player); if(playerObj != null) { @@ -79,6 +80,7 @@ public boolean drop(Collection left, UUID player) { */ @Override public int removeAll(PaperItemStack stack, Inventory inventory) { + final ItemStack compare = stack.locale().clone(); compare.setAmount(1); @@ -123,6 +125,7 @@ public int removeAll(PaperItemStack stack, Inventory inventory) { */ @Override public int count(PaperItemStack stack, Inventory inventory) { + final ItemStack compare = stack.locale().clone(); compare.setAmount(1); @@ -185,19 +188,24 @@ public int count(PaperItemStack stack, Inventory inventory) { /** * Takes a collection of items from an inventory. - * @param items The collection of items to remove. + * + * @param items The collection of items to remove. * @param inventory The inventory to remove the items from. */ public void takeItems(Collection items, Inventory inventory) { - items.forEach(itemStack -> removeItem(itemStack, inventory)); + + items.forEach(itemStack->removeItem(itemStack, inventory)); } /** - * Adds a collection of net.tnemc.item stacks to an inventory, dropping them on the ground if it's a player inventory and overflow exists. - * @param items The collection of items to add to the inventory. + * Adds a collection of net.tnemc.item stacks to an inventory, dropping them on the ground if it's + * a player inventory and overflow exists. + * + * @param items The collection of items to add to the inventory. * @param inventory The inventory to add the collection of items to. */ public Collection giveItems(Collection items, Inventory inventory) { + final Collection leftOver = new ArrayList<>(); for(PaperItemStack item : items) { @@ -218,12 +226,15 @@ public Collection giveItems(Collection items, In /** * Removes an ItemStack with a specific amount from an inventory. - * @param stack The stack, with the correct amount, to remove. + * + * @param stack The stack, with the correct amount, to remove. * @param inventory The inventory to return the net.tnemc.item stack from. + * * @return The remaining amount of items to remove. */ @Override public int removeItem(PaperItemStack stack, Inventory inventory) { + int left = stack.locale().clone().getAmount(); final ItemStack compare = stack.locale().clone(); @@ -283,6 +294,7 @@ public int removeItem(PaperItemStack stack, Inventory inventory) { */ @Override public Optional getInventory(UUID identifier, InventoryType type) { + final OfflinePlayer player = Bukkit.getOfflinePlayer(identifier); if(player.isOnline() && player.getPlayer() != null) { diff --git a/PaperCore/src/net/tnemc/paper/PaperPlugin.java b/PaperCore/src/net/tnemc/paper/PaperPlugin.java index 0261a9c9..6c7c6c30 100644 --- a/PaperCore/src/net/tnemc/paper/PaperPlugin.java +++ b/PaperCore/src/net/tnemc/paper/PaperPlugin.java @@ -55,12 +55,13 @@ public class PaperPlugin { private boolean papiHooked = false; public void load(final JavaPlugin plugin) { + load(plugin, new PaperCore(plugin), new PaperServerProvider(new PaperCalculationsProvider())); } /** - * Called when the plugin is loaded by the Bukkit plugin manager. - * This method should be used to initialize any necessary resources or data. + * Called when the plugin is loaded by the Bukkit plugin manager. This method should be used to + * initialize any necessary resources or data. */ public void load(final JavaPlugin plugin, TNECore core, ServerConnector provider) { @@ -87,8 +88,8 @@ public void load(final JavaPlugin plugin, TNECore core, ServerConnector provider } /** - * Called by the Bukkit plugin manager when the plugin is enabled. - * This method should be used to enable the functionality provided by this class. + * Called by the Bukkit plugin manager when the plugin is enabled. This method should be used to + * enable the functionality provided by this class. */ public void enable(final JavaPlugin plugin) { @@ -124,18 +125,21 @@ public void enable(final JavaPlugin plugin) { } /** - * Called by the Bukkit plugin manager when the plugin is disabled. - * This method should be used to disable the functionality provided by this class. + * Called by the Bukkit plugin manager when the plugin is disabled. This method should be used to + * disable the functionality provided by this class. */ public void disable(final JavaPlugin plugin) { + this.pluginCore.onDisable(); } public boolean isPapiHooked() { + return papiHooked; } public void setPapiHooked(boolean papiHooked) { + this.papiHooked = papiHooked; } } diff --git a/PaperCore/src/net/tnemc/paper/TNE.java b/PaperCore/src/net/tnemc/paper/TNE.java index 287958e8..890596e2 100644 --- a/PaperCore/src/net/tnemc/paper/TNE.java +++ b/PaperCore/src/net/tnemc/paper/TNE.java @@ -32,16 +32,19 @@ public class TNE extends JavaPlugin { @Override public void onLoad() { + this.paper.load(this); } @Override public void onEnable() { + this.paper.enable(this); } @Override public void onDisable() { + this.paper.disable(this); } } \ No newline at end of file diff --git a/PaperCore/src/net/tnemc/paper/command/AdminCommand.java b/PaperCore/src/net/tnemc/paper/command/AdminCommand.java index 46ab9d7d..59971f9a 100644 --- a/PaperCore/src/net/tnemc/paper/command/AdminCommand.java +++ b/PaperCore/src/net/tnemc/paper/command/AdminCommand.java @@ -59,133 +59,149 @@ * @author creatorfromhell * @since 0.1.2.0 */ -@Command({"tne", "myeco", "ecomenu", "ecomin", "ecoadmin", "ecomanage", "theneweconomy"}) +@Command({ "tne", "myeco", "ecomenu", "ecomin", "ecoadmin", "ecomanage", "theneweconomy" }) @Description("Admin.Main.Description") public class AdminCommand { - @DefaultFor({"tne", "myeco", "ecomenu", "ecomin", "ecoadmin", "ecomanage", "theneweconomy"}) - @Subcommand({"ecomenu", "menu", "myeco"}) + @DefaultFor({ "tne", "myeco", "ecomenu", "ecomin", "ecoadmin", "ecomanage", "theneweconomy" }) + @Subcommand({ "ecomenu", "menu", "myeco" }) @Usage("Admin.MyEco.Arguments") @Description("Admin.MyEco.Description") @CommandPermission("tne.admin.menu") public void onMyEco(BukkitCommandActor sender) { + net.tnemc.core.command.AdminCommand.onMyEco(new PaperCMDSource(sender)); } - @Subcommand({"help", "?"}) + @Subcommand({ "help", "?" }) @Usage("Help.Arguments") @Description("Help.Description") public void help(BukkitCommandActor actor, CommandHelp helpEntries, @Default("1") int page) { + BaseCommand.help(new PaperCMDSource(actor), helpEntries, page); } - @Subcommand({"backup", "archive"}) + @Subcommand({ "backup", "archive" }) @Usage("Admin.Backup.Arguments") @Description("Admin.Backup.Description") @CommandPermission("tne.admin.backup") public void backup(BukkitCommandActor sender) { + net.tnemc.core.command.AdminCommand.onBackup(new PaperCMDSource(sender)); } - @Subcommand({"create", "add", "new", "make", "+"}) + @Subcommand({ "create", "add", "new", "make", "+" }) @Usage("Admin.Create.Arguments") @Description("Admin.Create.Description") @CommandPermission("tne.admin.create") public void create(BukkitCommandActor sender, String name) { + net.tnemc.core.command.AdminCommand.onCreate(new PaperCMDSource(sender), name); } - @Subcommand({"debug"}) + @Subcommand({ "debug" }) @Usage("Admin.Debug.Arguments") @Description("Admin.Debug.Description") @CommandPermission("tne.admin.debug") public void debug(BukkitCommandActor sender, DebugLevel level) { + net.tnemc.core.command.AdminCommand.onDebug(new PaperCMDSource(sender), level); } - @Subcommand({"delete", "destroy", "del", "remove", "-"}) + @Subcommand({ "delete", "destroy", "del", "remove", "-" }) @Usage("Admin.Delete.Arguments") @Description("Admin.Delete.Description") @CommandPermission("tne.admin.delete") public void delete(BukkitCommandActor sender, String name) { + net.tnemc.core.command.AdminCommand.onDelete(new PaperCMDSource(sender), name); } - @Subcommand({"extract"}) + @Subcommand({ "extract" }) @Usage("Admin.Extract.Arguments") @Description("Admin.Extract.Description") @CommandPermission("tne.admin.extract") public void extract(BukkitCommandActor sender) { + net.tnemc.core.command.AdminCommand.onExtract(new PaperCMDSource(sender)); } - @Subcommand({"purge"}) + @Subcommand({ "purge" }) @Usage("Admin.Purge.Arguments") @Description("Admin.Purge.Description") @CommandPermission("tne.admin.purge") public void purge(BukkitCommandActor sender) { + net.tnemc.core.command.AdminCommand.onPurge(new PaperCMDSource(sender)); } - @Subcommand({"reload"}) + @Subcommand({ "reload" }) @Usage("Admin.Reload.Arguments") @Description("Admin.Reload.Description") @CommandPermission("tne.admin.reload") public void reload(BukkitCommandActor sender, @Default("all") String type) { + net.tnemc.core.command.AdminCommand.onReload(new PaperCMDSource(sender), type); } - @Subcommand({"reset", "nuke"}) + @Subcommand({ "reset", "nuke" }) @Usage("Admin.Reset.Arguments") @Description("Admin.Reset.Description") @CommandPermission("tne.admin.reset") public void reset(BukkitCommandActor sender) { + net.tnemc.core.command.AdminCommand.onReset(new PaperCMDSource(sender)); } - @Subcommand({"restore"}) + @Subcommand({ "restore" }) @Usage("Admin.Restore.Arguments") @Description("Admin.Restore.Description") @CommandPermission("tne.admin.restore") public void restore(BukkitCommandActor sender, @Default("0") int extraction) { + net.tnemc.core.command.AdminCommand.onRestore(new PaperCMDSource(sender), extraction); } - @Subcommand({"old"}) + @Subcommand({ "old" }) @Usage("Admin.Restore.Arguments") @Description("Admin.Restore.Description") @CommandPermission("tne.admin.old") public void old(BukkitCommandActor sender, @Default("0") int extraction) { + PluginCore.server().scheduler().createDelayedTask(()->restoreOld(extraction), new ChoreTime(0), ChoreExecution.SECONDARY); new PaperCMDSource(sender).message(new MessageData("Messages.Admin.Restoration")); } - @Subcommand({"save"}) + @Subcommand({ "save" }) @Usage("Admin.Save.Arguments") @Description("Admin.Save.Description") @CommandPermission("tne.admin.save") public void save(BukkitCommandActor sender) { + net.tnemc.core.command.AdminCommand.onSave(new PaperCMDSource(sender)); } - @Subcommand({"status"}) + @Subcommand({ "status" }) @Usage("Admin.Status.Arguments") @Description("Admin.Status.Description") @CommandPermission("tne.admin.status") public void status(BukkitCommandActor sender, Account account, @Default("normal") AccountStatus status) { + net.tnemc.core.command.AdminCommand.onStatus(new PaperCMDSource(sender), account, status); } - @Subcommand({"version", "ver", "build"}) + @Subcommand({ "version", "ver", "build" }) @Usage("Admin.Version.Arguments") @Description("Admin.Version.Description") @CommandPermission("tne.admin.version") public void version(BukkitCommandActor sender) { + net.tnemc.core.command.AdminCommand.onVersion(new PaperCMDSource(sender)); } public static boolean restoreOld(@Nullable final Integer extraction) { + final File file = new File(PluginCore.directory(), "extracted.yml"); if(!file.exists()) { @@ -240,15 +256,15 @@ public static boolean restoreOld(@Nullable final Integer extraction) { final String currency = (String)currencyNameObj; if(!recode) { - final String finalCurrency = (currency.equalsIgnoreCase("default")) ? TNECore.eco().currency().getDefaultCurrency().getIdentifier() : currency; + final String finalCurrency = (currency.equalsIgnoreCase("default"))? TNECore.eco().currency().getDefaultCurrency().getIdentifier() : currency; final Optional cur = TNECore.eco().currency().findCurrency(finalCurrency); - final Currency currencyObj = cur.orElseGet(() -> TNECore.eco().currency().getDefaultCurrency(TNECore.eco().region().resolve(region))); + final Currency currencyObj = cur.orElseGet(()->TNECore.eco().currency().getDefaultCurrency(TNECore.eco().region().resolve(region))); final BigDecimal amount = new BigDecimal(extracted.getString("Accounts." + name + ".Balances." + region + "." + currency)); response.getAccount().get().setHoldings(new HoldingsEntry(TNECore.eco().region().resolve(region), currencyObj.getUid(), - amount, EconomyManager.NORMAL), TNECore.eco().getFor(currencyObj.type()).get(0).identifier()); + amount, EconomyManager.NORMAL), TNECore.eco().getFor(currencyObj.type()).get(0).identifier()); } else { final Set types = extracted.getSection("Accounts." + name + ".Balances." + region + "." + currency).getKeys(); @@ -256,23 +272,23 @@ public static boolean restoreOld(@Nullable final Integer extraction) { final String type = (String)typeObj; final BigDecimal amount = new BigDecimal(extracted.getString("Accounts." + name - + ".Balances." + region - + "." + currency + "." - + type)); + + ".Balances." + region + + "." + currency + "." + + type)); response.getAccount().get().setHoldings(new HoldingsEntry(region, UUID.fromString(currency), - amount, Identifier.fromID(type))); + amount, Identifier.fromID(type))); } } number++; try { final boolean message = (number % frequency == 0); - if (message) { + if(message) { final int progress = (number * 100) / accounts.size(); PluginCore.log().inform("Restoration Progress: " + progress, DebugLevel.OFF); } - } catch(Exception ignore) {} + } catch(Exception ignore) { } } } } @@ -283,6 +299,7 @@ public static boolean restoreOld(@Nullable final Integer extraction) { } protected static UUID get(final String name) { + for(OfflinePlayer player : Bukkit.getServer().getOfflinePlayers()) { if(player.getName() == null) continue; if(player.getName().equalsIgnoreCase(name)) { diff --git a/PaperCore/src/net/tnemc/paper/command/ModuleCommand.java b/PaperCore/src/net/tnemc/paper/command/ModuleCommand.java index 9108f978..650d5012 100644 --- a/PaperCore/src/net/tnemc/paper/command/ModuleCommand.java +++ b/PaperCore/src/net/tnemc/paper/command/ModuleCommand.java @@ -37,54 +37,60 @@ * @author creatorfromhell * @since 0.1.2.0 */ -@Command({"module", "mod"}) +@Command({ "module", "mod" }) public class ModuleCommand { - @Subcommand({"help", "?"}) + @Subcommand({ "help", "?" }) @Usage("Help.Arguments") @Description("Help.Description") public void help(BukkitCommandActor actor, CommandHelp helpEntries, @Default("1") int page) { + BaseCommand.help(new PaperCMDSource(actor), helpEntries, page); } - @Subcommand({"avail", "available"}) + @Subcommand({ "avail", "available" }) @Usage("Module.Available.Arguments") @Description("Module.Available.Description") @CommandPermission("tne.module.available") public void onAvailable(BukkitCommandActor sender, @Default(TNECore.coreURL) String url) { + net.tnemc.core.command.ModuleCommand.onAvailable(new PaperCMDSource(sender), url); } - @Subcommand({"download", "dl"}) + @Subcommand({ "download", "dl" }) @Usage("Module.Download.Arguments") @Description("Module.Download.Description") @CommandPermission("tne.module.download") public void onDownload(BukkitCommandActor sender, String moduleName, @Default(TNECore.coreURL) String url) { + net.tnemc.core.command.ModuleCommand.onDownload(new PaperCMDSource(sender), moduleName, url); } - @Subcommand({"info", "i"}) + @Subcommand({ "info", "i" }) @Usage("Module.Info.Arguments") @Description("Module.Info.Description") @CommandPermission("tne.module.info") public void onInfo(BukkitCommandActor sender, String moduleName) { + net.tnemc.core.command.ModuleCommand.onInfo(new PaperCMDSource(sender), moduleName); } - @Subcommand({"list", "l"}) + @Subcommand({ "list", "l" }) @Usage("Module.List.Arguments") - @DefaultFor({"module", "mod"}) + @DefaultFor({ "module", "mod" }) @Description("Module.List.Description") @CommandPermission("tne.list.available") public void onList(BukkitCommandActor sender) { + net.tnemc.core.command.ModuleCommand.onList(new PaperCMDSource(sender)); } - @Subcommand({"load"}) + @Subcommand({ "load" }) @Usage("Module.Load.Arguments") @Description("Module.Load.Description") @CommandPermission("tne.module.load") public void onLoad(BukkitCommandActor sender, String moduleName) { + net.tnemc.core.command.ModuleCommand.onLoad(new PaperCMDSource(sender), moduleName); } } \ No newline at end of file diff --git a/PaperCore/src/net/tnemc/paper/command/MoneyCommand.java b/PaperCore/src/net/tnemc/paper/command/MoneyCommand.java index 3d861e0c..11890344 100644 --- a/PaperCore/src/net/tnemc/paper/command/MoneyCommand.java +++ b/PaperCore/src/net/tnemc/paper/command/MoneyCommand.java @@ -42,144 +42,161 @@ * @author creatorfromhell * @since 0.1.2.0 */ -@Command({"money", "eco", "balo", "balance", "bal", "balanceother", "mybal"}) +@Command({ "money", "eco", "balo", "balance", "bal", "balanceother", "mybal" }) public class MoneyCommand { - @DefaultFor({"mybal"}) - @Subcommand({"balmenu", "menu", "mybal"}) + @DefaultFor({ "mybal" }) + @Subcommand({ "balmenu", "menu", "mybal" }) @Usage("Money.MyBal.Arguments") @Description("Money.MyBal.Description") @CommandPermission("tne.money.mybal") public void onMyBal(BukkitCommandActor sender) { + net.tnemc.core.command.MoneyCommand.onMyBal(new PaperCMDSource(sender)); } - @Subcommand({"help", "?"}) + @Subcommand({ "help", "?" }) @Usage("Help.Arguments") @Description("Help.Description") public void help(BukkitCommandActor actor, CommandHelp helpEntries, @Default("1") int page) { + BaseCommand.help(new PaperCMDSource(actor), helpEntries, page); } - @DefaultFor({"bal", "money", "eco", "balance"}) - @Subcommand({"balance", "bal", "val"}) + @DefaultFor({ "bal", "money", "eco", "balance" }) + @Subcommand({ "balance", "bal", "val" }) @Usage("Money.Balance.Arguments") @Description("Money.Balance.Description") @CommandPermission("tne.money.balance") public void onBalance(BukkitCommandActor sender, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onBalance(new PaperCMDSource(sender), currency, region); } - @Subcommand({"convert"}) + @Subcommand({ "convert" }) @Usage("Money.Convert.Arguments") @Description("Money.Convert.Description") @CommandPermission("tne.money.convert") public void onConvert(BukkitCommandActor sender, @Named("amount") PercentBigDecimal amount, @Named("currency") Currency currency, @Named("currency") Currency from) { + net.tnemc.core.command.MoneyCommand.onConvert(new PaperCMDSource(sender), amount, currency, from); } - @Subcommand({"deposit"}) + @Subcommand({ "deposit" }) @Usage("Money.Deposit.Arguments") @Description("Money.Deposit.Description") @CommandPermission("tne.money.deposit") public void onDeposit(BukkitCommandActor sender, @Named("amount") PercentBigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onDeposit(new PaperCMDSource(sender), amount, currency, region); } - @Subcommand({"give", "+", "add"}) + @Subcommand({ "give", "+", "add" }) @Usage("Money.Give.Arguments") @Description("Money.Give.Description") @CommandPermission("tne.money.give") public void onGive(BukkitCommandActor sender, Account player, @Named("amount") PercentBigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onGive(new PaperCMDSource(sender), player, amount, region, currency); } - @Subcommand({"givenote", "+note", "addnote"}) + @Subcommand({ "givenote", "+note", "addnote" }) @Usage("Money.GiveNote.Arguments") @Description("Money.GiveNote.Description") @CommandPermission("tne.money.givenote") public void onGiveNote(BukkitCommandActor sender, Account player, @Named("amount") BigDecimal amount, @Default("") @Named("currency") Currency currency) { + net.tnemc.core.command.MoneyCommand.onGiveNote(new PaperCMDSource(sender), player, amount, currency); } - @Subcommand({"note", "n"}) + @Subcommand({ "note", "n" }) @Usage("Money.Note.Arguments") @Description("Money.Note.Description") @CommandPermission("tne.money.note") public void onNote(BukkitCommandActor sender, @Named("amount") PercentBigDecimal amount, @Default("") @Named("currency") Currency currency) { + net.tnemc.core.command.MoneyCommand.onNote(new PaperCMDSource(sender), amount, currency); } - @Subcommand({"other", "check", "balo"}) - @DefaultFor({"balo", "balanceother"}) + @Subcommand({ "other", "check", "balo" }) + @DefaultFor({ "balo", "balanceother" }) @Usage("Money.Other.Arguments") @Description("Money.Other.Description") @CommandPermission("tne.money.other") public void onOther(BukkitCommandActor sender, Account player, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onOther(new PaperCMDSource(sender), player, region, currency); } - @Subcommand({"pay", "send", "transfer"}) + @Subcommand({ "pay", "send", "transfer" }) @Usage("Money.Pay.Arguments") @Description("Money.Pay.Description") @CommandPermission("tne.money.pay") public void onPay(BukkitCommandActor sender, Account player, @Named("amount") PercentBigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("") String from) { + net.tnemc.core.command.MoneyCommand.onPay(new PaperCMDSource(sender), player, amount, currency, from); } - @Subcommand({"request"}) + @Subcommand({ "request" }) @Usage("Money.Request.Arguments") @Description("Money.Request.Description") @CommandPermission("tne.money.Request") public void onRequest(BukkitCommandActor sender, Account player, @Named("amount") BigDecimal amount, @Default("") @Named("currency") Currency currency) { + net.tnemc.core.command.MoneyCommand.onRequest(new PaperCMDSource(sender), player, amount, currency); } - @Subcommand({"set", "eq", "="}) + @Subcommand({ "set", "eq", "=" }) @Usage("Money.Set.Arguments") @Description("Money.Set.Description") @CommandPermission("tne.money.set") public void onSet(BukkitCommandActor sender, Account player, @Named("amount") BigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onSet(new PaperCMDSource(sender), player, amount, region, currency); } - @Subcommand({"setall"}) + @Subcommand({ "setall" }) @Usage("Money.SetAll.Arguments") @Description("Money.SetAll.Description") @CommandPermission("tne.money.setall") public void onSetAll(BukkitCommandActor sender, @Named("amount") BigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onSetAll(new PaperCMDSource(sender), amount, region, currency); } - @Subcommand({"switch", "swap"}) + @Subcommand({ "switch", "swap" }) @Usage("Money.Switch.Arguments") @Description("Money.Switch.Description") @CommandPermission("tne.money.switch") public void onSwitch(BukkitCommandActor sender, @Named("switched") Account account) { + net.tnemc.core.command.MoneyCommand.onSwitch(new PaperCMDSource(sender), account); } - @Subcommand({"take", "minus", "remove", "-"}) + @Subcommand({ "take", "minus", "remove", "-" }) @Usage("Money.Take.Arguments") @Description("Money.Take.Description") @CommandPermission("tne.money.take") public void onTake(BukkitCommandActor sender, Account player, @Named("amount") PercentBigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onTake(new PaperCMDSource(sender), player, amount, region, currency); } - @Subcommand({"top", "baltop"}) + @Subcommand({ "top", "baltop" }) @Usage("Money.Top.Arguments") @Description("Money.Top.Description") @CommandPermission("tne.money.top") public void onTop(BukkitCommandActor sender, @Default("1") Integer page, @Default("") @Named("currency") Currency currency, @Default("false") Boolean refresh) { + net.tnemc.core.command.MoneyCommand.onTop(new PaperCMDSource(sender), page, currency, refresh); } - @Subcommand({"withdraw"}) + @Subcommand({ "withdraw" }) @Usage("Money.Withdraw.Arguments") @Description("Money.Withdraw.Description") @CommandPermission("tne.money.withdraw") public void onWithdraw(BukkitCommandActor sender, @Named("amount") PercentBigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onWithdraw(new PaperCMDSource(sender), amount, currency, region); } } \ No newline at end of file diff --git a/PaperCore/src/net/tnemc/paper/command/ShortCommands.java b/PaperCore/src/net/tnemc/paper/command/ShortCommands.java index 474bb8b7..3939f6e3 100644 --- a/PaperCore/src/net/tnemc/paper/command/ShortCommands.java +++ b/PaperCore/src/net/tnemc/paper/command/ShortCommands.java @@ -40,59 +40,66 @@ */ public class ShortCommands { - @Command({"givemoney", "givebal"}) + @Command({ "givemoney", "givebal" }) @Usage("Money.Give.Arguments") @Description("Money.Give.Description") @CommandPermission("tne.money.give") public void onGive(BukkitCommandActor sender, @Named("account") Account player, @Named("amount") PercentBigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onGive(new PaperCMDSource(sender), player, amount, region, currency); } - @Command({"givenote", "+note", "addnote"}) + @Command({ "givenote", "+note", "addnote" }) @Usage("Money.GiveNote.Arguments") @Description("Money.GiveNote.Description") @CommandPermission("tne.money.givenote") public void onGiveNote(BukkitCommandActor sender, Account player, @Named("amount") BigDecimal amount, @Default("") @Named("currency") Currency currency) { + net.tnemc.core.command.MoneyCommand.onGiveNote(new PaperCMDSource(sender), player, amount, currency); } - @Command({"pay"}) + @Command({ "pay" }) @Usage("Money.Pay.Arguments") @Description("Money.Pay.Description") @CommandPermission("tne.money.pay") public void onPay(BukkitCommandActor sender, @Named("account") Account player, @Named("amount") PercentBigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("") String from) { + net.tnemc.core.command.MoneyCommand.onPay(new PaperCMDSource(sender), player, amount, currency, from); } - @Command({"setmoney", "setbal"}) + @Command({ "setmoney", "setbal" }) @Usage("Money.Set.Arguments") @Description("Money.Set.Description") @CommandPermission("tne.money.set") public void onSet(BukkitCommandActor sender, @Named("account") Account player, @Named("amount") BigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onSet(new PaperCMDSource(sender), player, amount, region, currency); } - @Command({"takemoney", "takebal"}) + @Command({ "takemoney", "takebal" }) @Usage("Money.Take.Arguments") @Description("Money.Take.Description") @CommandPermission("tne.money.take") public void onTake(BukkitCommandActor sender, @Named("account") Account player, @Named("amount") PercentBigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onTake(new PaperCMDSource(sender), player, amount, region, currency); } - @Command({"baltop"}) + @Command({ "baltop" }) @Usage("Money.Top.Arguments") @Description("Money.Top.Description") @CommandPermission("tne.money.top") public void onTop(BukkitCommandActor sender, @Default("1") @Named("page") Integer page, @Default("") @Named("currency") Currency currency, @Default("false") Boolean refresh) { + net.tnemc.core.command.MoneyCommand.onTop(new PaperCMDSource(sender), page, currency, refresh); } - @Command({"transactions"}) + @Command({ "transactions" }) @Usage("Transaction.History.Arguments") @Description("Transaction.History.Description") @CommandPermission("tne.transaction.history") public void history(BukkitCommandActor sender, @Default("1") int page, @Default("world-113") @Named("region") String region, @Default("SELF_ACCOUNT") Account account) { + net.tnemc.core.command.TransactionCommand.history(new PaperCMDSource(sender), page, region, account); } } \ No newline at end of file diff --git a/PaperCore/src/net/tnemc/paper/command/TransactionCommand.java b/PaperCore/src/net/tnemc/paper/command/TransactionCommand.java index 9060bbe5..99776d54 100644 --- a/PaperCore/src/net/tnemc/paper/command/TransactionCommand.java +++ b/PaperCore/src/net/tnemc/paper/command/TransactionCommand.java @@ -17,6 +17,7 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . */ + import net.tnemc.core.account.Account; import net.tnemc.core.command.BaseCommand; import net.tnemc.plugincore.paper.impl.PaperCMDSource; @@ -39,46 +40,51 @@ * @author creatorfromhell * @since 0.1.2.0 */ -@Command({"transaction", "trans", "receipt"}) +@Command({ "transaction", "trans", "receipt" }) public class TransactionCommand { - @Subcommand({"help", "?"}) - @DefaultFor({"transaction", "trans", "receipt"}) + @Subcommand({ "help", "?" }) + @DefaultFor({ "transaction", "trans", "receipt" }) @Usage("Help.Arguments") @Description("Help.Description") public void help(BukkitCommandActor actor, CommandHelp helpEntries, @Default("1") int page) { + BaseCommand.help(new PaperCMDSource(actor), helpEntries, page); } - @Subcommand({"away", "gone", "afk", "afg"}) + @Subcommand({ "away", "gone", "afk", "afg" }) @Usage("Transaction.Away.Arguments") @Description("Transaction.Away.Description") @CommandPermission("tne.transaction.away") public void away(BukkitCommandActor sender, @Default("1") int page) { + net.tnemc.core.command.TransactionCommand.away(new PaperCMDSource(sender), page); } - @Subcommand({"history", "list", "hist", "archive"}) + @Subcommand({ "history", "list", "hist", "archive" }) @Usage("Transaction.History.Arguments") @Description("Transaction.History.Description") @CommandPermission("tne.transaction.history") public void history(BukkitCommandActor sender, @Default("1") int page, @Default("world-113") @Named("region") String region, @Default("SELF_ACCOUNT") Account account) { + net.tnemc.core.command.TransactionCommand.history(new PaperCMDSource(sender), page, region, account); } - @Subcommand({"info", "i", "about", "brief"}) + @Subcommand({ "info", "i", "about", "brief" }) @Usage("Transaction.Info.Arguments") @Description("Transaction.Info.Description") @CommandPermission("tne.info.history") public void info(BukkitCommandActor sender, UUID uuid) { + net.tnemc.core.command.TransactionCommand.info(new PaperCMDSource(sender), uuid); } - @Subcommand({"void", "retract", "undo"}) + @Subcommand({ "void", "retract", "undo" }) @Usage("Transaction.Void.Arguments") @Description("Transaction.Void.Description") @CommandPermission("tne.void.history") public void voidT(BukkitCommandActor sender, Account account, UUID uuid) { + net.tnemc.core.command.TransactionCommand.voidT(new PaperCMDSource(sender), account, uuid); } } diff --git a/PaperCore/src/net/tnemc/paper/hook/economy/TNEVault.java b/PaperCore/src/net/tnemc/paper/hook/economy/TNEVault.java index e4e6eaf8..8de16460 100644 --- a/PaperCore/src/net/tnemc/paper/hook/economy/TNEVault.java +++ b/PaperCore/src/net/tnemc/paper/hook/economy/TNEVault.java @@ -50,46 +50,55 @@ public class TNEVault implements Economy { /** * Checks if economy method is enabled. + * * @return Success or Failure */ public boolean isEnabled() { + return true; } /** * Gets name of economy method + * * @return Name of Economy Method */ public String getName() { + return "TheNewEconomy"; } /** * Returns true if the given implementation supports banks. + * * @return true if the implementation supports banks */ public boolean hasBankSupport() { + return false; } /** - * Some economy plugins round off after a certain number of digits. - * This function returns the number of digits the plugin keeps - * or -1 if no rounding occurs. + * Some economy plugins round off after a certain number of digits. This function returns the + * number of digits the plugin keeps or -1 if no rounding occurs. + * * @return number of digits after the decimal point kept */ public int fractionalDigits() { + return TNECore.eco().currency().getDefaultCurrency().getDecimalPlaces(); } /** - * Format amount into a human-readable String This provides translation into - * economy specific formatting to improve consistency between plugins. + * Format amount into a human-readable String This provides translation into economy specific + * formatting to improve consistency between plugins. * * @param amount to format + * * @return Human-readable string describing amount */ public String format(double amount) { + return CurrencyFormatter.format(null, new HoldingsEntry(TNECore.eco().region().defaultRegion(), TNECore.eco().currency().getDefaultCurrency().getUid(), BigDecimal.valueOf(amount), @@ -98,44 +107,48 @@ public String format(double amount) { } /** - * Returns the name of the currency in plural form. - * If the economy being used does not support currency names then an empty string will be returned. + * Returns the name of the currency in plural form. If the economy being used does not support + * currency names then an empty string will be returned. * * @return name of the currency (plural) */ public String currencyNamePlural() { + return TNECore.eco().currency().getDefaultCurrency().getDisplayPlural(); } /** - * Returns the name of the currency in singular form. - * If the economy being used does not support currency names then an empty string will be returned. + * Returns the name of the currency in singular form. If the economy being used does not support + * currency names then an empty string will be returned. * * @return name of the currency (singular) */ public String currencyNameSingular() { + return TNECore.eco().currency().getDefaultCurrency().getDisplay(); } /** - * * @deprecated As of VaultAPI 1.4 use {@link #hasAccount(OfflinePlayer)} instead. */ @Deprecated public boolean hasAccount(String name) { + return hasAccount(name, "ahoy matey"); } /** - * Checks if this player has an account on the server yet - * This will always return true if the player has joined the server at least once - * as all major economy plugins auto-generate a player account when the player joins the server + * Checks if this player has an account on the server yet This will always return true if the + * player has joined the server at least once as all major economy plugins auto-generate a player + * account when the player joins the server * * @param player to check + * * @return if the player has an account */ public boolean hasAccount(OfflinePlayer player) { + return hasAccount(player, "woah"); } @@ -144,19 +157,22 @@ public boolean hasAccount(OfflinePlayer player) { */ @Deprecated public boolean hasAccount(String name, String world) { + return TNECore.eco().account().findAccount(name).isPresent(); } /** - * Checks if this player has an account on the server yet on the given world - * This will always return true if the player has joined the server at least once - * as all major economy plugins auto-generate a player account when the player joins the server + * Checks if this player has an account on the server yet on the given world This will always + * return true if the player has joined the server at least once as all major economy plugins + * auto-generate a player account when the player joins the server * * @param player to check in the world - * @param world world-specific account + * @param world world-specific account + * * @return if the player has an account */ public boolean hasAccount(OfflinePlayer player, String world) { + return hasAccount(player.getUniqueId().toString(), world); } @@ -165,6 +181,7 @@ public boolean hasAccount(OfflinePlayer player, String world) { */ @Deprecated public double getBalance(String name) { + return getBalance(name, TNECore.eco().region().defaultRegion()); } @@ -172,9 +189,11 @@ public double getBalance(String name) { * Gets balance of a player * * @param player of the player + * * @return Amount currently held in players account */ public double getBalance(OfflinePlayer player) { + return getBalance(player.getUniqueId().toString(), TNECore.eco().region().defaultRegion()); } @@ -183,6 +202,7 @@ public double getBalance(OfflinePlayer player) { */ @Deprecated public double getBalance(String name, String world) { + PluginCore.log().debug("Vault Balance call. Name: " + name + " World: " + world, DebugLevel.STANDARD); final Optional account = TNECore.eco().account().findAccount(name); @@ -191,7 +211,7 @@ public double getBalance(String name, String world) { PluginCore.log().debug("==== Vault balance call with color code! ====", DebugLevel.DEVELOPER); final StackTraceElement[] elements = Thread.currentThread().getStackTrace(); - for (int i = 1; i < elements.length; i++) { + for(int i = 1; i < elements.length; i++) { final StackTraceElement s = elements[i]; PluginCore.log().debug("\tat " + s.getClassName() + "." + s.getMethodName() + "(" + s.getFileName() + ":" + s.getLineNumber() + ")", DebugLevel.DEVELOPER); } @@ -210,13 +230,16 @@ public double getBalance(String name, String world) { } /** - * Gets balance of a player on the specified world. - * IMPLEMENTATION SPECIFIC - if an economy plugin does not support this the global balance will be returned. + * Gets balance of a player on the specified world. IMPLEMENTATION SPECIFIC - if an economy plugin + * does not support this the global balance will be returned. + * * @param player to check - * @param world name of the world + * @param world name of the world + * * @return Amount currently held in players account */ public double getBalance(OfflinePlayer player, String world) { + final Optional account = TNECore.eco().account().findAccount(player.getUniqueId().toString()); if(player.getName() != null && account.isEmpty()) { return getBalance(player.getName(), world); @@ -229,6 +252,7 @@ public double getBalance(OfflinePlayer player, String world) { */ @Deprecated public boolean has(String name, double amount) { + return has(name, TNECore.eco().region().defaultRegion(), amount); } @@ -237,9 +261,11 @@ public boolean has(String name, double amount) { * * @param player to check * @param amount to check for + * * @return True if player has amount, False else wise */ public boolean has(OfflinePlayer player, double amount) { + final Optional account = TNECore.eco().account().findAccount(player.getUniqueId().toString()); if(player.getName() != null && account.isEmpty()) { return has(player.getName(), TNECore.eco().region().defaultRegion(), amount); @@ -252,21 +278,25 @@ public boolean has(OfflinePlayer player, double amount) { */ @Deprecated public boolean has(String name, String world, double amount) { + final Optional account = TNECore.eco().account().findAccount(name); return account.filter(value->value.getHoldingsTotal(world, TNECore.eco().currency().getDefaultCurrency(world).getUid()) - .compareTo(BigDecimal.valueOf(amount)) >= 0).isPresent(); + .compareTo(BigDecimal.valueOf(amount)) >= 0).isPresent(); } /** * Checks if the player account has the amount in a given world - DO NOT USE NEGATIVE AMOUNTS - * IMPLEMENTATION SPECIFIC - if an economy plugin does not support this the global balance will be returned. + * IMPLEMENTATION SPECIFIC - if an economy plugin does not support this the global balance will be + * returned. * * @param player to check - * @param world to check with + * @param world to check with * @param amount to check for + * * @return True if player has amount, False else wise */ public boolean has(OfflinePlayer player, String world, double amount) { + final Optional account = TNECore.eco().account().findAccount(player.getUniqueId().toString()); if(player.getName() != null && account.isEmpty()) { return has(player.getName(), world, amount); @@ -279,6 +309,7 @@ public boolean has(OfflinePlayer player, String world, double amount) { */ @Deprecated public EconomyResponse withdrawPlayer(String name, double amount) { + return withdrawPlayer(name, TNECore.eco().region().defaultRegion(), amount); } @@ -287,9 +318,11 @@ public EconomyResponse withdrawPlayer(String name, double amount) { * * @param player to withdraw from * @param amount Amount to withdraw + * * @return Detailed response of transaction */ public EconomyResponse withdrawPlayer(OfflinePlayer player, double amount) { + final EconomyResponse response = withdrawPlayer(player.getUniqueId().toString(), TNECore.eco().region().defaultRegion(), amount); PluginCore.log().debug("Player ID: " + player.getUniqueId()); @@ -303,7 +336,8 @@ public EconomyResponse withdrawPlayer(OfflinePlayer player, double amount) { } /** - * @deprecated As of VaultAPI 1.4 use {@link #withdrawPlayer(OfflinePlayer, String, double)} instead. + * @deprecated As of VaultAPI 1.4 use {@link #withdrawPlayer(OfflinePlayer, String, double)} + * instead. */ @Deprecated public EconomyResponse withdrawPlayer(String name, String world, double amount) { @@ -312,7 +346,7 @@ public EconomyResponse withdrawPlayer(String name, String world, double amount) if(account.isEmpty()) { return new EconomyResponse(0.0, 0.0, - EconomyResponse.ResponseType.FAILURE, "Unable to locate associated account."); + EconomyResponse.ResponseType.FAILURE, "Unable to locate associated account."); } final HoldingsModifier modifier = new HoldingsModifier(world, @@ -320,9 +354,9 @@ public EconomyResponse withdrawPlayer(String name, String world, double amount) BigDecimal.valueOf(amount)); final Transaction transaction = new Transaction("take") - .to(account.get(), modifier.counter()) - .processor(EconomyManager.baseProcessor()) - .source(new PluginSource("Vault")); + .to(account.get(), modifier.counter()) + .processor(EconomyManager.baseProcessor()) + .source(new PluginSource("Vault")); try { TransactionResult result = transaction.process(); @@ -337,14 +371,17 @@ public EconomyResponse withdrawPlayer(String name, String world, double amount) } /** - * Withdraw an amount from a player on a given world - DO NOT USE NEGATIVE AMOUNTS - * IMPLEMENTATION SPECIFIC - if an economy plugin does not support this the global balance will be returned. + * Withdraw an amount from a player on a given world - DO NOT USE NEGATIVE AMOUNTS IMPLEMENTATION + * SPECIFIC - if an economy plugin does not support this the global balance will be returned. + * * @param player to withdraw from - * @param world - name of the world + * @param world - name of the world * @param amount Amount to withdraw + * * @return Detailed response of transaction */ public EconomyResponse withdrawPlayer(OfflinePlayer player, String world, double amount) { + final EconomyResponse response = withdrawPlayer(player.getUniqueId().toString(), world, amount); if(response.transactionSuccess() || player.getName() == null) { return response; @@ -357,6 +394,7 @@ public EconomyResponse withdrawPlayer(OfflinePlayer player, String world, double */ @Deprecated public EconomyResponse depositPlayer(String name, double amount) { + return depositPlayer(name, TNECore.eco().region().defaultRegion(), amount); } @@ -365,9 +403,11 @@ public EconomyResponse depositPlayer(String name, double amount) { * * @param player to deposit to * @param amount Amount to deposit + * * @return Detailed response of transaction */ public EconomyResponse depositPlayer(OfflinePlayer player, double amount) { + final EconomyResponse response = depositPlayer(player.getUniqueId().toString(), TNECore.eco().region().defaultRegion(), amount); if(response.transactionSuccess() || player.getName() == null) { return response; @@ -376,7 +416,8 @@ public EconomyResponse depositPlayer(OfflinePlayer player, double amount) { } /** - * @deprecated As of VaultAPI 1.4 use {@link #depositPlayer(OfflinePlayer, String, double)} instead. + * @deprecated As of VaultAPI 1.4 use {@link #depositPlayer(OfflinePlayer, String, double)} + * instead. */ @Deprecated public EconomyResponse depositPlayer(String name, String world, double amount) { @@ -385,7 +426,7 @@ public EconomyResponse depositPlayer(String name, String world, double amount) { if(account.isEmpty()) { return new EconomyResponse(0.0, 0.0, - EconomyResponse.ResponseType.FAILURE, "Unable to locate associated account."); + EconomyResponse.ResponseType.FAILURE, "Unable to locate associated account."); } final HoldingsModifier modifier = new HoldingsModifier(world, @@ -394,9 +435,9 @@ public EconomyResponse depositPlayer(String name, String world, double amount) { final Transaction transaction = new Transaction("give") - .to(account.get(), modifier) - .processor(EconomyManager.baseProcessor()) - .source(new PluginSource("Vault")); + .to(account.get(), modifier) + .processor(EconomyManager.baseProcessor()) + .source(new PluginSource("Vault")); try { TransactionResult result = transaction.process(); @@ -411,15 +452,17 @@ public EconomyResponse depositPlayer(String name, String world, double amount) { } /** - * Deposit an amount to a player - DO NOT USE NEGATIVE AMOUNTS - * IMPLEMENTATION SPECIFIC - if an economy plugin does not support this the global balance will be returned. + * Deposit an amount to a player - DO NOT USE NEGATIVE AMOUNTS IMPLEMENTATION SPECIFIC - if an + * economy plugin does not support this the global balance will be returned. * * @param player to deposit to - * @param world name of the world + * @param world name of the world * @param amount Amount to deposit + * * @return Detailed response of transaction */ public EconomyResponse depositPlayer(OfflinePlayer player, String world, double amount) { + final EconomyResponse response = depositPlayer(player.getUniqueId().toString(), world, amount); if(response.transactionSuccess() || player.getName() == null) { return response; @@ -432,67 +475,83 @@ public EconomyResponse depositPlayer(OfflinePlayer player, String world, double */ @Deprecated public EconomyResponse createBank(String name, String player) { + return new EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, ""); } /** * Creates a bank account with the specified name and the player as the owner - * @param name of account + * + * @param name of account * @param player the account should be linked to + * * @return EconomyResponse Object */ public EconomyResponse createBank(String name, OfflinePlayer player) { + return new EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, ""); } /** * Deletes a bank account with the specified name. + * * @param name of the back to delete + * * @return if the operation completed successfully */ public EconomyResponse deleteBank(String name) { + return new EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, ""); } /** * Returns the amount the bank has + * * @param name of the account + * * @return EconomyResponse Object */ public EconomyResponse bankBalance(String name) { + return new EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, ""); } /** * Returns true or false whether the bank has the amount specified - DO NOT USE NEGATIVE AMOUNTS * - * @param name of the account + * @param name of the account * @param amount to check for + * * @return EconomyResponse Object */ public EconomyResponse bankHas(String name, double amount) { + return new EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, ""); } /** * Withdraw an amount from a bank account - DO NOT USE NEGATIVE AMOUNTS * - * @param name of the account + * @param name of the account * @param amount to withdraw + * * @return EconomyResponse Object */ public EconomyResponse bankWithdraw(String name, double amount) { + return new EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, ""); } /** * Deposit an amount into a bank account - DO NOT USE NEGATIVE AMOUNTS * - * @param name of the account + * @param name of the account * @param amount to deposit + * * @return EconomyResponse Object */ public EconomyResponse bankDeposit(String name, double amount) { + return new EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, ""); } @@ -501,17 +560,20 @@ public EconomyResponse bankDeposit(String name, double amount) { */ @Deprecated public EconomyResponse isBankOwner(String name, String playerName) { + return new EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, ""); } /** * Check if a player is the owner of a bank account * - * @param name of the account + * @param name of the account * @param player to check for ownership + * * @return EconomyResponse Object */ public EconomyResponse isBankOwner(String name, OfflinePlayer player) { + return new EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, ""); } @@ -520,25 +582,30 @@ public EconomyResponse isBankOwner(String name, OfflinePlayer player) { */ @Deprecated public EconomyResponse isBankMember(String name, String playerName) { + return new EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, ""); } /** * Check if the player is a member of the bank account * - * @param name of the account + * @param name of the account * @param player to check membership + * * @return EconomyResponse Object */ public EconomyResponse isBankMember(String name, OfflinePlayer player) { + return new EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, ""); } /** * Gets the list of banks + * * @return the List of Banks */ public List getBanks() { + return new ArrayList<>(); } @@ -547,20 +614,25 @@ public List getBanks() { */ @Deprecated public boolean createPlayerAccount(String name) { + return createPlayerAccount(name, "this doesn't matter."); } /** * Attempts to create a player account for the given player + * * @param player OfflinePlayer + * * @return if the account creation was successful */ public boolean createPlayerAccount(OfflinePlayer player) { + return createPlayerAccount(player, "this doesn't matter."); } /** - * @deprecated As of VaultAPI 1.4 use {{@link #createPlayerAccount(OfflinePlayer, String)} instead. + * @deprecated As of VaultAPI 1.4 use {{@link #createPlayerAccount(OfflinePlayer, String)} + * instead. */ @Deprecated public boolean createPlayerAccount(String name, String world) { @@ -570,10 +642,12 @@ public boolean createPlayerAccount(String name, String world) { } /** - * Attempts to create a player account for the given player on the specified world - * IMPLEMENTATION SPECIFIC - if an economy plugin does not support this then false will always be returned. + * Attempts to create a player account for the given player on the specified world IMPLEMENTATION + * SPECIFIC - if an economy plugin does not support this then false will always be returned. + * * @param player OfflinePlayer - * @param world String name of the world + * @param world String name of the world + * * @return if the account creation was successful */ public boolean createPlayerAccount(OfflinePlayer player, String world) { @@ -590,7 +664,7 @@ public boolean createPlayerAccount(OfflinePlayer player, String world) { PluginCore.log().debug("==== Vault create call with color code! ====", DebugLevel.DEVELOPER); final StackTraceElement[] elements = Thread.currentThread().getStackTrace(); - for (int i = 1; i < elements.length; i++) { + for(int i = 1; i < elements.length; i++) { final StackTraceElement s = elements[i]; PluginCore.log().debug("\tat " + s.getClassName() + "." + s.getMethodName() + "(" + s.getFileName() + ":" + s.getLineNumber() + ")", DebugLevel.DEVELOPER); } @@ -602,6 +676,7 @@ public boolean createPlayerAccount(OfflinePlayer player, String world) { } private EconomyResponse.ResponseType fromResult(@Nullable TransactionResult result) { + if(result != null && result.isSuccessful()) { return EconomyResponse.ResponseType.SUCCESS; } diff --git a/PaperCore/src/net/tnemc/paper/hook/economy/TNEVaultUnlocked.java b/PaperCore/src/net/tnemc/paper/hook/economy/TNEVaultUnlocked.java index 0f7c7c98..baad6a7f 100644 --- a/PaperCore/src/net/tnemc/paper/hook/economy/TNEVaultUnlocked.java +++ b/PaperCore/src/net/tnemc/paper/hook/economy/TNEVaultUnlocked.java @@ -50,6 +50,7 @@ * @since 0.1.2.0 */ public class TNEVaultUnlocked implements Economy { + /** * Checks if economy plugin is enabled. * @@ -57,6 +58,7 @@ public class TNEVaultUnlocked implements Economy { */ @Override public boolean isEnabled() { + return true; } @@ -67,6 +69,7 @@ public boolean isEnabled() { */ @Override public String getName() { + return "TheNewEconomy"; } @@ -77,6 +80,7 @@ public String getName() { */ @Override public boolean hasBankSupport() { + return false; } @@ -87,6 +91,7 @@ public boolean hasBankSupport() { */ @Override public boolean hasMultiCurrencySupport() { + return true; } @@ -99,6 +104,7 @@ public boolean hasMultiCurrencySupport() { */ @Override public int fractionalDigits() { + return TNECore.eco().currency().getDefaultCurrency().getDecimalPlaces(); } @@ -112,10 +118,11 @@ public int fractionalDigits() { */ @Override public String format(BigDecimal amount) { + return CurrencyFormatter.format(null, new HoldingsEntry(TNECore.eco().region().defaultRegion(), - TNECore.eco().currency().getDefaultCurrency().getUid(), - amount, - EconomyManager.NORMAL + TNECore.eco().currency().getDefaultCurrency().getUid(), + amount, + EconomyManager.NORMAL )); } @@ -130,10 +137,11 @@ public String format(BigDecimal amount) { */ @Override public String format(BigDecimal amount, String currency) { + return CurrencyFormatter.format(null, new HoldingsEntry(TNECore.eco().region().defaultRegion(), - TNECore.eco().currency().getDefaultCurrency().getUid(), - amount, - EconomyManager.NORMAL + TNECore.eco().currency().getDefaultCurrency().getUid(), + amount, + EconomyManager.NORMAL )); } @@ -146,6 +154,7 @@ public String format(BigDecimal amount, String currency) { */ @Override public boolean hasCurrency(String currency) { + return TNECore.eco().currency().findCurrency(currency).isPresent(); } @@ -157,6 +166,7 @@ public boolean hasCurrency(String currency) { */ @Override public String defaultCurrency() { + return TNECore.eco().currency().getDefaultCurrency().getIdentifier(); } @@ -168,6 +178,7 @@ public String defaultCurrency() { */ @Override public String defaultCurrencyNamePlural() { + return TNECore.eco().currency().getDefaultCurrency().getDisplayPlural(); } @@ -179,6 +190,7 @@ public String defaultCurrencyNamePlural() { */ @Override public String defaultCurrencyNameSingular() { + return TNECore.eco().currency().getDefaultCurrency().getDisplay(); } @@ -191,6 +203,7 @@ public String defaultCurrencyNameSingular() { */ @Override public Collection currencies() { + return TNECore.eco().currency().getCurIDMap().keySet(); } @@ -204,6 +217,7 @@ public Collection currencies() { */ @Override public boolean createAccount(UUID uuid, String name) { + return TNECore.eco().account().createAccount(uuid.toString(), name).getResponse().success(); } @@ -219,6 +233,7 @@ public boolean createAccount(UUID uuid, String name) { */ @Override public boolean createAccount(UUID uuid, String name, String worldName) { + return createAccount(uuid, name); } @@ -232,6 +247,7 @@ public boolean createAccount(UUID uuid, String name, String worldName) { */ @Override public Map getUUIDNameMap() { + return Map.of(); } @@ -245,6 +261,7 @@ public Map getUUIDNameMap() { */ @Override public Optional getAccountName(UUID uuid) { + final Optional accountOpt = TNECore.eco().account().findAccount(uuid); return accountOpt.map(Account::getName); } @@ -258,6 +275,7 @@ public Optional getAccountName(UUID uuid) { */ @Override public boolean hasAccount(UUID uuid) { + return TNECore.eco().account().findAccount(uuid.toString()).isPresent(); } @@ -271,6 +289,7 @@ public boolean hasAccount(UUID uuid) { */ @Override public boolean hasAccount(UUID uuid, String worldName) { + return hasAccount(uuid); } @@ -285,6 +304,7 @@ public boolean hasAccount(UUID uuid, String worldName) { */ @Override public boolean renameAccount(UUID uuid, String name) { + return false; } @@ -298,6 +318,7 @@ public boolean renameAccount(UUID uuid, String name) { */ @Override public BigDecimal getBalance(String pluginName, UUID uuid) { + return getBalance(pluginName, uuid, TNECore.eco().region().defaultRegion(), defaultCurrency()); } @@ -313,6 +334,7 @@ public BigDecimal getBalance(String pluginName, UUID uuid) { */ @Override public BigDecimal getBalance(String pluginName, UUID uuid, String world) { + return getBalance(pluginName, uuid, world, defaultCurrency()); } @@ -329,6 +351,7 @@ public BigDecimal getBalance(String pluginName, UUID uuid, String world) { */ @Override public BigDecimal getBalance(String pluginName, UUID uuid, String world, String currency) { + final Optional account = TNECore.eco().account().findAccount(uuid.toString()); final Optional currencyOpt = TNECore.eco().currency().findCurrency(currency); @@ -353,6 +376,7 @@ public BigDecimal getBalance(String pluginName, UUID uuid, String world, String */ @Override public boolean has(String pluginName, UUID uuid, BigDecimal amount) { + return has(pluginName, uuid, TNECore.eco().region().defaultRegion(), defaultCurrency(), amount); } @@ -370,6 +394,7 @@ public boolean has(String pluginName, UUID uuid, BigDecimal amount) { */ @Override public boolean has(String pluginName, UUID uuid, String worldName, BigDecimal amount) { + return has(pluginName, uuid, worldName, defaultCurrency(), amount); } @@ -388,11 +413,12 @@ public boolean has(String pluginName, UUID uuid, String worldName, BigDecimal am */ @Override public boolean has(String pluginName, UUID uuid, String worldName, String currency, BigDecimal amount) { + final Optional account = TNECore.eco().account().findAccount(uuid.toString()); final Optional currencyOpt = TNECore.eco().currency().findCurrency(currency); return currencyOpt.filter(currency1->account.filter(value->value.getHoldingsTotal(worldName, currency1.getUid()) - .compareTo(amount) >= 0).isPresent()).isPresent(); + .compareTo(amount) >= 0).isPresent()).isPresent(); } @@ -403,11 +429,13 @@ public boolean has(String pluginName, UUID uuid, String worldName, String curren * @param uuid the UUID associated with the account to withdraw from. * @param amount Amount to withdraw. * - * @return {@link EconomyResponse} which includes the Economy plugin's {@link EconomyResponse.ResponseType} as to - * whether the transaction was a Success, Failure, Unsupported. + * @return {@link EconomyResponse} which includes the Economy plugin's + * {@link EconomyResponse.ResponseType} as to whether the transaction was a Success, Failure, + * Unsupported. */ @Override public EconomyResponse withdraw(String pluginName, UUID uuid, BigDecimal amount) { + return withdraw(pluginName, uuid, TNECore.eco().region().defaultRegion(), defaultCurrency(), amount); } @@ -426,6 +454,7 @@ public EconomyResponse withdraw(String pluginName, UUID uuid, BigDecimal amount) */ @Override public EconomyResponse withdraw(String pluginName, UUID uuid, String worldName, BigDecimal amount) { + return withdraw(pluginName, uuid, worldName, defaultCurrency(), amount); } @@ -445,16 +474,17 @@ public EconomyResponse withdraw(String pluginName, UUID uuid, String worldName, */ @Override public EconomyResponse withdraw(String pluginName, UUID uuid, String worldName, String currency, BigDecimal amount) { + final Optional account = TNECore.eco().account().findAccount(uuid.toString()); if(account.isEmpty()) { return new EconomyResponse(BigDecimal.ZERO, BigDecimal.ZERO, - EconomyResponse.ResponseType.FAILURE, "Unable to locate associated account."); + EconomyResponse.ResponseType.FAILURE, "Unable to locate associated account."); } final HoldingsModifier modifier = new HoldingsModifier(worldName, - TNECore.eco().currency().getDefaultCurrency(worldName).getUid(), - amount); + TNECore.eco().currency().getDefaultCurrency(worldName).getUid(), + amount); final Transaction transaction = new Transaction("take") .to(account.get(), modifier.counter()) @@ -464,12 +494,12 @@ public EconomyResponse withdraw(String pluginName, UUID uuid, String worldName, try { TransactionResult result = transaction.process(); return new EconomyResponse(amount, transaction.getTo().getCombinedEnding(), - fromResult(result), - result.getMessage()); + fromResult(result), + result.getMessage()); } catch(InvalidTransactionException e) { return new EconomyResponse(amount, transaction.getTo().getCombinedEnding(), - EconomyResponse.ResponseType.FAILURE, e.getMessage()); + EconomyResponse.ResponseType.FAILURE, e.getMessage()); } } @@ -485,6 +515,7 @@ public EconomyResponse withdraw(String pluginName, UUID uuid, String worldName, */ @Override public EconomyResponse deposit(String pluginName, UUID uuid, BigDecimal amount) { + return deposit(pluginName, uuid, TNECore.eco().region().defaultRegion(), defaultCurrency(), amount); } @@ -503,6 +534,7 @@ public EconomyResponse deposit(String pluginName, UUID uuid, BigDecimal amount) */ @Override public EconomyResponse deposit(String pluginName, UUID uuid, String worldName, BigDecimal amount) { + return deposit(pluginName, uuid, worldName, defaultCurrency(), amount); } @@ -522,6 +554,7 @@ public EconomyResponse deposit(String pluginName, UUID uuid, String worldName, B */ @Override public EconomyResponse deposit(String pluginName, UUID uuid, String worldName, String currency, BigDecimal amount) { + final Optional account = TNECore.eco().account().findAccount(uuid.toString()); if(account.isEmpty()) { @@ -529,8 +562,8 @@ public EconomyResponse deposit(String pluginName, UUID uuid, String worldName, S } final HoldingsModifier modifier = new HoldingsModifier(worldName, - TNECore.eco().currency().getDefaultCurrency(worldName).getUid(), - amount); + TNECore.eco().currency().getDefaultCurrency(worldName).getUid(), + amount); final Transaction transaction = new Transaction("give") @@ -541,11 +574,11 @@ public EconomyResponse deposit(String pluginName, UUID uuid, String worldName, S try { TransactionResult result = transaction.process(); return new EconomyResponse(amount, transaction.getTo().getCombinedEnding(), fromResult(result), - result.getMessage()); + result.getMessage()); } catch(InvalidTransactionException e) { return new EconomyResponse(amount, transaction.getTo().getCombinedEnding(), - ResponseType.FAILURE, e.getMessage()); + ResponseType.FAILURE, e.getMessage()); } } @@ -560,6 +593,7 @@ public EconomyResponse deposit(String pluginName, UUID uuid, String worldName, S */ @Override public boolean createBank(String pluginName, String name, UUID uuid) { + return false; } @@ -573,6 +607,7 @@ public boolean createBank(String pluginName, String name, UUID uuid) { */ @Override public boolean deleteBank(String pluginName, UUID uuid) { + return false; } @@ -586,6 +621,7 @@ public boolean deleteBank(String pluginName, UUID uuid) { */ @Override public Map getBankUUIDNameMap() { + return Map.of(); } @@ -599,6 +635,7 @@ public Map getBankUUIDNameMap() { */ @Override public String getBankAccountName(UUID uuid) { + return ""; } @@ -611,6 +648,7 @@ public String getBankAccountName(UUID uuid) { */ @Override public boolean hasBankAccount(UUID uuid) { + return false; } @@ -624,6 +662,7 @@ public boolean hasBankAccount(UUID uuid) { */ @Override public boolean bankSupportsCurrency(UUID uuid, String currency) { + return false; } @@ -639,6 +678,7 @@ public boolean bankSupportsCurrency(UUID uuid, String currency) { */ @Override public boolean renameBankAccount(String pluginName, UUID uuid, String name) { + return false; } @@ -652,6 +692,7 @@ public boolean renameBankAccount(String pluginName, UUID uuid, String name) { */ @Override public BigDecimal bankBalance(String pluginName, UUID uuid) { + return BigDecimal.ZERO; } @@ -666,6 +707,7 @@ public BigDecimal bankBalance(String pluginName, UUID uuid) { */ @Override public BigDecimal bankBalance(String pluginName, UUID uuid, String currency) { + return BigDecimal.ZERO; } @@ -680,6 +722,7 @@ public BigDecimal bankBalance(String pluginName, UUID uuid, String currency) { */ @Override public boolean bankHas(String pluginName, UUID uuid, BigDecimal amount) { + return false; } @@ -695,6 +738,7 @@ public boolean bankHas(String pluginName, UUID uuid, BigDecimal amount) { */ @Override public boolean bankHas(String pluginName, UUID uuid, String currency, BigDecimal amount) { + return false; } @@ -710,6 +754,7 @@ public boolean bankHas(String pluginName, UUID uuid, String currency, BigDecimal */ @Override public EconomyResponse bankWithdraw(String pluginName, UUID uuid, BigDecimal amount) { + return new EconomyResponse(BigDecimal.ZERO, BigDecimal.ZERO, ResponseType.NOT_IMPLEMENTED, ""); } @@ -726,6 +771,7 @@ public EconomyResponse bankWithdraw(String pluginName, UUID uuid, BigDecimal amo */ @Override public EconomyResponse bankWithdraw(String pluginName, UUID uuid, String currency, BigDecimal amount) { + return new EconomyResponse(BigDecimal.ZERO, BigDecimal.ZERO, ResponseType.NOT_IMPLEMENTED, ""); } @@ -741,6 +787,7 @@ public EconomyResponse bankWithdraw(String pluginName, UUID uuid, String currenc */ @Override public EconomyResponse bankDeposit(String pluginName, UUID uuid, BigDecimal amount) { + return new EconomyResponse(BigDecimal.ZERO, BigDecimal.ZERO, ResponseType.NOT_IMPLEMENTED, ""); } @@ -752,11 +799,13 @@ public EconomyResponse bankDeposit(String pluginName, UUID uuid, BigDecimal amou * @param currency the currency to use. * @param amount to deposit. * - * @return {@link EconomyResponse} which includes the Economy plugin's {@link EconomyResponse.ResponseType} as to - * whether the transaction was a Success, Failure, Unsupported. + * @return {@link EconomyResponse} which includes the Economy plugin's + * {@link EconomyResponse.ResponseType} as to whether the transaction was a Success, Failure, + * Unsupported. */ @Override public EconomyResponse bankDeposit(String pluginName, UUID uuid, String currency, BigDecimal amount) { + return new EconomyResponse(BigDecimal.ZERO, BigDecimal.ZERO, ResponseType.NOT_IMPLEMENTED, ""); } @@ -770,6 +819,7 @@ public EconomyResponse bankDeposit(String pluginName, UUID uuid, String currency */ @Override public boolean isBankOwner(UUID uuid, UUID bankUUID) { + return false; } @@ -783,6 +833,7 @@ public boolean isBankOwner(UUID uuid, UUID bankUUID) { */ @Override public boolean isBankMember(UUID uuid, UUID bankUUID) { + return false; } @@ -793,10 +844,12 @@ public boolean isBankMember(UUID uuid, UUID bankUUID) { */ @Override public Collection getBanks() { + return List.of(); } private EconomyResponse.ResponseType fromResult(@Nullable TransactionResult result) { + if(result != null && result.isSuccessful()) { return EconomyResponse.ResponseType.SUCCESS; } diff --git a/PaperCore/src/net/tnemc/paper/hook/economy/VaultHook.java b/PaperCore/src/net/tnemc/paper/hook/economy/VaultHook.java index f350beeb..c2b28f2f 100644 --- a/PaperCore/src/net/tnemc/paper/hook/economy/VaultHook.java +++ b/PaperCore/src/net/tnemc/paper/hook/economy/VaultHook.java @@ -38,6 +38,7 @@ public class VaultHook implements Hook { */ @Override public boolean enabled() { + return false; } @@ -46,8 +47,9 @@ public boolean enabled() { */ @Override public void register() { + PaperCore.instance().getPlugin().getServer().getServicesManager().register(Economy.class, new TNEVault(), - PaperCore.instance().getPlugin(), ServicePriority.Highest); + PaperCore.instance().getPlugin(), ServicePriority.Highest); PluginCore.log().inform("Hooked into Vault"); } diff --git a/PaperCore/src/net/tnemc/paper/hook/economy/VaultUnlockedHook.java b/PaperCore/src/net/tnemc/paper/hook/economy/VaultUnlockedHook.java index 860d84cf..030ee6df 100644 --- a/PaperCore/src/net/tnemc/paper/hook/economy/VaultUnlockedHook.java +++ b/PaperCore/src/net/tnemc/paper/hook/economy/VaultUnlockedHook.java @@ -37,6 +37,7 @@ public class VaultUnlockedHook implements Hook { */ @Override public boolean enabled() { + return false; } @@ -45,8 +46,9 @@ public boolean enabled() { */ @Override public void register() { + PaperCore.instance().getPlugin().getServer().getServicesManager().register(Economy.class, new TNEVaultUnlocked(), - PaperCore.instance().getPlugin(), ServicePriority.Highest); + PaperCore.instance().getPlugin(), ServicePriority.Highest); PluginCore.log().inform("Hooked into VaultUnlocked"); } diff --git a/PaperCore/src/net/tnemc/paper/hook/misc/PAPIHook.java b/PaperCore/src/net/tnemc/paper/hook/misc/PAPIHook.java index 5fbdee75..5b1656a2 100644 --- a/PaperCore/src/net/tnemc/paper/hook/misc/PAPIHook.java +++ b/PaperCore/src/net/tnemc/paper/hook/misc/PAPIHook.java @@ -47,21 +47,25 @@ public class PAPIHook extends PlaceholderExpansion { @Override public String getAuthor() { + return "creatorfromhell"; } @Override public String getIdentifier() { + return "TNE"; } @Override public String getVersion() { + return "0.1.2.8"; } @Override public boolean persist() { + return true; } @@ -109,9 +113,9 @@ public String onPlaceholderRequest(Player player, @NotNull String identifier) { } final HoldingsEntry entry = new HoldingsEntry(TNECore.eco().region().defaultRegion(), - curID, - amount, - EconomyManager.NORMAL); + curID, + amount, + EconomyManager.NORMAL); return CurrencyFormatter.format(account.get(), entry); } else { return amount.toPlainString(); @@ -233,10 +237,12 @@ public String onPlaceholderRequest(Player player, @NotNull String identifier) { } public boolean formatted(final String parameter) { + return parameter.contains("formatted"); } public Optional findFromArgs(final String parameter) { + return TNECore.eco().account().findAccount(parameter); } } \ No newline at end of file diff --git a/PaperCore/src/net/tnemc/paper/listener/PlayerInteractListener.java b/PaperCore/src/net/tnemc/paper/listener/PlayerInteractListener.java index 2b69584c..264b3e52 100644 --- a/PaperCore/src/net/tnemc/paper/listener/PlayerInteractListener.java +++ b/PaperCore/src/net/tnemc/paper/listener/PlayerInteractListener.java @@ -39,6 +39,7 @@ public class PlayerInteractListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void onInteract(final PlayerInteractEvent event) { + final PlayerProvider provider = PluginCore.server().initializePlayer(event.getPlayer()); final ItemStack stack = event.getItem(); @@ -46,7 +47,7 @@ public void onInteract(final PlayerInteractEvent event) { if(stack == null) return; if(event.getAction().equals(Action.RIGHT_CLICK_AIR) || - event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { + event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { new PlayerInteractHandler().handle(provider, BukkitItemStack.locale(stack)); } diff --git a/README.md b/README.md index 435aa172..fa0939bf 100644 --- a/README.md +++ b/README.md @@ -3,8 +3,10 @@ [![Codacy Badge](https://app.codacy.com/project/badge/Grade/246101510dca4eb9a729ef178dae682c)](https://app.codacy.com/gh/TheNewEconomy/EconomyCore/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_grade) [![Build Status](https://ci.codemc.io/job/creatorfromhell/job/TNE/badge/icon)](https://ci.codemc.io/job/creatorfromhell/job/TNE/) -The New Economy, TNE, is the ultimate economy plugin for your Minecraft server, no matter what platform you're on. While -TNE is pushed as being "feature-packed," but it's not feature-packed in the normal sense of jamming a bunch of useless features +The New Economy, TNE, is the ultimate economy plugin for your Minecraft server, no matter what +platform you're on. While +TNE is pushed as being "feature-packed," but it's not feature-packed in the normal sense of jamming +a bunch of useless features into the core plugin, but rather using modules.

@@ -15,58 +17,81 @@ into the core plugin, but rather using modules.

# About TNE -TNE was originally created for hey0's hMod long before Bukkit/Spigot/Paper was a thing. Since then, it has taken on many -forms and this is the future form of the plugin. This core is designed to be robust and carry TNE into the future with or + +TNE was originally created for hey0's hMod long before Bukkit/Spigot/Paper was a thing. Since then, +it has taken on many +forms and this is the future form of the plugin. This core is designed to be robust and carry TNE +into the future with or without Minecraft by not being platform-dependent. # Why TNE? ## Platform Agnostic + Use TNE on the platform you want! + - Sponge? If you want - Spigot/Paper? Definitely! -- Use both? We support cross-server balances on both. That's right. You can send money from your Spigot server to your -Sponge Server! +- Use both? We support cross-server balances on both. That's right. You can send money from your + Spigot server to your + Sponge Server! ## Features + Want minimal Features? Why not! Want all the features? That's an option too! -I believe that server owners should be able to have options, and that's the premise behind TNE. While many features are -offered, they're all optional. If you don't want any additional features, and just want a simple economy then you can elect +I believe that server owners should be able to have options, and that's the premise behind TNE. +While many features are +offered, they're all optional. If you don't want any additional features, and just want a simple +economy then you can elect to not download and install them, it's as easy as that! ## API Support -TNE offers support for Vault, which lets any third-party plugin hook into your economy and add additional functionality. + +TNE offers support for Vault, which lets any third-party plugin hook into your economy and add +additional functionality. Key Supported Plugins: + - Factions - Towny - Geyser ## Easy to Use -TNE has been recorded with ease of use in mind. This means whether you're a power user who loves your YAML files, or a + +TNE has been recorded with ease of use in mind. This means whether you're a power user who loves +your YAML files, or a a casual user who wants Menu-based interactions, TNE is right for you! ## Free as in Freedom, not Free as in Beer -[TNE is licensed under the AGPLv3](license.md), which means you're free to use it how you want. This also means that + +[TNE is licensed under the AGPLv3](license.md), which means you're free to use it how you want. This +also means that networks that add improvements to their version must also provide them for everyone else to enjoy! ## Translations + TNE utilizes Crowdin for Translation management. Find more about contributing to translations -for TNE on the [Translation Guide](https://github.com/TheNewEconomy/EconomyCore/wiki/Translation-Guide). +for TNE on +the [Translation Guide](https://github.com/TheNewEconomy/EconomyCore/wiki/Translation-Guide). ## Documented + TNE has lots of documentation for the power users that like all the documentation. -*Please note: As the new TNE Core is a work in progress, documentation is very limited at the moment.* +*Please note: As the new TNE Core is a work in progress, documentation is very limited at the +moment.* ## Requirements + TNE has some minimum requirements that should be followed. + - MySQL 8.0+ (if using MySQL for storage) - MariaDB 10.7.0+ - Java 17+ ## Project Support + We have some organizations that provide open-source licenses to help support this project. diff --git a/Sponge8/pom.xml b/Sponge8/pom.xml index fa4f9752..3668b9bd 100644 --- a/Sponge8/pom.xml +++ b/Sponge8/pom.xml @@ -1,4 +1,6 @@ - + 4.0.0 Sponge8Core jar @@ -29,7 +31,6 @@ - clean package target @@ -86,7 +87,9 @@ - ${project.build.directory}/dependency-reduced-pom.xml + + ${project.build.directory}/dependency-reduced-pom.xml + net.tnemc:* diff --git a/Sponge8/src/net/tnemc/sponge/SpongeCore.java b/Sponge8/src/net/tnemc/sponge/SpongeCore.java index 1db6f4a6..06bcecae 100644 --- a/Sponge8/src/net/tnemc/sponge/SpongeCore.java +++ b/Sponge8/src/net/tnemc/sponge/SpongeCore.java @@ -80,6 +80,7 @@ public class SpongeCore extends TNECore { @Inject SpongeCore(final PluginContainer container, final Logger log, final Metrics.Factory metricsFactory) { + this.pluginCore = new SpongePluginCore(container, this, log, new BaseTranslationProvider(), new TNECallbackProvider()); this.container = container; @@ -90,12 +91,14 @@ public class SpongeCore extends TNECore { @Override public void registerMenuHandler() { + this.menuHandler = new Sponge8MenuHandler(container, true); } @Listener public void onConstruct(final ConstructPluginEvent event) { + if(hasConsent()) { metrics.startup(event); } @@ -103,6 +106,7 @@ public void onConstruct(final ConstructPluginEvent event) { @Listener public void onEngineStart(final StartingEngineEvent event) { + PluginCore.log().inform("Starting up The New Economy."); //Register our event listeners @@ -120,26 +124,31 @@ public void onServerStart(final StartedEngineEvent event) { @Listener public void onServerStop(final StoppingEngineEvent event) { + pluginCore.onDisable(); PluginCore.log().inform("The New Economy has been disabled."); } @Listener public void provideEconomy(final ProvideServiceEvent.EngineScoped event) { + event.suggest(SpongeEconomy::new); } public PluginContainer getContainer() { + return container; } @Override public void registerCommandHandler() { + command = SpongeCommandHandler.create(container); } @Override public String commandHelpWriter(ExecutableCommand executableCommand, CommandActor commandActor) { + return ""; } @@ -162,20 +171,24 @@ public void registerConfigs() { @Override public void registerCallbacks(CallbackManager callbackManager) { + super.registerCallbacks(callbackManager); //nothing to see here. } @Override public SpongeItemCalculations itemCalculations() { + return new SpongeItemCalculations(); } public boolean hasConsent() { + return this.metricsConfigManager.collectionState(this.container).asBoolean(); } public static ResourceKey key(final String key) { + final String[] split = key.split(":"); final String namespace = (split.length >= 2)? split[0] : "minecraft"; diff --git a/Sponge8/src/net/tnemc/sponge/command/AdminCommand.java b/Sponge8/src/net/tnemc/sponge/command/AdminCommand.java index aa309b3a..f2f421e8 100644 --- a/Sponge8/src/net/tnemc/sponge/command/AdminCommand.java +++ b/Sponge8/src/net/tnemc/sponge/command/AdminCommand.java @@ -37,112 +37,125 @@ * @author creatorfromhell * @since 0.1.2.0 */ -@Command({"tne", "ecomin", "ecoadmin", "ecomanage", "theneweconomy"}) +@Command({ "tne", "ecomin", "ecoadmin", "ecomanage", "theneweconomy" }) @Description("#{Admin.Main.Description}") public class AdminCommand { - @DefaultFor({"tne", "ecomin", "ecoadmin", "ecomanage", "theneweconomy"}) - @Subcommand({"ecomenu", "menu", "myeco", "ecomenu"}) + @DefaultFor({ "tne", "ecomin", "ecoadmin", "ecomanage", "theneweconomy" }) + @Subcommand({ "ecomenu", "menu", "myeco", "ecomenu" }) @Usage("#{Admin.MyEco.Arguments}") @Description("#{Admin.MyEco.Description}") @CommandPermission("tne.money.myeco") public void onMyEco(SpongeCommandActor sender) { + net.tnemc.core.command.AdminCommand.onMyEco(new SpongeCMDSource(sender)); } - @Subcommand({"backup", "archive"}) + @Subcommand({ "backup", "archive" }) @Usage("#{Admin.Backup.Arguments}") @Description("#{Admin.Backup.Description}") @CommandPermission("tne.admin.backup") public void backup(SpongeCommandActor sender) { + net.tnemc.core.command.AdminCommand.onBackup(new SpongeCMDSource(sender)); } - @Subcommand({"create", "add", "new", "make", "+"}) + @Subcommand({ "create", "add", "new", "make", "+" }) @Usage("#{Admin.Create.Arguments}") @Description("#{Admin.Create.Description}") @CommandPermission("tne.admin.create") public void create(SpongeCommandActor sender, String name) { + net.tnemc.core.command.AdminCommand.onCreate(new SpongeCMDSource(sender), name); } - @Subcommand({"debug"}) + @Subcommand({ "debug" }) @Usage("#{Admin.Debug.Arguments}") @Description("#{Admin.Debug.Description}") @CommandPermission("tne.admin.debug") public void debug(SpongeCommandActor sender, DebugLevel level) { + net.tnemc.core.command.AdminCommand.onDebug(new SpongeCMDSource(sender), level); } - @Subcommand({"delete", "destroy", "del", "remove", "-"}) + @Subcommand({ "delete", "destroy", "del", "remove", "-" }) @Usage("#{Admin.Delete.Arguments}") @Description("#{Admin.Delete.Description}") @CommandPermission("tne.admin.delete") public void delete(SpongeCommandActor sender, String name) { + net.tnemc.core.command.AdminCommand.onDelete(new SpongeCMDSource(sender), name); } - @Subcommand({"extract"}) + @Subcommand({ "extract" }) @Usage("#{Admin.Extract.Arguments}") @Description("#{Admin.Extract.Description}") @CommandPermission("tne.admin.extract") public void extract(SpongeCommandActor sender) { + net.tnemc.core.command.AdminCommand.onExtract(new SpongeCMDSource(sender)); } - @Subcommand({"purge"}) + @Subcommand({ "purge" }) @Usage("#{Admin.Purge.Arguments}") @Description("#{Admin.Purge.Description}") @CommandPermission("tne.admin.purge") public void purge(SpongeCommandActor sender) { + net.tnemc.core.command.AdminCommand.onPurge(new SpongeCMDSource(sender)); } - @Subcommand({"reload"}) + @Subcommand({ "reload" }) @Usage("#{Admin.Reload.Arguments}") @Description("#{Admin.Reload.Description}") @CommandPermission("tne.admin.reload") public void reload(SpongeCommandActor sender, @Default("all") String type) { + net.tnemc.core.command.AdminCommand.onReload(new SpongeCMDSource(sender), type); } - @Subcommand({"reset", "nuke"}) + @Subcommand({ "reset", "nuke" }) @Usage("#{Admin.Reset.Arguments}") @Description("#{Admin.Reset.Description}") @CommandPermission("tne.admin.reset") public void reset(SpongeCommandActor sender) { + net.tnemc.core.command.AdminCommand.onReset(new SpongeCMDSource(sender)); } - @Subcommand({"restore"}) + @Subcommand({ "restore" }) @Usage("#{Admin.Restore.Arguments}") @Description("#{Admin.Restore.Description}") @CommandPermission("tne.admin.restore") public void restore(SpongeCommandActor sender, @Default("0") int extraction) { + net.tnemc.core.command.AdminCommand.onRestore(new SpongeCMDSource(sender), extraction); } - @Subcommand({"save"}) + @Subcommand({ "save" }) @Usage("#{Admin.Save.Arguments}") @Description("#{Admin.Save.Description}") @CommandPermission("tne.admin.save") public void save(SpongeCommandActor sender) { + net.tnemc.core.command.AdminCommand.onSave(new SpongeCMDSource(sender)); } - @Subcommand({"status"}) + @Subcommand({ "status" }) @Usage("#{Admin.Status.Arguments}") @Description("#{Admin.Status.Description}") @CommandPermission("tne.admin.status") public void status(SpongeCommandActor sender, Account account, @Default("normal") AccountStatus status) { + net.tnemc.core.command.AdminCommand.onStatus(new SpongeCMDSource(sender), account, status); } - @Subcommand({"version", "ver", "build"}) + @Subcommand({ "version", "ver", "build" }) @Usage("#{Admin.Version.Arguments}") @Description("#{Admin.Version.Description}") @CommandPermission("tne.admin.version") public void version(SpongeCommandActor sender) { + net.tnemc.core.command.AdminCommand.onVersion(new SpongeCMDSource(sender)); } } diff --git a/Sponge8/src/net/tnemc/sponge/command/ModuleCommand.java b/Sponge8/src/net/tnemc/sponge/command/ModuleCommand.java index 6675da92..1b779774 100644 --- a/Sponge8/src/net/tnemc/sponge/command/ModuleCommand.java +++ b/Sponge8/src/net/tnemc/sponge/command/ModuleCommand.java @@ -34,23 +34,25 @@ * @author creatorfromhell * @since 0.1.2.0 */ -@Command({"module", "mod"}) +@Command({ "module", "mod" }) public class ModuleCommand { - @Subcommand({"info", "i"}) + @Subcommand({ "info", "i" }) @Usage("#{Module.Info.Arguments}") @Description("#{Module.Info.Description}") @CommandPermission("tne.module.info") public void onInfo(SpongeCommandActor sender, String moduleName) { + net.tnemc.core.command.ModuleCommand.onInfo(new SpongeCMDSource(sender), moduleName); } - @Subcommand({"list", "l"}) + @Subcommand({ "list", "l" }) @Usage("#{Module.List.Arguments}") - @DefaultFor({"module", "mod"}) + @DefaultFor({ "module", "mod" }) @Description("#{Module.List.Description}") @CommandPermission("tne.list.available") public void onList(SpongeCommandActor sender) { + net.tnemc.core.command.ModuleCommand.onList(new SpongeCMDSource(sender)); } } \ No newline at end of file diff --git a/Sponge8/src/net/tnemc/sponge/command/MoneyCommand.java b/Sponge8/src/net/tnemc/sponge/command/MoneyCommand.java index 535fd1f5..92035948 100644 --- a/Sponge8/src/net/tnemc/sponge/command/MoneyCommand.java +++ b/Sponge8/src/net/tnemc/sponge/command/MoneyCommand.java @@ -40,137 +40,153 @@ * @author creatorfromhell * @since 0.1.2.0 */ -@Command({"money", "eco", "balo", "balance", "bal", "balanceother", "mybal"}) +@Command({ "money", "eco", "balo", "balance", "bal", "balanceother", "mybal" }) public class MoneyCommand { - @DefaultFor({"mybal"}) - @Subcommand({"balmenu", "menu", "mybal"}) + @DefaultFor({ "mybal" }) + @Subcommand({ "balmenu", "menu", "mybal" }) @Usage("Money.MyBal.Arguments") @Description("Money.MyBal.Description") @CommandPermission("tne.money.mybal") public void onMyBal(SpongeCommandActor sender) { + net.tnemc.core.command.MoneyCommand.onMyBal(new SpongeCMDSource(sender)); } - @DefaultFor({"bal", "money", "eco", "balance"}) - @Subcommand({"balance", "bal", "val"}) + @DefaultFor({ "bal", "money", "eco", "balance" }) + @Subcommand({ "balance", "bal", "val" }) @Usage("#{Money.Balance.Arguments}") @Description("#{Money.Balance.Description}") @CommandPermission("tne.money.balance") public void onBalance(SpongeCommandActor sender, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onBalance(new SpongeCMDSource(sender), currency, region); } - @Subcommand({"convert"}) + @Subcommand({ "convert" }) @Usage("#{Money.Convert.Arguments}") @Description("#{Money.Convert.Description}") @CommandPermission("tne.money.convert") public void onConvert(SpongeCommandActor sender, @Named("amount") PercentBigDecimal amount, @Named("currency") Currency currency, Currency fromCurrency) { + net.tnemc.core.command.MoneyCommand.onConvert(new SpongeCMDSource(sender), amount, currency, fromCurrency); } - @Subcommand({"deposit"}) + @Subcommand({ "deposit" }) @Usage("Money.Deposit.Arguments") @Description("Money.Deposit.Description") @CommandPermission("tne.money.deposit") public void onDeposit(SpongeCommandActor sender, @Named("amount") PercentBigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onDeposit(new SpongeCMDSource(sender), amount, currency, region); } - @Subcommand({"give", "+", "add"}) + @Subcommand({ "give", "+", "add" }) @Usage("#{Money.Give.Arguments}") @Description("#{Money.Give.Description}") @CommandPermission("tne.money.give") public void onGive(SpongeCommandActor sender, Account player, @Named("amount") PercentBigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onGive(new SpongeCMDSource(sender), player, amount, region, currency); } - @Subcommand({"givenote", "+note", "addnote"}) + @Subcommand({ "givenote", "+note", "addnote" }) @Usage("Money.GiveNote.Arguments") @Description("Money.GiveNote.Description") @CommandPermission("tne.money.givenote") public void onGiveNote(SpongeCommandActor sender, Account player, @Named("amount") BigDecimal amount, @Default("") @Named("currency") Currency currency) { + net.tnemc.core.command.MoneyCommand.onGiveNote(new SpongeCMDSource(sender), player, amount, currency); } - @Subcommand({"note", "n"}) + @Subcommand({ "note", "n" }) @Usage("#{Money.Note.Arguments}") @Description("#{Money.Note.Description}") @CommandPermission("tne.money.note") public void onNote(SpongeCommandActor sender, @Named("amount") PercentBigDecimal amount, @Default("") @Named("currency") Currency currency) { + net.tnemc.core.command.MoneyCommand.onNote(new SpongeCMDSource(sender), amount, currency); } - @Subcommand({"other", "check", "balo"}) - @DefaultFor({"balo", "balanceother"}) + @Subcommand({ "other", "check", "balo" }) + @DefaultFor({ "balo", "balanceother" }) @Usage("#{Money.Other.Arguments}") @Description("#{Money.Other.Description}") @CommandPermission("tne.money.other") public void onOther(SpongeCommandActor sender, Account player, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onOther(new SpongeCMDSource(sender), player, region, currency); } - @Subcommand({"pay", "send", "transfer"}) + @Subcommand({ "pay", "send", "transfer" }) @Usage("#{Money.Pay.Arguments}") @Description("#{Money.Pay.Description}") @CommandPermission("tne.money.pay") public void onPay(SpongeCommandActor sender, Account player, @Named("amount") PercentBigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("") String from) { + net.tnemc.core.command.MoneyCommand.onPay(new SpongeCMDSource(sender), player, amount, currency, from); } - @Subcommand({"request"}) + @Subcommand({ "request" }) @Usage("#{Money.Request.Arguments}") @Description("#{Money.Request.Description}") @CommandPermission("tne.money.Request") public void onRequest(SpongeCommandActor sender, Account player, @Named("amount") BigDecimal amount, @Default("") @Named("currency") Currency currency) { + net.tnemc.core.command.MoneyCommand.onRequest(new SpongeCMDSource(sender), player, amount, currency); } - @Subcommand({"set", "eq", "="}) + @Subcommand({ "set", "eq", "=" }) @Usage("#{Money.Set.Arguments}") @Description("#{Money.Set.Description}") @CommandPermission("tne.money.set") public void onSet(SpongeCommandActor sender, Account player, @Named("amount") BigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onSet(new SpongeCMDSource(sender), player, amount, region, currency); } - @Subcommand({"setall"}) + @Subcommand({ "setall" }) @Usage("#{Money.SetAll.Arguments}") @Description("#{Money.SetAll.Description}") @CommandPermission("tne.money.setall") public void onSetAll(SpongeCommandActor sender, @Named("amount") BigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onSetAll(new SpongeCMDSource(sender), amount, region, currency); } - @Subcommand({"switch", "swap"}) + @Subcommand({ "switch", "swap" }) @Usage("Money.Switch.Arguments") @Description("Money.Switch.Description") @CommandPermission("tne.money.switch") public void onSwitch(SpongeCommandActor sender, @Named("switched") Account account) { + net.tnemc.core.command.MoneyCommand.onSwitch(new SpongeCMDSource(sender), account); } - @Subcommand({"take", "minus", "remove", "-"}) + @Subcommand({ "take", "minus", "remove", "-" }) @Usage("#{Money.Take.Arguments}") @Description("#{Money.Take.Description}") @CommandPermission("tne.money.take") public void onTake(SpongeCommandActor sender, Account player, @Named("amount") PercentBigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onTake(new SpongeCMDSource(sender), player, amount, region, currency); } - @Subcommand({"top", "baltop"}) + @Subcommand({ "top", "baltop" }) @Usage("Money.Top.Arguments") @Description("Money.Top.Description") @CommandPermission("tne.money.top") public void onTop(SpongeCommandActor sender, Integer page, @Default("") @Named("currency") Currency currency, @Default("false") Boolean refresh) { + net.tnemc.core.command.MoneyCommand.onTop(new SpongeCMDSource(sender), page, currency, refresh); } - @Subcommand({"withdraw"}) + @Subcommand({ "withdraw" }) @Usage("Money.Withdraw.Arguments") @Description("Money.Withdraw.Description") @CommandPermission("tne.money.withdraw") public void onWithdraw(SpongeCommandActor sender, @Named("amount") PercentBigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onWithdraw(new SpongeCMDSource(sender), amount, currency, region); } } \ No newline at end of file diff --git a/Sponge8/src/net/tnemc/sponge/command/ShortCommands.java b/Sponge8/src/net/tnemc/sponge/command/ShortCommands.java index 35da674b..dc953bfc 100644 --- a/Sponge8/src/net/tnemc/sponge/command/ShortCommands.java +++ b/Sponge8/src/net/tnemc/sponge/command/ShortCommands.java @@ -41,59 +41,66 @@ */ public class ShortCommands { - @Command({"givemoney", "givebal"}) + @Command({ "givemoney", "givebal" }) @Usage("Money.Give.Arguments") @Description("Money.Give.Description") @CommandPermission("tne.money.give") public void onGive(SpongeCommandActor sender, @Named("account") Account player, @Named("amount") PercentBigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onGive(new SpongeCMDSource(sender), player, amount, region, currency); } - @Command({"givenote", "+note", "addnote"}) + @Command({ "givenote", "+note", "addnote" }) @Usage("Money.GiveNote.Arguments") @Description("Money.GiveNote.Description") @CommandPermission("tne.money.givenote") public void onGiveNote(SpongeCommandActor sender, Account player, @Named("amount") BigDecimal amount, @Default("") @Named("currency") Currency currency) { + net.tnemc.core.command.MoneyCommand.onGiveNote(new SpongeCMDSource(sender), player, amount, currency); } - @Command({"pay"}) + @Command({ "pay" }) @Usage("Money.Pay.Arguments") @Description("Money.Pay.Description") @CommandPermission("tne.money.pay") public void onPay(SpongeCommandActor sender, @Named("account") Account player, @Named("amount") PercentBigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("") String from) { + net.tnemc.core.command.MoneyCommand.onPay(new SpongeCMDSource(sender), player, amount, currency, from); } - @Command({"setmoney", "setbal"}) + @Command({ "setmoney", "setbal" }) @Usage("Money.Set.Arguments") @Description("Money.Set.Description") @CommandPermission("tne.money.set") public void onSet(SpongeCommandActor sender, @Named("account") Account player, @Named("amount") BigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onSet(new SpongeCMDSource(sender), player, amount, region, currency); } - @Command({"takemoney", "takebal"}) + @Command({ "takemoney", "takebal" }) @Usage("Money.Take.Arguments") @Description("Money.Take.Description") @CommandPermission("tne.money.take") public void onTake(SpongeCommandActor sender, @Named("account") Account player, @Named("amount") PercentBigDecimal amount, @Default("") @Named("currency") Currency currency, @Default("world-113") @Named("region") String region) { + net.tnemc.core.command.MoneyCommand.onTake(new SpongeCMDSource(sender), player, amount, region, currency); } - @Command({"baltop"}) + @Command({ "baltop" }) @Usage("Money.Top.Arguments") @Description("Money.Top.Description") @CommandPermission("tne.money.top") public void onTop(SpongeCommandActor sender, @Default("1") @Named("page") Integer page, @Default("") @Named("currency") Currency currency, @Default("false") Boolean refresh) { + net.tnemc.core.command.MoneyCommand.onTop(new SpongeCMDSource(sender), page, currency, refresh); } - @Command({"transactions"}) + @Command({ "transactions" }) @Usage("Transaction.History.Arguments") @Description("Transaction.History.Description") @CommandPermission("tne.transaction.history") public void history(SpongeCommandActor sender, @Default("1") int page, @Default("world-113") @Named("region") String region, @Default("SELF_ACCOUNT") Account account) { + net.tnemc.core.command.TransactionCommand.history(new SpongeCMDSource(sender), page, region, account); } } \ No newline at end of file diff --git a/Sponge8/src/net/tnemc/sponge/command/TransactionCommand.java b/Sponge8/src/net/tnemc/sponge/command/TransactionCommand.java index 8f019527..8127787e 100644 --- a/Sponge8/src/net/tnemc/sponge/command/TransactionCommand.java +++ b/Sponge8/src/net/tnemc/sponge/command/TransactionCommand.java @@ -38,39 +38,43 @@ * @author creatorfromhell * @since 0.1.2.0 */ -@Command({"transaction", "trans", "receipt"}) +@Command({ "transaction", "trans", "receipt" }) public class TransactionCommand { - @Subcommand({"away", "gone", "afk", "afg"}) + @Subcommand({ "away", "gone", "afk", "afg" }) @Usage("Transaction.Away.Arguments") @Description("Transaction.Away.Description") @CommandPermission("tne.transaction.away") public void away(SpongeCommandActor sender, @Default("1") int page) { + net.tnemc.core.command.TransactionCommand.away(new SpongeCMDSource(sender), page); } - @DefaultFor({"transaction", "trans", "receipt"}) - @Subcommand({"history", "list", "hist", "archive"}) + @DefaultFor({ "transaction", "trans", "receipt" }) + @Subcommand({ "history", "list", "hist", "archive" }) @Usage("Transaction.History.Arguments") @Description("Transaction.History.Description") @CommandPermission("tne.transaction.history") public void history(SpongeCommandActor sender, @Default("1") int page, String region, @Default("SELF_ACCOUNT") Account account) { + net.tnemc.core.command.TransactionCommand.history(new SpongeCMDSource(sender), page, region, account); } - @Subcommand({"info", "i", "about", "brief"}) + @Subcommand({ "info", "i", "about", "brief" }) @Usage("Transaction.Info.Arguments") @Description("Transaction.Info.Description") @CommandPermission("tne.info.history") public void info(SpongeCommandActor sender, UUID uuid) { + net.tnemc.core.command.TransactionCommand.info(new SpongeCMDSource(sender), uuid); } - @Subcommand({"void", "retract", "undo"}) + @Subcommand({ "void", "retract", "undo" }) @Usage("Transaction.Void.Arguments") @Description("Transaction.Void.Description") @CommandPermission("tne.void.history") public void voidT(SpongeCommandActor sender, Account account, UUID uuid) { + net.tnemc.core.command.TransactionCommand.voidT(new SpongeCMDSource(sender), account, uuid); } } diff --git a/Sponge8/src/net/tnemc/sponge/impl/SpongeCurrency.java b/Sponge8/src/net/tnemc/sponge/impl/SpongeCurrency.java index d388d654..4baa7b19 100644 --- a/Sponge8/src/net/tnemc/sponge/impl/SpongeCurrency.java +++ b/Sponge8/src/net/tnemc/sponge/impl/SpongeCurrency.java @@ -35,36 +35,43 @@ public class SpongeCurrency implements Currency { private final net.tnemc.core.currency.Currency currency; public SpongeCurrency(net.tnemc.core.currency.Currency currency) { + this.currency = currency; } @Override public Component displayName() { + return Component.text(currency.getDisplay()); } @Override public Component pluralDisplayName() { + return Component.text(currency.getDisplayPlural()); } @Override public Component symbol() { + return Component.text(currency.getSymbol()); } @Override public Component format(BigDecimal amount, int numFractionDigits) { + return Component.text(CurrencyFormatter.format(null, amount)); } @Override public int defaultFractionDigits() { + return currency.getDecimalPlaces(); } @Override public boolean isDefault() { + return currency.isGlobalDefault(); } } diff --git a/Sponge8/src/net/tnemc/sponge/impl/SpongeDeletionResult.java b/Sponge8/src/net/tnemc/sponge/impl/SpongeDeletionResult.java index ba4e0c05..39cb63c5 100644 --- a/Sponge8/src/net/tnemc/sponge/impl/SpongeDeletionResult.java +++ b/Sponge8/src/net/tnemc/sponge/impl/SpongeDeletionResult.java @@ -32,11 +32,13 @@ public class SpongeDeletionResult implements AccountDeletionResultType { private final EconomyResponse response; public SpongeDeletionResult(EconomyResponse response) { + this.response = response; } @Override public boolean isSuccess() { + return response.success(); } } diff --git a/Sponge8/src/net/tnemc/sponge/impl/SpongeEconomy.java b/Sponge8/src/net/tnemc/sponge/impl/SpongeEconomy.java index 855a524f..855a524c 100644 --- a/Sponge8/src/net/tnemc/sponge/impl/SpongeEconomy.java +++ b/Sponge8/src/net/tnemc/sponge/impl/SpongeEconomy.java @@ -46,16 +46,19 @@ public class SpongeEconomy implements EconomyService { @Override public Currency defaultCurrency() { + return new SpongeCurrency(TNECore.eco().currency().getDefaultCurrency()); } @Override public boolean hasAccount(UUID identifier) { + return TNECore.eco().account().findAccount(identifier).isPresent(); } @Override public boolean hasAccount(String identifier) { + return TNECore.eco().account().findAccount(identifier).isPresent(); } @@ -80,36 +83,43 @@ public Optional findOrCreateAccount(UUID identifier) { @Override public Optional findOrCreateAccount(String identifier) { + return Optional.empty(); } @Override public Stream streamUniqueAccounts() { + return uniqueAccounts().stream(); } @Override public Collection uniqueAccounts() { + return new ArrayList<>(); } @Override public Stream streamVirtualAccounts() { + return virtualAccounts().stream(); } @Override public Collection virtualAccounts() { + return new ArrayList<>(); } @Override public AccountDeletionResultType deleteAccount(UUID identifier) { + return new SpongeDeletionResult(TNECore.eco().account().deleteAccount(identifier)); } @Override public AccountDeletionResultType deleteAccount(String identifier) { + final Optional account = TNECore.eco().account().findAccount(identifier); return new SpongeDeletionResult(TNECore.eco().account().deleteAccount(account.get().getIdentifier())); diff --git a/Sponge8/src/net/tnemc/sponge/impl/SpongeReceipt.java b/Sponge8/src/net/tnemc/sponge/impl/SpongeReceipt.java index ee660e2a..9113fc57 100644 --- a/Sponge8/src/net/tnemc/sponge/impl/SpongeReceipt.java +++ b/Sponge8/src/net/tnemc/sponge/impl/SpongeReceipt.java @@ -46,6 +46,7 @@ public class SpongeReceipt implements TransactionResult { public SpongeReceipt(net.tnemc.core.transaction.TransactionResult result, Account account, SpongeCurrency currency, BigDecimal amount, Set contexts, TransactionType type) { + this.result = result; this.account = account; this.currency = currency; @@ -56,26 +57,31 @@ public SpongeReceipt(net.tnemc.core.transaction.TransactionResult result, Accoun @Override public Account account() { + return account; } @Override public Currency currency() { + return currency; } @Override public BigDecimal amount() { + return amount; } @Override public Set contexts() { + return contexts; } @Override public ResultType result() { + if(result.isSuccessful()) { return ResultType.SUCCESS; } @@ -84,6 +90,7 @@ public ResultType result() { @Override public TransactionType type() { + return type; } } diff --git a/Sponge8/src/net/tnemc/sponge/impl/SpongeTransactionEvent.java b/Sponge8/src/net/tnemc/sponge/impl/SpongeTransactionEvent.java index ddcd7678..33694679 100644 --- a/Sponge8/src/net/tnemc/sponge/impl/SpongeTransactionEvent.java +++ b/Sponge8/src/net/tnemc/sponge/impl/SpongeTransactionEvent.java @@ -33,16 +33,19 @@ public class SpongeTransactionEvent implements EconomyTransactionEvent { private final SpongeReceipt receipt; public SpongeTransactionEvent(SpongeReceipt receipt) { + this.receipt = receipt; } @Override public TransactionResult transactionResult() { + return receipt; } @Override public Cause cause() { + return null; } } \ No newline at end of file diff --git a/Sponge8/src/net/tnemc/sponge/impl/SpongeTransferReceipt.java b/Sponge8/src/net/tnemc/sponge/impl/SpongeTransferReceipt.java index 3b8e0886..28ee8636 100644 --- a/Sponge8/src/net/tnemc/sponge/impl/SpongeTransferReceipt.java +++ b/Sponge8/src/net/tnemc/sponge/impl/SpongeTransferReceipt.java @@ -38,12 +38,14 @@ public class SpongeTransferReceipt extends SpongeReceipt implements TransferResu private final Account accountTo; public SpongeTransferReceipt(TransactionResult result, Account account, SpongeCurrency currency, BigDecimal amount, Set contexts, TransactionType type, Account accountTo) { + super(result, account, currency, amount, contexts, type); this.accountTo = accountTo; } @Override public Account accountTo() { + return accountTo; } } diff --git a/Sponge8/src/net/tnemc/sponge/impl/SpongeUniqueAccount.java b/Sponge8/src/net/tnemc/sponge/impl/SpongeUniqueAccount.java index 3c743026..36db786b 100644 --- a/Sponge8/src/net/tnemc/sponge/impl/SpongeUniqueAccount.java +++ b/Sponge8/src/net/tnemc/sponge/impl/SpongeUniqueAccount.java @@ -32,11 +32,13 @@ public class SpongeUniqueAccount extends SpongeVirtualAccount implements UniqueAccount { public SpongeUniqueAccount(PlayerAccount account) { + super(account); } @Override public UUID uniqueId() { + if(account instanceof PlayerAccount) { return ((PlayerAccount)account).getUUID(); } diff --git a/Sponge8/src/net/tnemc/sponge/impl/SpongeVirtualAccount.java b/Sponge8/src/net/tnemc/sponge/impl/SpongeVirtualAccount.java index 0e91d70b..de4d8e2f 100644 --- a/Sponge8/src/net/tnemc/sponge/impl/SpongeVirtualAccount.java +++ b/Sponge8/src/net/tnemc/sponge/impl/SpongeVirtualAccount.java @@ -57,16 +57,19 @@ public class SpongeVirtualAccount implements VirtualAccount { protected final Account account; public SpongeVirtualAccount(Account account) { + this.account = account; } @Override public Component displayName() { + return Component.text(account.getName()); } @Override public BigDecimal defaultBalance(Currency currency) { + PluginCore.log().warning("WARNING: One of your plugins is using the built-in Sponge API. Please note that this doesn't provide multi-currency support. Refer them to the TNE API: https://github.com/TheNewEconomy/EconomyCore/wiki/API#tne-api", DebugLevel.OFF); return TNECore.eco().currency().getDefaultCurrency().getStartingHoldings(); } @@ -74,19 +77,21 @@ public BigDecimal defaultBalance(Currency currency) { @Override public boolean hasBalance(Currency currency, Set contexts) { //Context: WORLD_KEY PluginCore.log().warning("WARNING: One of your plugins is using the built-in Sponge API. Please note that this doesn't provide multi-currency support. Refer them to the TNE API: https://github.com/TheNewEconomy/EconomyCore/wiki/API#tne-api", DebugLevel.OFF); - return account.getWallet().getHoldings(resolveRegion(contexts), TNECore.eco().currency().getDefaultCurrency().getUid()).isPresent(); + return account.getWallet().getHoldings(resolveRegion(contexts), TNECore.eco().currency().getDefaultCurrency().getUid()).isPresent(); } @Override public boolean hasBalance(Currency currency, Cause cause) { + PluginCore.log().warning("WARNING: One of your plugins is using the built-in Sponge API. Please note that this doesn't provide multi-currency support. Refer them to the TNE API: https://github.com/TheNewEconomy/EconomyCore/wiki/API#tne-api", DebugLevel.OFF); - return account.getWallet().getHoldings(PluginCore.server().defaultWorld(), TNECore.eco().currency().getDefaultCurrency().getUid()).isPresent(); + return account.getWallet().getHoldings(PluginCore.server().defaultWorld(), TNECore.eco().currency().getDefaultCurrency().getUid()).isPresent(); } @Override public BigDecimal balance(Currency currency, Set contexts) { + PluginCore.log().warning("WARNING: One of your plugins is using the built-in Sponge API. Please note that this doesn't provide multi-currency support. Refer them to the TNE API: https://github.com/TheNewEconomy/EconomyCore/wiki/API#tne-api", DebugLevel.OFF); - final Optional entry = account.getWallet().getHoldings(resolveRegion(contexts), TNECore.eco().currency().getDefaultCurrency().getUid()); + final Optional entry = account.getWallet().getHoldings(resolveRegion(contexts), TNECore.eco().currency().getDefaultCurrency().getUid()); if(entry.isPresent()) { return entry.get().getAmount(); } @@ -95,8 +100,9 @@ public BigDecimal balance(Currency currency, Set contexts) { @Override public BigDecimal balance(Currency currency, Cause cause) { + PluginCore.log().warning("WARNING: One of your plugins is using the built-in Sponge API. Please note that this doesn't provide multi-currency support. Refer them to the TNE API: https://github.com/TheNewEconomy/EconomyCore/wiki/API#tne-api", DebugLevel.OFF); - final Optional entry = account.getWallet().getHoldings(PluginCore.server().defaultWorld(), TNECore.eco().currency().getDefaultCurrency().getUid()); + final Optional entry = account.getWallet().getHoldings(PluginCore.server().defaultWorld(), TNECore.eco().currency().getDefaultCurrency().getUid()); if(entry.isPresent()) { return entry.get().getAmount(); } @@ -105,11 +111,13 @@ public BigDecimal balance(Currency currency, Cause cause) { @Override public Map balances(Set contexts) { + return balances(resolveRegion(contexts)); } @Override public Map balances(Cause cause) { + return balances(PluginCore.server().defaultWorld()); } @@ -119,20 +127,21 @@ public Map balances(final String region) { for(net.tnemc.core.currency.Currency cur : TNECore.eco().currency().getCurrencies(region)) { - final Optional entry = account.getWallet().getHoldings(region, cur.getUid()); - entry.ifPresent(holdingsEntry -> balances.put(new SpongeCurrency(cur), holdingsEntry.getAmount())); + final Optional entry = account.getWallet().getHoldings(region, cur.getUid()); + entry.ifPresent(holdingsEntry->balances.put(new SpongeCurrency(cur), holdingsEntry.getAmount())); } return balances; } @Override public TransactionResult setBalance(Currency currency, BigDecimal amount, Set contexts) { + PluginCore.log().warning("WARNING: One of your plugins is using the built-in Sponge API. Please note that this doesn't provide multi-currency support. Refer them to the TNE API: https://github.com/TheNewEconomy/EconomyCore/wiki/API#tne-api", DebugLevel.OFF); final HoldingsModifier modifier = new HoldingsModifier(resolveRegion(contexts), - TNECore.eco().currency().getDefaultCurrency().getUid(), - amount, - HoldingsOperation.SET); + TNECore.eco().currency().getDefaultCurrency().getUid(), + amount, + HoldingsOperation.SET); final Transaction transaction = new Transaction("set") .to(account, modifier) @@ -143,12 +152,13 @@ public TransactionResult setBalance(Currency currency, BigDecimal amount, Set resetBalances(Set contexts) { + return resetBalances(resolveRegion(contexts)); } @Override public Map resetBalances(Cause cause) { + return resetBalances(PluginCore.server().defaultWorld()); } @@ -173,9 +185,9 @@ public Map resetBalances(final String region) { for(net.tnemc.core.currency.Currency cur : TNECore.eco().currency().getCurrencies(region)) { final HoldingsModifier modifier = new HoldingsModifier(PluginCore.server().defaultWorld(), - TNECore.eco().currency().getDefaultCurrency().getUid(), - cur.getStartingHoldings(), - HoldingsOperation.SET); + TNECore.eco().currency().getDefaultCurrency().getUid(), + cur.getStartingHoldings(), + HoldingsOperation.SET); final Transaction transaction = new Transaction("set") .to(account, modifier) @@ -188,22 +200,25 @@ public Map resetBalances(final String region) { @Override public TransactionResult resetBalance(Currency currency, Set contexts) { + PluginCore.log().warning("WARNING: One of your plugins is using the built-in Sponge API. Please note that this doesn't provide multi-currency support. Refer them to the TNE API: https://github.com/TheNewEconomy/EconomyCore/wiki/API#tne-api", DebugLevel.OFF); return setBalance(currency, defaultBalance(currency), contexts); } @Override public TransactionResult resetBalance(Currency currency, Cause cause) { + PluginCore.log().warning("WARNING: One of your plugins is using the built-in Sponge API. Please note that this doesn't provide multi-currency support. Refer them to the TNE API: https://github.com/TheNewEconomy/EconomyCore/wiki/API#tne-api", DebugLevel.OFF); return setBalance(currency, defaultBalance(currency), cause); } @Override public TransactionResult deposit(Currency currency, BigDecimal amount, Set contexts) { + PluginCore.log().warning("WARNING: One of your plugins is using the built-in Sponge API. Please note that this doesn't provide multi-currency support. Refer them to the TNE API: https://github.com/TheNewEconomy/EconomyCore/wiki/API#tne-api", DebugLevel.OFF); final HoldingsModifier modifier = new HoldingsModifier(resolveRegion(contexts), - TNECore.eco().currency().getDefaultCurrency().getUid(), - amount); + TNECore.eco().currency().getDefaultCurrency().getUid(), + amount); final Transaction transaction = new Transaction("give") .to(account, modifier) @@ -213,10 +228,11 @@ public TransactionResult deposit(Currency currency, BigDecimal amount, Set contexts) { + PluginCore.log().warning("WARNING: One of your plugins is using the built-in Sponge API. Please note that this doesn't provide multi-currency support. Refer them to the TNE API: https://github.com/TheNewEconomy/EconomyCore/wiki/API#tne-api", DebugLevel.OFF); final HoldingsModifier modifier = new HoldingsModifier(resolveRegion(contexts), - TNECore.eco().currency().getDefaultCurrency().getUid(), - amount + TNECore.eco().currency().getDefaultCurrency().getUid(), + amount ); final Transaction transaction = new Transaction("take") @@ -241,10 +258,11 @@ public TransactionResult withdraw(Currency currency, BigDecimal amount, Set contexts) { + PluginCore.log().warning("WARNING: One of your plugins is using the built-in Sponge API. Please note that this doesn't provide multi-currency support. Refer them to the TNE API: https://github.com/TheNewEconomy/EconomyCore/wiki/API#tne-api", DebugLevel.OFF); final Optional toAccount = TNECore.eco().account().findAccount(to.identifier()); if(toAccount.isEmpty()) return null; final HoldingsModifier modifier = new HoldingsModifier(resolveRegion(contexts), - TNECore.eco().currency().getDefaultCurrency().getUid(), - amount + TNECore.eco().currency().getDefaultCurrency().getUid(), + amount ); final Transaction transaction = new Transaction("transfer") @@ -276,13 +295,14 @@ public TransferResult transfer(org.spongepowered.api.service.economy.account.Acc @Override public TransferResult transfer(org.spongepowered.api.service.economy.account.Account to, Currency currency, BigDecimal amount, Cause cause) { + PluginCore.log().warning("WARNING: One of your plugins is using the built-in Sponge API. Please note that this doesn't provide multi-currency support. Refer them to the TNE API: https://github.com/TheNewEconomy/EconomyCore/wiki/API#tne-api", DebugLevel.OFF); final Optional toAccount = TNECore.eco().account().findAccount(to.identifier()); if(toAccount.isEmpty()) return null; final HoldingsModifier modifier = new HoldingsModifier(PluginCore.server().defaultWorld(), - TNECore.eco().currency().getDefaultCurrency().getUid(), - amount + TNECore.eco().currency().getDefaultCurrency().getUid(), + amount ); final Transaction transaction = new Transaction("transfer") @@ -295,20 +315,23 @@ public TransferResult transfer(org.spongepowered.api.service.economy.account.Acc @Override public String identifier() { + return account.getIdentifier().toString(); } public Account getAccount() { + return account; } private String resolveRegion(final Set context) { final Optional conResolve = contextRegion(context); - return conResolve.map(s -> TNECore.eco().region().resolve(s)).orElseGet(() -> PluginCore.server().defaultWorld()); + return conResolve.map(s->TNECore.eco().region().resolve(s)).orElseGet(()->PluginCore.server().defaultWorld()); } protected SpongeTransferReceipt transaction(final org.spongepowered.api.service.economy.account.Account to, final Transaction transaction, final BigDecimal amount, final Set context, TransactionType type) { + SpongeTransferReceipt receipt; try { @@ -324,6 +347,7 @@ protected SpongeTransferReceipt transaction(final org.spongepowered.api.service. } protected SpongeReceipt transaction(final Transaction transaction, final BigDecimal amount, final Set context, TransactionType type) { + SpongeReceipt receipt; try { @@ -339,6 +363,7 @@ protected SpongeReceipt transaction(final Transaction transaction, final BigDeci } private Optional contextRegion(final Set context) { + for(Context con : context) { if(con.getKey().equalsIgnoreCase(Context.WORLD_KEY)) { return Optional.of(con.getValue()); diff --git a/Sponge8/src/net/tnemc/sponge/listeners/player/PlayerCloseInventoryListener.java b/Sponge8/src/net/tnemc/sponge/listeners/player/PlayerCloseInventoryListener.java index c4129b36..f5f12f46 100644 --- a/Sponge8/src/net/tnemc/sponge/listeners/player/PlayerCloseInventoryListener.java +++ b/Sponge8/src/net/tnemc/sponge/listeners/player/PlayerCloseInventoryListener.java @@ -42,6 +42,7 @@ public class PlayerCloseInventoryListener { private final PluginContainer plugin; public PlayerCloseInventoryListener(PluginContainer plugin) { + this.plugin = plugin; } @@ -54,7 +55,8 @@ public void onClose(InteractContainerEvent.Close event, @First ServerPlayer play } public boolean isEnderChest(Container container) { - if (container instanceof BlockCarrier) { + + if(container instanceof BlockCarrier) { Location location = ((BlockCarrier)container).location(); return location.blockEntity().isPresent() && (location.blockEntity().get() instanceof EnderChest); } diff --git a/Sponge8/src/net/tnemc/sponge/listeners/player/PlayerJoinListener.java b/Sponge8/src/net/tnemc/sponge/listeners/player/PlayerJoinListener.java index c2bc6132..e00f726a 100644 --- a/Sponge8/src/net/tnemc/sponge/listeners/player/PlayerJoinListener.java +++ b/Sponge8/src/net/tnemc/sponge/listeners/player/PlayerJoinListener.java @@ -37,13 +37,15 @@ public class PlayerJoinListener { private final PluginContainer plugin; public PlayerJoinListener(PluginContainer plugin) { + this.plugin = plugin; } @Listener public void listen(ServerSideConnectionEvent.Join event) { + final HandlerResponse handle = new PlayerJoinHandler() - .handle(new SpongePlayerProvider(event.player().user(), plugin)); + .handle(new SpongePlayerProvider(event.player().user(), plugin)); if(handle.isCancelled()) { diff --git a/Sponge8/src/net/tnemc/sponge/listeners/player/PlayerLeaveListener.java b/Sponge8/src/net/tnemc/sponge/listeners/player/PlayerLeaveListener.java index ade3f2a1..16eb7337 100644 --- a/Sponge8/src/net/tnemc/sponge/listeners/player/PlayerLeaveListener.java +++ b/Sponge8/src/net/tnemc/sponge/listeners/player/PlayerLeaveListener.java @@ -35,11 +35,13 @@ public class PlayerLeaveListener { private final PluginContainer plugin; public PlayerLeaveListener(PluginContainer plugin) { + this.plugin = plugin; } @Listener public void listen(ServerSideConnectionEvent.Disconnect event) { + new PlayerLeaveHandler().handle(new SpongePlayerProvider(event.player().user(), plugin)); } } \ No newline at end of file diff --git a/Velocity/pom.xml b/Velocity/pom.xml index e9795a6a..4758e51f 100644 --- a/Velocity/pom.xml +++ b/Velocity/pom.xml @@ -21,7 +21,6 @@ - clean package target @@ -78,7 +77,9 @@ - ${project.build.directory}/dependency-reduced-pom.xml + + ${project.build.directory}/dependency-reduced-pom.xml + net.tnemc:* diff --git a/Velocity/src/net/tnemc/velocity/VelocityCore.java b/Velocity/src/net/tnemc/velocity/VelocityCore.java index 6da3d508..17dfe3de 100644 --- a/Velocity/src/net/tnemc/velocity/VelocityCore.java +++ b/Velocity/src/net/tnemc/velocity/VelocityCore.java @@ -41,7 +41,7 @@ * @since 0.1.2.0 */ @Plugin(id = "tne_velocity", name = "The New Economy Velocity", version = "0.1.3.2", - url = "https://tnemc.net", description = "A bridge for TheNewEconomy plugin.", authors = {"creatorfromhell"}) + url = "https://tnemc.net", description = "A bridge for TheNewEconomy plugin.", authors = { "creatorfromhell" }) public class VelocityCore { private final Map backlog = new HashMap<>(); @@ -55,6 +55,7 @@ public class VelocityCore { @Inject public VelocityCore(ProxyServer server, Logger logger) { + this.server = server; this.logger = logger; instance = this; @@ -75,18 +76,22 @@ public void onInitialize(ProxyInitializeEvent event) { } public static VelocityCore instance() { + return instance; } public ProxyServer getServer() { + return server; } public Map getBacklog() { + return backlog; } public void remove(final UUID server) { + backlog.remove(server); } } \ No newline at end of file diff --git a/Velocity/src/net/tnemc/velocity/VelocityProxy.java b/Velocity/src/net/tnemc/velocity/VelocityProxy.java index f98d1b3f..76c3cfa7 100644 --- a/Velocity/src/net/tnemc/velocity/VelocityProxy.java +++ b/Velocity/src/net/tnemc/velocity/VelocityProxy.java @@ -44,6 +44,7 @@ public class VelocityProxy implements ProxyProvider { */ @Override public void sendToAll(String channel, byte[] out, boolean backlog) { + VelocityCore.instance().getServer().getAllServers().forEach(server->{ if(!server.getPlayersConnected().isEmpty()) { server.sendPluginMessage(MinecraftChannelIdentifier.from(channel), out); @@ -77,6 +78,7 @@ public void sendTo(String serverName, String channel, byte[] out) { */ @Override public void sendBacklog(@NotNull MessageData data) { + for(RegisteredServer server : VelocityCore.instance().getServer().getAllServers()) { if(server.getServerInfo().getAddress().getPort() == Integer.valueOf(data.getServerName())) { for(BacklogEntry entry : data.getBacklog()) { diff --git a/Velocity/src/net/tnemc/velocity/event/ServerPostConnectListener.java b/Velocity/src/net/tnemc/velocity/event/ServerPostConnectListener.java index 6eb2ef47..a4d638cb 100644 --- a/Velocity/src/net/tnemc/velocity/event/ServerPostConnectListener.java +++ b/Velocity/src/net/tnemc/velocity/event/ServerPostConnectListener.java @@ -32,6 +32,7 @@ * @since 0.1.2.0 */ public class ServerPostConnectListener { + @Subscribe public void handle(ServerPostConnectEvent event) { diff --git a/Velocity/src/net/tnemc/velocity/message/MessageListener.java b/Velocity/src/net/tnemc/velocity/message/MessageListener.java index 315bf7e3..f7be54e9 100644 --- a/Velocity/src/net/tnemc/velocity/message/MessageListener.java +++ b/Velocity/src/net/tnemc/velocity/message/MessageListener.java @@ -32,6 +32,7 @@ public class MessageListener { @Subscribe public void handle(PluginMessageEvent event) { + final String id = event.getIdentifier().toString(); if(!id.startsWith("tne:")) { diff --git a/changelog.md b/changelog.md index f552a5e3..c792d29d 100644 --- a/changelog.md +++ b/changelog.md @@ -1,12 +1,14 @@ # 0.1.2.0 Build 29 -- Added message for console that outlines when accounts are loaded with balances of currencies that don't exist. + +- Added message for console that outlines when accounts are loaded with balances of currencies that + don't exist. - Made default last online date be the same as creation date for player accounts - - This is now taken into account for ImportItems config in config.yml + - This is now taken into account for ImportItems config in config.yml - Add TNK Account Types for alpha testing The New Kings - - Adds Village, Kingdom, Pact, Camp types + - Adds Village, Kingdom, Pact, Camp types - Added Redis Support. This will allow data syncing without the need for bungee - Added a currency template module(requested by stoffeh) - - This contains some example pre-configured commonly used currency setups for TNE. + - This contains some example pre-configured commonly used currency setups for TNE. - Added $currency, $player variables for /money give/take messages in messages.yml - Updated Turkish Translation(thanks to Colonel Kai) - Ability to do /money give/take as a %, example /money take 20% player diff --git a/license.md b/license.md index fbb72f7c..e998b4ab 100644 --- a/license.md +++ b/license.md @@ -3,196 +3,469 @@ The New Economy is licensed under the AGPLv3, or (at your option) any later version. What this means to you in basic terms: + - Include a copy of the full license text and the original copyright notice - State all significant changes made to the original software - Make available the source code when you distribute any works based on the licensed software -- Include any installation information necessary to update and reinstall the software if the program is being used as -part of a consumer device -- If you make access to modified software available to users over a network, you must make your source code available to -those users. This means if you modify this plugin for your server, the modified source must be made public under this same -license. +- Include any installation information necessary to update and reinstall the software if the program + is being used as + part of a consumer device +- If you make access to modified software available to users over a network, you must make your + source code available to + those users. This means if you modify this plugin for your server, the modified source must be + made public under this same + license. ## Full License Text *The legal mumbo jumbo.* ### Affero GENERAL PUBLIC LICENSE + *Version 3, 19 November 2007* Copyright (C) 2007 Free Software Foundation, Inc. -Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing +it is not allowed. Preamble -The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. - -The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. - -When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. - -Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. - -A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. - -The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. - -An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. +The GNU Affero General Public License is a free, copyleft license for software and other kinds of +works, specifically designed to ensure cooperation with the community in the case of network server +software. + +The licenses for most software and other practical works are designed to take away your freedom to +share and change the works. By contrast, our General Public Licenses are intended to guarantee your +freedom to share and change all versions of a program--to make sure it remains free software for all +its users. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses +are designed to make sure that you have the freedom to distribute copies of free software (and +charge for them if you wish), that you receive source code or can get it if you want it, that you +can change the software or use pieces of it in new free programs, and that you know you can do these +things. + +Developers that use our General Public Licenses protect your rights with two steps: (1) assert +copyright on the software, and (2) offer you this License which gives you legal permission to copy, +distribute and/or modify the software. + +A secondary benefit of defending all users' freedom is that improvements made in alternate versions +of the program, if they receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and encouraged by the resulting +cooperation. However, in the case of software used on network servers, this result may fail to come +about. The GNU General Public License permits making a modified version and letting the public +access it on a server without ever releasing its source code to the public. + +The GNU Affero General Public License is designed specifically to ensure that, in such cases, the +modified source code becomes available to the community. It requires the operator of a network +server to provide the source code of the modified version running there to the users of that server. +Therefore, public use of a modified version, on a publicly accessible server, gives the public +access to the source code of the modified version. + +An older license, called the Affero General Public License and published by Affero, was designed to +accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero +has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS + 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. -"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. +"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor +masks. -"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. +"The Program" refers to any copyrightable work licensed under this License. Each licensee is +addressed as "you". "Licensees" and "recipients" may be individuals or organizations. -To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. +To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring +copyright permission, other than the making of an exact copy. The resulting work is called a " +modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. -To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. +To "propagate" a work means to do anything with it that, without permission, would make you directly +or secondarily liable for infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, distribution (with or without +modification), making available to the public, and in some countries other activities as well. -To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. +To "convey" a work means any kind of propagation that enables other parties to make or receive +copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not +conveying. -An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. +An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a +convenient and prominently visible feature that (1) displays an appropriate copyright notice, and ( +2) tells the user that there is no warranty for the work (except to the extent that warranties are +provided), that licensees may convey the work under this License, and how to view a copy of this +License. If the interface presents a list of user commands or options, such as a menu, a prominent +item in the list meets this criterion. 1. Source Code. - The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. - -A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. - -The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. - -The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. - -The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + The "source code" for a work means the preferred form of the work for making modifications to + it. "Object code" means any non-source form of a work. + +A "Standard Interface" means an interface that either is an official standard defined by a +recognized standards body, or, in the case of interfaces specified for a particular programming +language, one that is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other than the work as a whole, +that (a) is included in the normal form of packaging a Major Component, but which is not part of +that Major Component, and (b) serves only to enable use of the work with that Major Component, or to +implement a Standard Interface for which an implementation is available to the public in source code +form. A "Major Component", in this context, means a major essential component (kernel, window +system, and so on) of the specific operating system (if any) on which the executable work runs, or a +compiler used to produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all the source code needed to +generate, install, and (for an executable work) run the object code and to modify the work, +including scripts to control those activities. However, it does not include the work's System +Libraries, or general-purpose tools or generally available free programs which are used unmodified +in performing those activities but which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for the work, and the source code +for shared libraries and dynamically linked subprograms that the work is specifically designed to +require, such as by intimate data communication or control flow between those subprograms and other +parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from +other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. - All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. - -You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. - -Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + All rights granted under this License are granted for the term of copyright on the Program, and + are irrevocable provided the stated conditions are met. This License explicitly affirms your + unlimited permission to run the unmodified Program. The output from running a covered work is + covered by this License only if the output, given its content, constitutes a covered work. This + License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as +your license otherwise remains in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you with facilities for running +those works, provided that you comply with the terms of this License in conveying all material for +which you do not control copyright. Those thus making or running the covered works for you must do +so exclusively on your behalf, under your direction and control, on terms that prohibit them from +making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. +Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + No covered work shall be deemed part of an effective technological measure under any applicable + law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December + 1996, or similar laws prohibiting or restricting circumvention of such measures. -When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. +When you convey a covered work, you waive any legal power to forbid circumvention of technological +measures to the extent such circumvention is effected by exercising rights under this License with +respect to the covered work, and you disclaim any intention to limit operation or modification of +the work as a means of enforcing, against the work's users, your or third parties' legal rights to +forbid circumvention of technological measures. 4. Conveying Verbatim Copies. - You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + You may convey verbatim copies of the Program's source code as you receive it, in any medium, + provided that you conspicuously and appropriately publish on each copy an appropriate copyright + notice; keep intact all notices stating that this License and any non-permissive terms added in + accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; + and give all recipients a copy of this License along with the Program. -You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. +You may charge any price or no price for each copy that you convey, and you may offer support or +warranty protection for a fee. 5. Conveying Modified Source Versions. - You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + You may convey a work based on the Program, or the modifications to produce it from the Program, + in the form of source code under the terms of section 4, provided that you also meet all of these + conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. -b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". -c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. -d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. -A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. +b) The work must carry prominent notices stating that it is released under this License and any +conditions added under section 7. This requirement modifies the requirement in section 4 to "keep +intact all notices". +c) You must license the entire work, as a whole, under this License to anyone who comes into +possession of a copy. This License will therefore apply, along with any applicable section 7 +additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. +This License gives no permission to license the work in any other way, but it does not invalidate +such permission if you have separately received it. +d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; +however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, +your work need not make them do so. +A compilation of a covered work with other separate and independent works, which are not by their +nature extensions of the covered work, and which are not combined with it such as to form a larger +program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the +compilation and its resulting copyright are not used to limit the access or legal rights of the +compilation's users beyond what the individual works permit. Inclusion of a covered work in an +aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. - You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: - -a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. -b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. -c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. -d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. -e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. -A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. - -A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. - -"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. - -If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). - -The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. - -Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + You may convey a covered work in object code form under the terms of sections 4 and 5, provided + that you also convey the machine-readable Corresponding Source under the terms of this License, + in one of these ways: + +a) Convey the object code in, or embodied in, a physical product (including a physical distribution +medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used +for software interchange. +b) Convey the object code in, or embodied in, a physical product (including a physical distribution +medium), accompanied by a written offer, valid for at least three years and valid for as long as you +offer spare parts or customer support for that product model, to give anyone who possesses the +object code either (1) a copy of the Corresponding Source for all the software in the product that +is covered by this License, on a durable physical medium customarily used for software interchange, +for a price no more than your reasonable cost of physically performing this conveying of source, +or (2) access to copy the Corresponding Source from a network server at no charge. +c) Convey individual copies of the object code with a copy of the written offer to provide the +Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if +you received the object code with such an offer, in accord with subsection 6b. +d) Convey the object code by offering access from a designated place (gratis or for a charge), and +offer equivalent access to the Corresponding Source in the same way through the same place at no +further charge. You need not require recipients to copy the Corresponding Source along with the +object code. If the place to copy the object code is a network server, the Corresponding Source may +be on a different server (operated by you or a third party) that supports equivalent copying +facilities, provided you maintain clear directions next to the object code saying where to find the +Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated +to ensure that it is available for as long as needed to satisfy these requirements. +e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the +object code and Corresponding Source of the work are being offered to the general public at no +charge under subsection 6d. +A separable portion of the object code, whose source code is excluded from the Corresponding Source +as a System Library, need not be included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any tangible personal property +which is normally used for personal, family, or household purposes, or (2) anything designed or sold +for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful +cases shall be resolved in favor of coverage. For a particular product received by a particular +user, "normally used" refers to a typical or common use of that class of product, regardless of the +status of the particular user or of the way in which the particular user actually uses, or expects +or is expected to use, the product. A product is a consumer product regardless of whether the +product has substantial commercial, industrial or non-consumer uses, unless such uses represent the +only significant mode of use of the product. + +"Installation Information" for a User Product means any methods, procedures, authorization keys, or +other information required to install and execute modified versions of a covered work in that User +Product from a modified version of its Corresponding Source. The information must suffice to ensure +that the continued functioning of the modified object code is in no case prevented or interfered +with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User +Product, and the conveying occurs as part of a transaction in which the right of possession and use +of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of +how the transaction is characterized), the Corresponding Source conveyed under this section must be +accompanied by the Installation Information. But this requirement does not apply if neither you nor +any third party retains the ability to install modified object code on the User Product (for +example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to +provide support service, warranty, or updates for a work that has been modified or installed by the +recipient, or for the User Product in which it has been modified or installed. Access to a network +may be denied when the modification itself materially and adversely affects the operation of the +network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section +must be in a format that is publicly documented (and with an implementation available to the public +in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. - "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. - -When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. - -Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: - -a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or -b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or -c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or + "Additional permissions" are terms that supplement the terms of this License by making exceptions + from one or more of its conditions. Additional permissions that are applicable to the entire + Program shall be treated as though they were included in this License, to the extent that they + are valid under applicable law. If additional permissions apply only to part of the Program, that + part may be used separately under those permissions, but the entire Program remains governed by + this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions +from that copy, or from any part of it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place additional permissions on +material, added by you to a covered work, for which you have or can give appropriate copyright +permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you +may (if authorized by the copyright holders of that material) supplement the terms of this License +with terms: + +a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of +this License; or +b) Requiring preservation of specified reasonable legal notices or author attributions in that +material or in the Appropriate Legal Notices displayed by works containing it; or +c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions +of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or -e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or -f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. -All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. - -If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. - -Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. +e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service +marks; or +f) Requiring indemnification of licensors and authors of that material by anyone who conveys the +material (or modified versions of it) with contractual assumptions of liability to the recipient, +for any liability that these contractual assumptions directly impose on those licensors and authors. +All other non-permissive additional terms are considered "further restrictions" within the meaning +of section 10. If the Program as you received it, or any part of it, contains a notice stating that +it is governed by this License along with a term that is a further restriction, you may remove that +term. If a license document contains a further restriction but permits relicensing or conveying +under this License, you may add to a covered work material governed by the terms of that license +document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant +source files, a statement of the additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written +license, or stated as exceptions; the above requirements apply either way. 8. Termination. - You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). - -However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. - -Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. - -Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + You may not propagate or modify a covered work except as expressly provided under this License. + Any attempt otherwise to propagate or modify it is void, and will automatically terminate your + rights under this License (including any patent licenses granted under the third paragraph of + section 11). + +However, if you cease all violation of this License, then your license from a particular copyright +holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally +terminates your license, and (b) permanently, if the copyright holder fails to notify you of the +violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright +holder notifies you of the violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that copyright holder, and you cure +the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have +received copies or rights from you under this License. If your rights have been terminated and not +permanently reinstated, you do not qualify to receive new licenses for the same material under +section 10. 9. Acceptance Not Required for Having Copies. - You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + You are not required to accept this License in order to receive or run a copy of the Program. + Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer + transmission to receive a copy likewise does not require acceptance. However, nothing other than + this License grants you permission to propagate or modify any covered work. These actions + infringe copyright if you do not accept this License. Therefore, by modifying or propagating a + covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. - Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. - -An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. - -You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + Each time you convey a covered work, the recipient automatically receives a license from the + original licensors, to run, modify and propagate that work, subject to this License. You are not + responsible for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an organization, or substantially +all assets of one, or subdividing an organization, or merging organizations. If propagation of a +covered work results from an entity transaction, each party to that transaction who receives a copy +of the work also receives whatever licenses to the work the party's predecessor in interest had or +could give under the previous paragraph, plus a right to possession of the Corresponding Source of +the work from the predecessor in interest, if the predecessor has it or can get it with reasonable +efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under +this License. For example, you may not impose a license fee, royalty, or other charge for exercise +of rights granted under this License, and you may not initiate litigation (including a cross-claim +or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, +offering for sale, or importing the Program or any portion of it. 11. Patents. - A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". - -A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. - -Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. - -In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. - -If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. - -If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. - -A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. - -Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + A "contributor" is a copyright holder who authorizes use under this License of the Program or a + work on which the Program is based. The work thus licensed is called the contributor's " + contributor version". + +A contributor's "essential patent claims" are all patent claims owned or controlled by the +contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, +permitted by this License, of making, using, or selling its contributor version, but do not include +claims that would be infringed only as a consequence of further modification of the contributor +version. For purposes of this definition, "control" includes the right to grant patent sublicenses +in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the +contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, +modify and propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express agreement or commitment, +however denominated, not to enforce a patent (such as an express permission to practice a patent or +covenant not to sue for patent infringement). To "grant" such a patent license to a party means to +make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of +the work is not available for anyone to copy, free of charge and under the terms of this License, +through a publicly available network server or other readily accessible means, then you must +either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of +the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent +with the requirements of this License, to extend the patent license to downstream recipients. " +Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying +the covered work in a country, or your recipient's use of the covered work in a country, would +infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate +by procuring conveyance of, a covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of +the covered work, then the patent license you grant is automatically extended to all recipients of +the covered work and works based on it. + +A patent license is "discriminatory" if it does not include within the scope of its coverage, +prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that +are specifically granted under this License. You may not convey a covered work if you are a party to +an arrangement with a third party that is in the business of distributing software, under which you +make payment to the third party based on the extent of your activity of conveying the work, and +under which the third party grants, to any of the parties who would receive the covered work from +you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by +you (or copies made from those copies), or (b) primarily for and in connection with specific +products or compilations that contain the covered work, unless you entered into that arrangement, or +that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other +defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. - If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + If conditions are imposed on you (whether by court order, agreement or otherwise) that + contradict the conditions of this License, they do not excuse you from the conditions of this + License. If you cannot convey a covered work so as to satisfy simultaneously your obligations + under this License and any other pertinent obligations, then as a consequence you may not convey + it at all. For example, if you agree to terms that obligate you to collect a royalty for further + conveying from those to whom you convey the Program, the only way you could satisfy both those + terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. - Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. - -Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. + Notwithstanding any other provision of this License, if you modify the Program, your modified + version must prominently offer all users interacting with it remotely through a computer + network (if your version supports such interaction) an opportunity to receive the Corresponding + Source of your version by providing access to the Corresponding Source from a network server at + no charge, through some standard or customary means of facilitating copying of software. This + Corresponding Source shall include the Corresponding Source for any work covered by version 3 of + the GNU General Public License that is incorporated pursuant to the following paragraph. + +Notwithstanding any other provision of this License, you have permission to link or combine any +covered work with a work licensed under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this License will continue to apply to +the part which is the covered work, but the work with which it is combined will remain governed by +version 3 of the GNU General Public License. 14. Revised Versions of this License. - The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + The Free Software Foundation may publish revised and/or new versions of the GNU Affero General + Public License from time to time. Such new versions will be similar in spirit to the present + version, but may differ in detail to address new problems or concerns. -Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. +Each version is given a distinguishing version number. If the Program specifies that a certain +numbered version of the GNU Affero General Public License "or any later version" applies to it, you +have the option of following the terms and conditions either of that numbered version or of any +later version published by the Free Software Foundation. If the Program does not specify a version +number of the GNU Affero General Public License, you may choose any version ever published by the +Free Software Foundation. -If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. +If the Program specifies that a proxy can decide which future versions of the GNU Affero General +Public License can be used, that proxy's public statement of acceptance of a version permanently +authorizes you to choose that version for the Program. -Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. +Later license versions may give you additional or different permissions. However, no additional +obligations are imposed on any author or copyright holder as a result of your choosing to follow a +later version. 15. Disclaimer of Warranty. - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN + OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS + IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, + THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK + AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE + DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, + OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU + FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF + THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING + RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO + OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE + POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. - If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + If the disclaimer of warranty and limitation of liability provided above cannot be given local + legal effect according to their terms, reviewing courts shall apply local law that most closely + approximates an absolute waiver of all civil liability in connection with the Program, unless a + warranty or assumption of liability accompanies a copy of the Program in return for a fee. diff --git a/pom.xml b/pom.xml index b2086fbd..b0c6f3db 100644 --- a/pom.xml +++ b/pom.xml @@ -1,4 +1,6 @@ - + 4.0.0 net.tnemc TNE diff --git a/resource.md b/resource.md index 0b4b5b40..982def60 100644 --- a/resource.md +++ b/resource.md @@ -1,9 +1,12 @@ # The New Economy + [![Codacy Badge](https://app.codacy.com/project/badge/Grade/246101510dca4eb9a729ef178dae682c)](https://app.codacy.com/gh/TheNewEconomy/EconomyCore/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_grade) [![Build Status](https://ci.codemc.io/job/creatorfromhell/job/TNE/badge/icon)](https://ci.codemc.io/job/creatorfromhell/job/TNE/) -The New Economy, TNE, is the ultimate economy plugin for your Minecraft server, no matter what platform you're on. While -TNE is pushed as being "feature-packed," but it's not feature-packed in the normal sense of jamming a bunch of useless features +The New Economy, TNE, is the ultimate economy plugin for your Minecraft server, no matter what +platform you're on. While +TNE is pushed as being "feature-packed," but it's not feature-packed in the normal sense of jamming +a bunch of useless features into the core plugin, but rather using modules.

@@ -14,20 +17,27 @@ into the core plugin, but rather using modules.

# About TNE -TNE was originally created for hey0's hMod long before Bukkit/Spigot/Paper was a thing. Since then, it has taken on many -forms and this is the future form of the plugin. This core is designed to be robust and carry TNE into the future with or + +TNE was originally created for hey0's hMod long before Bukkit/Spigot/Paper was a thing. Since then, +it has taken on many +forms and this is the future form of the plugin. This core is designed to be robust and carry TNE +into the future with or without Minecraft by not being platform-dependent. # Requirements + TNE has some minimum requirements that should be followed. + - MySQL 8.0+ (if using MySQL for storage) - MariaDB 10.7.0+ - Java 17+ # Switched? + - Converter Coming Soon! Take the poll: [here](https://strawpoll.com/4xw9gxag) # Support + To get an actual response use a support method below, not the reviews. - [Developer API Docs](https://github.com/TheNewEconomy/EconomyCore/wiki/API) @@ -37,43 +47,57 @@ To get an actual response use a support method below, not the reviews. # Features ## Menu System + Want to use menus for currency creation and player actions? We got you! ### MyBal for Players + ![mybal gif](https://raw.githubusercontent.com/TheNewEconomy/EconomyCore/main/mybal.gif) ### MyEco for Admins + ![myeco gif](https://raw.githubusercontent.com/TheNewEconomy/EconomyCore/main/myeco.gif) ## Support your favorite plugins -We provide support for all your favorite plugins from Towny to Factions. Anything that supports Vault, supports TNE! + +We provide support for all your favorite plugins from Towny to Factions. Anything that supports +Vault, supports TNE! ## Cross-Server + We support cross-server balance syncing through our velocity and bungee plugins, as well as Redis! ### Bungee + Download: [here](https://cdn.modrinth.com/data/bZ4eSWf0/versions/OTwQFFn1/TNE-BungeeCore-0.1.2.8-Release-1.jar) ### Velocity + Download: [here](https://cdn.modrinth.com/data/bZ4eSWf0/versions/prNGjbjv/TNE-VelocityCore-0.1.2.8-Release-1.jar) ## Updates + We continue to develop updates for TNE for free, and fix bugs as they're reported. ## All the currencies - Unlimited + TNE Allows you to create unlimited currencies with ease through the currency creation GUI. ### Types + TNE Supports different types of currencies! #### Virtual: Simple currency that exists in thin air #### Item: Use minecraft items as currency. + - Shulker Box Support - Bundle Support ### Fine Tune your Currency + Lots of per-currency configuration options. + - Create a custom balance format for each currency - Set a starting amount for each currency - Set custom conversion rates for each currency @@ -86,125 +110,141 @@ Lots of per-currency configuration options. - Allows for use of model data items as currency items ### Fine Tune Who Can Access What Currency -TNE allows you to fine tune who can run commands with each currency. You're able to block players from using + +TNE allows you to fine tune who can run commands with each currency. You're able to block players +from using /pay for certain currencies, and even checking their balance for others! #### Mixed: This type uses both virtual and item balances, and allows players to switch their balance between items and virtual whenever! #### Experience: Use experience as currency. + #### Experience-level: Use experience levels as currency. ## Money Notes + Convert your virtual currency into a physical money note using the /money note command. ## Multi-platform -Use Sponge? Sure. Paper? Why not? Both? Over Velocity? Definitely! Switch between, your TNE data works + +Use Sponge? Sure. Paper? Why not? Both? Over Velocity? Definitely! Switch between, your TNE data +works for you no matter your platform. More platforms soon! ### Supported: + - Paper/Spigot/Purpur - Sponge8 ### Coming: + - Fabric - Sponge7 ## Discord Server + We have a discord server available to those users that have questions or need support! ## Configurability -TNE strives to allow you to configure things as much as possible. From the messages to starting money, to max holdings! + +TNE strives to allow you to configure things as much as possible. From the messages to starting +money, to max holdings! ## MISC Features + - Adventure Chat support for translations to allow for awesome colorful messages! - Support for Placeholders, include top 10 - Easy commands for easy administration - Transaction Logging - Easy-to-use menu system for currency creation and balance actions! - Multiple data types - - SQL, YAML, and Maria DB + - SQL, YAML, and Maria DB - Tab completion for commands! - baltop command ## Open Source + Contribute on the [github](https://github.com/TheNewEconomy/EconomyCore)! ## Placeholders -| Name | Description | -|-------------------------------------------------------|----------------------------------------------------------------| -| tne_balance | Returns player's balance. | -| tne_balance_formatted | Returns formatted player's balance. | -| tne_world_worldname | returns player's balance for specific world. | -| tne_world_worldname_formatted | returns the formatted player's balance for specific world. | -| tne_currency_currencyname | returns player's balance for specific currency. | -| tne_currency_currencyname_formatted | returns player's balance for specific currency. | -| tne_wcur_worldname_currencyname | returns player's balance for specific world and currency. | -| tne_wcur_worldname_currencyname_formatted | returns player's balance for specific world and currency. | -| tne_toppos | returns player's position on baltop | -| tne_toppos_world name or all | returns player's balance for specific currency. | -| tne_toppos_world name or all_currency name or all | returns player's balance for specific world and currency. | -| tne_toppos_\_position\_ | returns the value for the position based on the value of Messages.Money.PlaceholderTopEntry in messages.yml | +| Name | Description | +|---------------------------------------------------|-------------------------------------------------------------------------------------------------------------| +| tne_balance | Returns player's balance. | +| tne_balance_formatted | Returns formatted player's balance. | +| tne_world_worldname | returns player's balance for specific world. | +| tne_world_worldname_formatted | returns the formatted player's balance for specific world. | +| tne_currency_currencyname | returns player's balance for specific currency. | +| tne_currency_currencyname_formatted | returns player's balance for specific currency. | +| tne_wcur_worldname_currencyname | returns player's balance for specific world and currency. | +| tne_wcur_worldname_currencyname_formatted | returns player's balance for specific world and currency. | +| tne_toppos | returns player's position on baltop | +| tne_toppos_world name or all | returns player's balance for specific currency. | +| tne_toppos_world name or all_currency name or all | returns player's balance for specific world and currency. | +| tne_toppos_\_position\_ | returns the value for the position based on the value of Messages.Money.PlaceholderTopEntry in messages.yml | ## Permissions & Commands ## /tne + **About:** All commands that are designated as being for administrative purposes. **Shortcuts:** /tne menu(/ecomenu), /tne(/ecomin, /ecoadmin, /ecomanage, /tneneweconomy) **Base node:** tne.admin (default: ops) **Wildcard node:** tne.admin.* -| Command | Permission | Description | Default | -|-----------------------------------|-------------------|-----------------------------------------------------------------------------------------------------------|---------------| -| tne backup | tne.admin.backup | Creates a backup of all server data. | ops | -| tne create \ \[balance\] | tne.admin.create | Creates a new economy account. Player ~ The account owner. Balance ~ The starting balance of the account. | ops | -| tne debug \[level\] | tne.admin.debug | Toggles console debug mode to the specified level. | ops | -| tne delete \ | tne.admin.delete | Deletes a player account. Player ~ The account owner. | ops | -| tne extract | tne.admin.extract | Extracts all player balances with their username attached for database related debugging. | ops | -| tne menu | tne.admin.menu | Opens up the tne economy admin menu | ops | -| tne purge | tne.admin.purge | Deletes all player accounts that have the default balance | ops | -| tne reload \[configs\] | tne.admin.reload | Used to reload configurations. | ops | -| tne reset | tne.admin.reset | Deletes all economy-related data from the database. | ops | -| tne restore | tne.admin.restore | Restores all balances that are located in extracted.yml after performing the extract command. | ops | -| tne save | tne.admin.save | Force saves all TNE data. | ops | -| tne status \ \[status\] | tne.admin.status | Displays, or sets, the current account status of an account. Player ~ The account owner. | ops | -| tne version | tne.admin.version | Displays the version of TNE currently running. | ops | +| Command | Permission | Description | Default | +|-----------------------------------|-------------------|-----------------------------------------------------------------------------------------------------------|---------| +| tne backup | tne.admin.backup | Creates a backup of all server data. | ops | +| tne create \ \[balance\] | tne.admin.create | Creates a new economy account. Player ~ The account owner. Balance ~ The starting balance of the account. | ops | +| tne debug \[level\] | tne.admin.debug | Toggles console debug mode to the specified level. | ops | +| tne delete \ | tne.admin.delete | Deletes a player account. Player ~ The account owner. | ops | +| tne extract | tne.admin.extract | Extracts all player balances with their username attached for database related debugging. | ops | +| tne menu | tne.admin.menu | Opens up the tne economy admin menu | ops | +| tne purge | tne.admin.purge | Deletes all player accounts that have the default balance | ops | +| tne reload \[configs\] | tne.admin.reload | Used to reload configurations. | ops | +| tne reset | tne.admin.reset | Deletes all economy-related data from the database. | ops | +| tne restore | tne.admin.restore | Restores all balances that are located in extracted.yml after performing the extract command. | ops | +| tne save | tne.admin.save | Force saves all TNE data. | ops | +| tne status \ \[status\] | tne.admin.status | Displays, or sets, the current account status of an account. Player ~ The account owner. | ops | +| tne version | tne.admin.version | Displays the version of TNE currently running. | ops | ## /money + **About:** All commands that are used to interact with the server's money system. -**Shortcuts:** /money balance(/bal, /balance), /money pay(/pay), /money top(/baltop), /money menu(/mybal) +**Shortcuts:** /money balance(/bal, /balance), /money pay(/pay), /money top(/baltop), /money menu( +/mybal) **Base node:** tne.money (default: everyone) **Wildcard node:** tne.money.* -| Command | Permission | Description | Default | -|------------------------------------------------------------|-----------------------|----------------------------------------------------------------------------------------|---------------| +| Command | Permission | Description | Default | +|------------------------------------------------------------|-----------------------|----------------------------------------------------------------------------------------|----------| | money balmenu | tne.money.mybal | Opens up the mybal menu. | everyone | | money balance \[world\] \[currency\] | tne.money.balance | Displays your current holdings. | everyone | | money convert \ \ \[from currency\] | tne.money.convert | Convert some of your holdings to another currency. | everyone | | money deposit \ \[currency\] | tne.money.deposit | Deposits money from an item form into a virtual bank for mixed currencies. | everyone | -| money give \ \ \[world\] \[currency\] | tne.money.give | Adds money into your economy, and gives it to a player. | ops | -| money givenote \ \ \[currency\] | tne.money.givenote | Gives the specified player a currency note for the specified amount. | ops | +| money give \ \ \[world\] \[currency\] | tne.money.give | Adds money into your economy, and gives it to a player. | ops | +| money givenote \ \ \[currency\] | tne.money.givenote | Gives the specified player a currency note for the specified amount. | ops | | money note \ \[currency\] | tne.money.note | Makes your virtual currency physical, for storage/trading purposes. | everyone | | money other \ \[world\] \[currency\] | tne.money.other | Retrieves the balance of a player. | everyone | | money pay \ \ \[currency\] | tne.money.pay | Use some of your holdings to pay another player. | everyone | | money request \ \ \[currency\] | tne.money.request | Request money from a player. | -| money set \ \ \[world\] \[currency\] | tne.money.set | Set the holdings of a player. | ops | -| money setall \ \[world\] \[currency\] | tne.money.setall | Set the holdings of all players. | ops | -| money take \ \ \[world\] \[currency\] | tne.money.take | Removes money from your economy, specifically from a player's balance. | ops | -| money top \[page\] | tne.money.top | A list of players with the highest balances. | ops | -| money top \[page\] \[refresh\(true/false\)\] | tne.money.top.refresh | This permission allows the user to include the refresh argument to refresh the baltop. | ops | -| money withdraw \ \[currency\] | tne.money.withdraw | Withdraws money from your virtual balance into its item form. | ops | +| money set \ \ \[world\] \[currency\] | tne.money.set | Set the holdings of a player. | ops | +| money setall \ \[world\] \[currency\] | tne.money.setall | Set the holdings of all players. | ops | +| money take \ \ \[world\] \[currency\] | tne.money.take | Removes money from your economy, specifically from a player's balance. | ops | +| money top \[page\] | tne.money.top | A list of players with the highest balances. | ops | +| money top \[page\] \[refresh\(true/false\)\] | tne.money.top.refresh | This permission allows the user to include the refresh argument to refresh the baltop. | ops | +| money withdraw \ \[currency\] | tne.money.withdraw | Withdraws money from your virtual balance into its item form. | ops | ## /transaction + **About:** All commands that are used to interact with the transaction system. **Shortcuts:** /trans **Base node:** tne.transaction (default: everyone) **Wildcard node:** tne.transaction.* - -| Command | Permission | Description | Default | -|--------------------------------------------------------------------|---------------------------------------------------------|---------------------------------------------------------------------------------------|---------------| -| transaction away \[page #\] | tne.transaction.away | Displays transactions that you missed since the last time you were on. | everyone | -| transaction history \[player:name\] \[page:#\] \[world:name/all\] | tne.transaction.history / tne.transaction.history.other | See a detailed break down of your transaction history. Page ~ The page number you wish to view. World ~ The world name you wish to filter, or all for every world. Defaults to current world. | everyone | -| transaction info \ | tne.transaction.info | Displays information about a transaction. UUID ~ The id of the transaction. | everyone | -| transaction void \ | tne.transaction.void | Undoes a previously completed transaction. UUID ~ The id of the transaction. | ops | \ No newline at end of file +| Command | Permission | Description | Default | +|-------------------------------------------------------------------|---------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------| +| transaction away \[page #\] | tne.transaction.away | Displays transactions that you missed since the last time you were on. | everyone | +| transaction history \[player:name\] \[page:#\] \[world:name/all\] | tne.transaction.history / tne.transaction.history.other | See a detailed break down of your transaction history. Page ~ The page number you wish to view. World ~ The world name you wish to filter, or all for every world. Defaults to current world. | everyone | +| transaction info \ | tne.transaction.info | Displays information about a transaction. UUID ~ The id of the transaction. | everyone | +| transaction void \ | tne.transaction.void | Undoes a previously completed transaction. UUID ~ The id of the transaction. | ops | \ No newline at end of file