Migrate to new Vault provider and economy integration (#3975)

This commit:
- Implements a new provider for VaultAPI's `Economy`
  - The legacy provider built into Vault uses player names, and has not changed since Vault was invented in 1864.
  - This properly supports UUIDs and works more predictably with EssentialsX.
- Replaces the Register method economy abstraction layer abstraction layer with a new `EconomyLayer` economy abstraction layer abstraction layer.
  - This opens the pathway for future economy abstraction layers to be supported.
  - This change also removes dubiously-licensed code from the project.

For users encountering userdata issues on this build, see this FAQ entry:
https://github.com/EssentialsX/Essentials/issues/3956#issuecomment-779254544

Fixes #4110.
Closes #3344.
Closes #2401.
This commit is contained in:
Josh Roy 2021-05-10 15:36:09 -04:00 committed by GitHub
parent 8b23c2c4cd
commit 071f99560e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 666 additions and 838 deletions

View File

@ -22,6 +22,8 @@ import com.earth2me.essentials.commands.IEssentialsCommand;
import com.earth2me.essentials.commands.NoChargeException;
import com.earth2me.essentials.commands.NotEnoughArgumentsException;
import com.earth2me.essentials.commands.QuietAbortException;
import com.earth2me.essentials.economy.EconomyLayers;
import com.earth2me.essentials.economy.vault.VaultEconomyProvider;
import com.earth2me.essentials.items.AbstractItemDb;
import com.earth2me.essentials.items.CustomItemResolver;
import com.earth2me.essentials.items.FlatItemDb;
@ -29,7 +31,6 @@ import com.earth2me.essentials.items.LegacyItemDb;
import com.earth2me.essentials.metrics.MetricsWrapper;
import com.earth2me.essentials.perm.PermissionsDefaults;
import com.earth2me.essentials.perm.PermissionsHandler;
import com.earth2me.essentials.register.payment.Methods;
import com.earth2me.essentials.signs.SignBlockListener;
import com.earth2me.essentials.signs.SignEntityListener;
import com.earth2me.essentials.signs.SignPlayerListener;
@ -98,6 +99,7 @@ import org.bukkit.plugin.InvalidDescriptionException;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.ServicePriority;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.java.JavaPluginLoader;
import org.bukkit.scheduler.BukkitScheduler;
@ -158,8 +160,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
private transient Map<String, IEssentialsCommand> commandMap = new HashMap<>();
static {
// TODO: improve legacy code
Methods.init();
EconomyLayers.init();
}
public Essentials() {
@ -204,6 +205,12 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
kits = new Kits(this);
}
@Override
public void onLoad() {
// Vault registers their Essentials provider at low priority, so we have to use normal priority here
getServer().getServicesManager().register(net.milkbowl.vault.economy.Economy.class, new VaultEconomyProvider(this), this, ServicePriority.Normal);
}
@Override
public void onEnable() {
try {

View File

@ -1,6 +1,7 @@
package com.earth2me.essentials;
import com.earth2me.essentials.register.payment.Methods;
import com.earth2me.essentials.economy.EconomyLayer;
import com.earth2me.essentials.economy.EconomyLayers;
import net.ess3.api.IEssentials;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
@ -12,9 +13,19 @@ import java.util.logging.Level;
public class EssentialsPluginListener implements Listener, IConf {
private final transient IEssentials ess;
private boolean serverLoaded = false;
public EssentialsPluginListener(final IEssentials ess) {
this.ess = ess;
// Run on first server tick
ess.scheduleSyncDelayedTask(() -> {
if (EconomyLayers.getSelectedLayer() == null || serverLoaded) {
return;
}
serverLoaded = true;
EconomyLayers.onServerLoad();
});
}
@EventHandler(priority = EventPriority.MONITOR)
@ -25,8 +36,9 @@ public class EssentialsPluginListener implements Listener, IConf {
ess.getPermissionsHandler().setUseSuperperms(ess.getSettings().useBukkitPermissions());
ess.getPermissionsHandler().checkPermissions();
ess.getAlternativeCommandsHandler().addPlugin(event.getPlugin());
if (!Methods.hasMethod() && Methods.setMethod(ess.getServer().getPluginManager())) {
ess.getLogger().log(Level.INFO, "Payment method found (" + Methods.getMethod().getLongName() + " version: " + Methods.getMethod().getVersion() + ")");
final EconomyLayer layer = EconomyLayers.onPluginEnable(event.getPlugin());
if (layer != null) {
ess.getLogger().log(Level.INFO, "Essentials found a compatible payment resolution method: " + layer.getName() + " (v" + layer.getPluginVersion() + ")!");
}
}
@ -37,10 +49,13 @@ public class EssentialsPluginListener implements Listener, IConf {
}
ess.getPermissionsHandler().checkPermissions();
ess.getAlternativeCommandsHandler().removePlugin(event.getPlugin());
// Check to see if the plugin thats being disabled is the one we are using
if (Methods.hasMethod() && Methods.checkDisabled(event.getPlugin())) {
Methods.reset();
ess.getLogger().log(Level.INFO, "Payment method was disabled. No longer accepting payments.");
if (EconomyLayers.onPluginDisable(event.getPlugin(), serverLoaded)) {
final EconomyLayer layer = EconomyLayers.getSelectedLayer();
if (layer != null) {
ess.getLogger().log(Level.INFO, "Essentials found a new compatible payment resolution method: " + layer.getName() + " (v" + layer.getPluginVersion() + ")!");
} else {
ess.getLogger().log(Level.INFO, "Active payment resolution method has been disabled! Falling back to Essentials' default payment resolution system!");
}
}
}

View File

@ -1,10 +1,10 @@
package com.earth2me.essentials;
import com.earth2me.essentials.commands.IEssentialsCommand;
import com.earth2me.essentials.economy.EconomyLayer;
import com.earth2me.essentials.economy.EconomyLayers;
import com.earth2me.essentials.messaging.IMessageRecipient;
import com.earth2me.essentials.messaging.SimpleMessageRecipient;
import com.earth2me.essentials.register.payment.Method;
import com.earth2me.essentials.register.payment.Methods;
import com.earth2me.essentials.utils.DateUtil;
import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.FormatUtil;
@ -485,16 +485,9 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
}
return BigDecimal.ZERO;
}
if (Methods.hasMethod()) {
try {
final Method method = Methods.getMethod();
if (!method.hasAccount(this.getName())) {
throw new Exception();
}
final Method.MethodAccount account = Methods.getMethod().getAccount(this.getName());
return BigDecimal.valueOf(account.balance());
} catch (final Exception ignored) {
}
final EconomyLayer layer = EconomyLayers.getSelectedLayer();
if (layer != null && (layer.hasAccount(getBase()) || layer.createPlayerAccount(getBase()))) {
return layer.getBalance(getBase());
}
return super.getMoney();
}
@ -512,31 +505,22 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
ess.getServer().getPluginManager().callEvent(updateEvent);
final BigDecimal newBalance = updateEvent.getNewBalance();
if (Methods.hasMethod()) {
try {
final Method method = Methods.getMethod();
if (!method.hasAccount(this.getName())) {
throw new Exception();
}
final Method.MethodAccount account = Methods.getMethod().getAccount(this.getName());
account.set(newBalance.doubleValue());
} catch (final Exception ignored) {
}
final EconomyLayer layer = EconomyLayers.getSelectedLayer();
if (layer != null && (layer.hasAccount(getBase()) || layer.createPlayerAccount(getBase()))) {
layer.set(getBase(), newBalance);
}
super.setMoney(newBalance, true);
Trade.log("Update", "Set", "API", getName(), new Trade(newBalance, ess), null, null, null, newBalance, ess);
}
public void updateMoneyCache(final BigDecimal value) {
if (ess.getSettings().isEcoDisabled()) {
if (ess.getSettings().isEcoDisabled() || !EconomyLayers.isLayerSelected() || super.getMoney().equals(value)) {
return;
}
if (Methods.hasMethod() && !super.getMoney().equals(value)) {
try {
super.setMoney(value, false);
} catch (final MaxMoneyException ex) {
// We don't want to throw any errors here, just updating a cache
}
try {
super.setMoney(value, false);
} catch (final MaxMoneyException ex) {
// We don't want to throw any errors here, just updating a cache
}
}
@ -629,7 +613,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
}
}
if (getJailTimeout() < currentTime && isJailed() ) {
if (getJailTimeout() < currentTime && isJailed()) {
final JailStatusChangeEvent event = new JailStatusChangeEvent(this, null, false);
ess.getServer().getPluginManager().callEvent(event);
@ -724,9 +708,9 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
final long autoafkkick = ess.getSettings().getAutoAfkKick();
if (autoafkkick > 0
&& lastActivity > 0 && (lastActivity + (autoafkkick * 1000)) < System.currentTimeMillis()
&& !isAuthorized("essentials.kick.exempt")
&& !isAuthorized("essentials.afk.kickexempt")) {
&& lastActivity > 0 && (lastActivity + (autoafkkick * 1000)) < System.currentTimeMillis()
&& !isAuthorized("essentials.kick.exempt")
&& !isAuthorized("essentials.afk.kickexempt")) {
final String kickReason = tl("autoAfkKickReason", autoafkkick / 60.0);
lastActivity = 0;
this.getBase().kickPlayer(kickReason);

View File

@ -130,7 +130,7 @@ public class UserMap extends CacheLoader<String, User> implements IConf {
if (!names.containsKey(keyName)) {
names.put(keyName, uuid);
uuidMap.writeUUIDMap();
} else if (!names.get(keyName).equals(uuid)) {
} else if (!isUUIDMatch(uuid, keyName)) {
if (replace) {
ess.getLogger().info("Found new UUID for " + name + ". Replacing " + names.get(keyName).toString() + " with " + uuid.toString());
names.put(keyName, uuid);
@ -143,6 +143,10 @@ public class UserMap extends CacheLoader<String, User> implements IConf {
}
}
public boolean isUUIDMatch(final UUID uuid, final String name) {
return names.containsKey(name) && names.get(name).equals(uuid);
}
@Override
public User load(final String stringUUID) throws Exception {
final UUID uuid = UUID.fromString(stringUUID);

View File

@ -178,10 +178,11 @@ public class Economy {
* @param balance The balance you want to set
* @throws UserDoesNotExistException If a user by that name does not exists
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws MaxMoneyException If this transaction has but the user over the maximum amount of money
* @deprecated Use {@link Economy#setMoney(UUID, BigDecimal)} or {@link Economy#setMoney(User, BigDecimal)}
*/
@Deprecated
public static void setMoney(final String name, final double balance) throws UserDoesNotExistException, NoLoanPermittedException {
public static void setMoney(final String name, final double balance) throws UserDoesNotExistException, NoLoanPermittedException, MaxMoneyException {
try {
setMoney(name, BigDecimal.valueOf(balance));
} catch (final ArithmeticException e) {
@ -196,10 +197,11 @@ public class Economy {
* @param balance The balance you want to set
* @throws UserDoesNotExistException If a user by that name does not exist
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws MaxMoneyException If this transaction has but the user over the maximum amount of money
* @deprecated Usernames can change use {@link Economy#setMoney(UUID, BigDecimal)} or {@link Economy#setMoney(User, BigDecimal)}
*/
@Deprecated
public static void setMoney(final String name, final BigDecimal balance) throws UserDoesNotExistException, NoLoanPermittedException {
public static void setMoney(final String name, final BigDecimal balance) throws UserDoesNotExistException, NoLoanPermittedException, MaxMoneyException {
final User user = getUserByName(name);
if (user == null) {
throw new UserDoesNotExistException(name);
@ -214,8 +216,9 @@ public class Economy {
* @param balance The balance you want to set
* @throws UserDoesNotExistException If a user by that uuid does not exist
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws MaxMoneyException If this transaction has but the user over the maximum amount of money
*/
public static void setMoney(final UUID uuid, final BigDecimal balance) throws NoLoanPermittedException, UserDoesNotExistException {
public static void setMoney(final UUID uuid, final BigDecimal balance) throws NoLoanPermittedException, UserDoesNotExistException, MaxMoneyException {
final User user = getUserByUUID(uuid);
if (user == null) {
throw new UserDoesNotExistException(uuid);
@ -229,8 +232,9 @@ public class Economy {
* @param user User
* @param balance The balance you want to set
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws MaxMoneyException If this transaction has but the user over the maximum amount of money
*/
public static void setMoney(final User user, final BigDecimal balance) throws NoLoanPermittedException {
public static void setMoney(final User user, final BigDecimal balance) throws NoLoanPermittedException, MaxMoneyException {
if (user == null) {
throw new IllegalArgumentException("Economy user cannot be null");
}
@ -240,11 +244,7 @@ public class Economy {
if (balance.signum() < 0 && !user.isAuthorized("essentials.eco.loan")) {
throw new NoLoanPermittedException();
}
try {
user.setMoney(balance, UserBalanceUpdateEvent.Cause.API);
} catch (final MaxMoneyException ex) {
//TODO: Update API to show max balance errors
}
user.setMoney(balance, UserBalanceUpdateEvent.Cause.API);
Trade.log("API", "Set", "API", user.getName(), new Trade(balance, ess), null, null, null, balance, ess);
}
@ -257,9 +257,10 @@ public class Economy {
* @param amount The money you want to add
* @throws UserDoesNotExistException If a user by that name does not exists
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws MaxMoneyException If this transaction has but the user over the maximum amount of money
*/
@Deprecated
public static void add(final String name, final double amount) throws UserDoesNotExistException, NoLoanPermittedException {
public static void add(final String name, final double amount) throws UserDoesNotExistException, NoLoanPermittedException, MaxMoneyException {
try {
add(name, BigDecimal.valueOf(amount));
} catch (final ArithmeticException e) {
@ -274,11 +275,11 @@ public class Economy {
* @param amount The amount of money to be added to the user's account
* @throws UserDoesNotExistException If a user by that name does not exist
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws ArithmeticException
* @throws MaxMoneyException If this transaction has but the user over the maximum amount of money
* @deprecated Usernames can change, use {@link Economy#add(UUID, BigDecimal)} or {@link Economy#add(User, BigDecimal)}
*/
@Deprecated
public static void add(final String name, final BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException {
public static void add(final String name, final BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException, MaxMoneyException {
final User user = getUserByName(name);
if (user == null) {
throw new UserDoesNotExistException(name);
@ -293,9 +294,9 @@ public class Economy {
* @param amount The money you want to add
* @throws UserDoesNotExistException If a user by that uuid does not exist
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws ArithmeticException
* @throws MaxMoneyException If this transaction has but the user over the maximum amount of money
*/
public static void add(final UUID uuid, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException, UserDoesNotExistException {
public static void add(final UUID uuid, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException, UserDoesNotExistException, MaxMoneyException {
final User user = getUserByUUID(uuid);
if (user == null) {
throw new UserDoesNotExistException(uuid);
@ -309,10 +310,9 @@ public class Economy {
* @param user User
* @param amount The money you want to add
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws ArithmeticException
* @deprecated Usernames can change, use {@link Economy#add(UUID, BigDecimal)} or {@link Economy#add(User, BigDecimal)}
* @throws MaxMoneyException If this transaction has but the user over the maximum amount of money
*/
public static void add(final User user, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException {
public static void add(final User user, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException, MaxMoneyException {
if (user == null) {
throw new IllegalArgumentException("Economy user cannot be null");
}
@ -328,10 +328,11 @@ public class Economy {
* @param amount The money you want to subtract
* @throws UserDoesNotExistException If a user by that name does not exists
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws MaxMoneyException If this transaction has but the user over the maximum amount of money
* @deprecated Use {@link Economy#subtract(UUID, BigDecimal)} or {@link Economy#subtract(User, BigDecimal)}
*/
@Deprecated
public static void subtract(final String name, final double amount) throws UserDoesNotExistException, NoLoanPermittedException {
public static void subtract(final String name, final double amount) throws UserDoesNotExistException, NoLoanPermittedException, MaxMoneyException {
try {
substract(name, BigDecimal.valueOf(amount));
} catch (final ArithmeticException e) {
@ -346,11 +347,11 @@ public class Economy {
* @param amount The money you want to subtract
* @throws UserDoesNotExistException If a user by that name does not exist
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws ArithmeticException
* @throws MaxMoneyException If this transaction has but the user over the maximum amount of money
* @deprecated Usernames can change, use {@link Economy#subtract(UUID, BigDecimal)} or {@link Economy#subtract(User, BigDecimal)}
*/
@Deprecated
public static void substract(final String name, final BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException {
public static void substract(final String name, final BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException, MaxMoneyException {
final BigDecimal result = getMoneyExact(name).subtract(amount, MATH_CONTEXT);
setMoney(name, result);
Trade.log("API", "Subtract", "API", name, new Trade(amount, ess), null, null, null, result, ess);
@ -363,9 +364,9 @@ public class Economy {
* @param amount The money you want to subtract
* @throws UserDoesNotExistException If a user by that UUID does not exist
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws ArithmeticException
* @throws MaxMoneyException If this transaction has but the user over the maximum amount of money
*/
public static void subtract(final UUID uuid, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException, UserDoesNotExistException {
public static void subtract(final UUID uuid, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException, UserDoesNotExistException, MaxMoneyException {
final User user = getUserByUUID(uuid);
if (user == null) {
throw new UserDoesNotExistException(uuid);
@ -379,9 +380,9 @@ public class Economy {
* @param user User
* @param amount The money you want to subtract
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws ArithmeticException
* @throws MaxMoneyException If this transaction has but the user over the maximum amount of money
*/
public static void subtract(final User user, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException {
public static void subtract(final User user, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException, MaxMoneyException {
if (user == null) {
throw new IllegalArgumentException("Economy user cannot be null");
}
@ -397,10 +398,11 @@ public class Economy {
* @param amount The balance is divided by this value
* @throws UserDoesNotExistException If a user by that name does not exists
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws MaxMoneyException If this transaction has but the user over the maximum amount of money
* @deprecated Use {@link Economy#divide(UUID, BigDecimal)} or {@link Economy#divide(User, BigDecimal)}
*/
@Deprecated
public static void divide(final String name, final double amount) throws UserDoesNotExistException, NoLoanPermittedException {
public static void divide(final String name, final double amount) throws UserDoesNotExistException, NoLoanPermittedException, MaxMoneyException {
try {
divide(name, BigDecimal.valueOf(amount));
} catch (final ArithmeticException e) {
@ -415,11 +417,11 @@ public class Economy {
* @param amount The balance is divided by this value
* @throws UserDoesNotExistException If a user by that name does not exist
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws ArithmeticException
* @throws MaxMoneyException If this transaction has but the user over the maximum amount of money
* @deprecated Usernames can change, use {@link Economy#divide(UUID, BigDecimal)} or {@link Economy#divide(User, BigDecimal)}
*/
@Deprecated
public static void divide(final String name, final BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException {
public static void divide(final String name, final BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException, MaxMoneyException {
final User user = getUserByName(name);
if (user == null) {
throw new UserDoesNotExistException(name);
@ -434,9 +436,9 @@ public class Economy {
* @param amount The balance is divided by this value
* @throws UserDoesNotExistException If a user by that UUID does not exist
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws ArithmeticException
* @throws MaxMoneyException If this transaction has but the user over the maximum amount of money
*/
public static void divide(final UUID uuid, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException, UserDoesNotExistException {
public static void divide(final UUID uuid, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException, UserDoesNotExistException, MaxMoneyException {
final User user = getUserByUUID(uuid);
if (user == null) {
throw new UserDoesNotExistException(uuid);
@ -450,9 +452,9 @@ public class Economy {
* @param user Name of the user
* @param amount The balance is divided by this value
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws ArithmeticException
* @throws MaxMoneyException If this transaction has but the user over the maximum amount of money
*/
public static void divide(final User user, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException {
public static void divide(final User user, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException, MaxMoneyException {
if (user == null) {
throw new IllegalArgumentException("Economy user cannot be null");
}
@ -468,10 +470,11 @@ public class Economy {
* @param amount The balance is multiplied by this value
* @throws UserDoesNotExistException If a user by that name does not exists
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws MaxMoneyException If this transaction has but the user over the maximum amount of money
* @deprecated Use {@link Economy#multiply(UUID, BigDecimal)} or {@link Economy#multiply(User, BigDecimal)}
*/
@Deprecated
public static void multiply(final String name, final double amount) throws UserDoesNotExistException, NoLoanPermittedException {
public static void multiply(final String name, final double amount) throws UserDoesNotExistException, NoLoanPermittedException, MaxMoneyException {
try {
multiply(name, BigDecimal.valueOf(amount));
} catch (final ArithmeticException e) {
@ -486,11 +489,11 @@ public class Economy {
* @param amount The balance is multiplied by the this value
* @throws UserDoesNotExistException If a user by that name does not exist
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws ArithmeticException
* @throws MaxMoneyException If this transaction has but the user over the maximum amount of money
* @deprecated Usernames can change, use {@link Economy#multiply(UUID, BigDecimal)} or {@link Economy#multiply(User, BigDecimal)}
*/
@Deprecated
public static void multiply(final String name, final BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException {
public static void multiply(final String name, final BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException, MaxMoneyException {
final User user = getUserByName(name);
if (user == null) {
throw new UserDoesNotExistException(name);
@ -505,9 +508,9 @@ public class Economy {
* @param amount The balance is multiplied by the this value
* @throws UserDoesNotExistException If a user by that uuid does not exist
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws ArithmeticException
* @throws MaxMoneyException If this transaction has but the user over the maximum amount of money
*/
public static void multiply(final UUID uuid, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException, UserDoesNotExistException {
public static void multiply(final UUID uuid, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException, UserDoesNotExistException, MaxMoneyException {
final User user = getUserByUUID(uuid);
if (user == null) {
throw new UserDoesNotExistException(uuid);
@ -521,9 +524,9 @@ public class Economy {
* @param user Name of the user
* @param amount The balance is multiplied by the this value
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws ArithmeticException
* @throws MaxMoneyException If this transaction has but the user over the maximum amount of money
*/
public static void multiply(final User user, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException {
public static void multiply(final User user, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException, MaxMoneyException {
if (user == null) {
throw new IllegalArgumentException("Economy user cannot be null");
}
@ -538,10 +541,11 @@ public class Economy {
* @param name Name of the user
* @throws UserDoesNotExistException If a user by that name does not exists
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws MaxMoneyException If this transaction has but the user over the maximum amount of money
* @deprecated Usernames can change, use {@link Economy#resetBalance(UUID)} or {@link Economy#resetBalance(User)}
*/
@Deprecated
public static void resetBalance(final String name) throws UserDoesNotExistException, NoLoanPermittedException {
public static void resetBalance(final String name) throws UserDoesNotExistException, NoLoanPermittedException, MaxMoneyException {
if (ess == null) {
throw new RuntimeException(WARN_CALL_BEFORE_LOAD);
}
@ -555,8 +559,9 @@ public class Economy {
* @param uuid UUID of the user
* @throws UserDoesNotExistException If a user by that UUID does not exists
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws MaxMoneyException If this transaction has but the user over the maximum amount of money
*/
public static void resetBalance(final UUID uuid) throws NoLoanPermittedException, UserDoesNotExistException {
public static void resetBalance(final UUID uuid) throws NoLoanPermittedException, UserDoesNotExistException, MaxMoneyException {
final User user = getUserByUUID(uuid);
if (user == null) {
throw new UserDoesNotExistException(uuid);
@ -569,8 +574,9 @@ public class Economy {
*
* @param user User
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
* @throws MaxMoneyException If this transaction has but the user over the maximum amount of money
*/
public static void resetBalance(final User user) throws NoLoanPermittedException {
public static void resetBalance(final User user) throws NoLoanPermittedException, MaxMoneyException {
if (ess == null) {
throw new RuntimeException(WARN_CALL_BEFORE_LOAD);
}

View File

@ -0,0 +1,39 @@
package com.earth2me.essentials.economy;
import org.bukkit.OfflinePlayer;
import org.bukkit.plugin.Plugin;
import java.math.BigDecimal;
public interface EconomyLayer {
String getName();
String getBackendName();
void enable(Plugin plugin);
boolean onServerLoad();
void disable();
String getPluginName();
String getPluginVersion();
boolean hasAccount(OfflinePlayer player);
boolean createPlayerAccount(OfflinePlayer player);
BigDecimal getBalance(OfflinePlayer player);
boolean deposit(OfflinePlayer player, BigDecimal amount);
boolean withdraw(OfflinePlayer player, BigDecimal amount);
default boolean set(OfflinePlayer player, BigDecimal amount) {
if (!withdraw(player, getBalance(player))) {
return false;
}
return amount.equals(BigDecimal.ZERO) || deposit(player, amount);
}
}

View File

@ -0,0 +1,89 @@
package com.earth2me.essentials.economy;
import com.earth2me.essentials.economy.layers.VaultLayer;
import org.bukkit.plugin.Plugin;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Abstraction layer for economy abstraction layers.
*/
public final class EconomyLayers {
private static final Map<String, EconomyLayer> registeredLayers = new HashMap<>();
private static final List<String> availableLayers = new ArrayList<>();
private static EconomyLayer selectedLayer = null;
private EconomyLayers() {
}
public static void init() {
if (!registeredLayers.isEmpty()) {
throw new IllegalStateException("Economy layers have already been registered!");
}
registerLayer(new VaultLayer());
}
public static EconomyLayer getSelectedLayer() {
return selectedLayer;
}
public static boolean isLayerSelected() {
return getSelectedLayer() != null;
}
public static EconomyLayer onPluginEnable(final Plugin plugin) {
if (!registeredLayers.containsKey(plugin.getName())) {
return null;
}
final EconomyLayer layer = registeredLayers.get(plugin.getName());
layer.enable(plugin);
availableLayers.add(plugin.getName());
if (selectedLayer != null) {
return null;
}
selectedLayer = layer;
selectedLayer.enable(plugin);
return selectedLayer;
}
public static boolean onPluginDisable(final Plugin plugin, final boolean serverStarted) {
if (!availableLayers.contains(plugin.getName())) {
return false;
}
registeredLayers.get(plugin.getName()).disable();
availableLayers.remove(plugin.getName());
if (selectedLayer.getPluginName().equals(plugin.getName())) {
selectedLayer = availableLayers.isEmpty() ? null : registeredLayers.get(availableLayers.get(0));
if (selectedLayer != null && serverStarted) {
selectedLayer.onServerLoad();
}
return true;
}
return false;
}
public static void onServerLoad() {
if (!isLayerSelected() || getSelectedLayer().onServerLoad()) {
return;
}
availableLayers.remove(getSelectedLayer().getPluginVersion());
selectedLayer = null;
if (!availableLayers.isEmpty()) {
selectedLayer = registeredLayers.get(availableLayers.get(0));
onServerLoad();
}
}
public static void registerLayer(final EconomyLayer economyLayer) {
registeredLayers.put(economyLayer.getPluginName(), economyLayer);
}
}

View File

@ -0,0 +1,76 @@
package com.earth2me.essentials.economy.layers;
import com.earth2me.essentials.economy.EconomyLayer;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.plugin.Plugin;
import java.math.BigDecimal;
public class VaultLayer implements EconomyLayer {
private Plugin plugin;
private Economy adapter;
@Override
public boolean hasAccount(OfflinePlayer player) {
return adapter.hasAccount(player);
}
@Override
public boolean createPlayerAccount(OfflinePlayer player) {
return adapter.createPlayerAccount(player);
}
@Override
public BigDecimal getBalance(OfflinePlayer player) {
return BigDecimal.valueOf(adapter.getBalance(player));
}
@Override
public boolean deposit(OfflinePlayer player, BigDecimal amount) {
return adapter.depositPlayer(player, amount.doubleValue()).transactionSuccess();
}
@Override
public boolean withdraw(OfflinePlayer player, BigDecimal amount) {
return false;
}
@Override
public String getName() {
return "Vault Compatibility Layer";
}
@Override
public String getBackendName() {
return adapter.getName();
}
@Override
public void enable(Plugin plugin) {
this.plugin = plugin;
}
@Override
public boolean onServerLoad() {
this.adapter = Bukkit.getServicesManager().load(Economy.class);
return adapter != null && !adapter.getName().equals("Essentials Economy") && !adapter.getName().equals("EssentialsX Economy");
}
@Override
public void disable() {
this.plugin = null;
this.adapter = null;
}
@Override
public String getPluginName() {
return "Vault";
}
@Override
public String getPluginVersion() {
return plugin == null ? null : plugin.getDescription().getVersion();
}
}

View File

@ -0,0 +1,350 @@
package com.earth2me.essentials.economy.vault;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.api.NoLoanPermittedException;
import com.earth2me.essentials.api.UserDoesNotExistException;
import com.earth2me.essentials.utils.NumberUtil;
import net.ess3.api.MaxMoneyException;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.economy.EconomyResponse;
import org.bukkit.OfflinePlayer;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
/**
* A goddamn Vault adapter, what more do you want?
* Provides access to the EssentialsX economy for plugins that use the Vault API.
* <p>
* Developer note: for accessing Essentials/Vault economy functions from EssentialsX code, see
* {@link com.earth2me.essentials.User}.
*/
public class VaultEconomyProvider implements Economy {
private final Essentials ess;
public VaultEconomyProvider(Essentials essentials) {
this.ess = essentials;
}
@Override
public boolean isEnabled() {
return ess.isEnabled();
}
@Override
public String getName() {
return "EssentialsX Economy";
}
@Override
public boolean hasBankSupport() {
return false;
}
@Override
public int fractionalDigits() {
return -1;
}
@Override
public String format(double amount) {
return NumberUtil.displayCurrency(BigDecimal.valueOf(amount), ess);
}
@Override
public String currencyNamePlural() {
return currencyNameSingular();
}
@Override
public String currencyNameSingular() {
return ess.getSettings().getCurrencySymbol();
}
@SuppressWarnings("deprecation")
@Override
public boolean hasAccount(String playerName) {
return com.earth2me.essentials.api.Economy.playerExists(playerName);
}
@Override
public boolean hasAccount(OfflinePlayer player) {
return com.earth2me.essentials.api.Economy.playerExists(player.getUniqueId());
}
@Override
public boolean hasAccount(String playerName, String worldName) {
return hasAccount(playerName);
}
@Override
public boolean hasAccount(OfflinePlayer player, String worldName) {
return hasAccount(player);
}
@SuppressWarnings("deprecation")
@Override
public double getBalance(String playerName) {
try {
return getDoubleValue(com.earth2me.essentials.api.Economy.getMoneyExact(playerName));
} catch (UserDoesNotExistException e) {
createPlayerAccount(playerName);
return getDoubleValue(ess.getSettings().getStartingBalance());
}
}
@Override
public double getBalance(OfflinePlayer player) {
try {
return getDoubleValue(com.earth2me.essentials.api.Economy.getMoneyExact(player.getUniqueId()));
} catch (UserDoesNotExistException e) {
createPlayerAccount(player);
return getDoubleValue(ess.getSettings().getStartingBalance());
}
}
private double getDoubleValue(final BigDecimal value) {
double amount = value.doubleValue();
if (new BigDecimal(amount).compareTo(value) > 0) {
// closest double is bigger than the exact amount
// -> get the previous double value to not return more money than the user has
amount = Math.nextAfter(amount, Double.NEGATIVE_INFINITY);
}
return amount;
}
@Override
public double getBalance(String playerName, String world) {
return getBalance(playerName);
}
@Override
public double getBalance(OfflinePlayer player, String world) {
return getBalance(player);
}
@SuppressWarnings("deprecation")
@Override
public boolean has(String playerName, double amount) {
try {
return com.earth2me.essentials.api.Economy.hasEnough(playerName, amount);
} catch (UserDoesNotExistException e) {
return false;
}
}
@Override
public boolean has(OfflinePlayer player, double amount) {
try {
return com.earth2me.essentials.api.Economy.hasEnough(player.getUniqueId(), BigDecimal.valueOf(amount));
} catch (UserDoesNotExistException e) {
return false;
}
}
@Override
public boolean has(String playerName, String worldName, double amount) {
return has(playerName, amount);
}
@Override
public boolean has(OfflinePlayer player, String worldName, double amount) {
return has(player, amount);
}
@SuppressWarnings("deprecation")
@Override
public EconomyResponse withdrawPlayer(String playerName, double amount) {
if (playerName == null) {
return new EconomyResponse(0, 0, EconomyResponse.ResponseType.FAILURE, "Player name cannot be null!");
}
if (amount < 0) {
return new EconomyResponse(0, 0, EconomyResponse.ResponseType.FAILURE, "Cannot withdraw negative funds!");
}
try {
com.earth2me.essentials.api.Economy.subtract(playerName, amount);
return new EconomyResponse(amount, getBalance(playerName), EconomyResponse.ResponseType.SUCCESS, null);
} catch (UserDoesNotExistException e) {
return new EconomyResponse(0, 0, EconomyResponse.ResponseType.FAILURE, "User does not exist!");
} catch (NoLoanPermittedException e) {
return new EconomyResponse(0, getBalance(playerName), EconomyResponse.ResponseType.FAILURE, "Loan was not permitted!");
} catch (MaxMoneyException e) {
return new EconomyResponse(0, getBalance(playerName), EconomyResponse.ResponseType.FAILURE, "User goes over maximum money limit!");
}
}
@Override
public EconomyResponse withdrawPlayer(OfflinePlayer player, double amount) {
if (player == null) {
return new EconomyResponse(0, 0, EconomyResponse.ResponseType.FAILURE, "Player cannot be null!");
}
if (amount < 0) {
return new EconomyResponse(0, 0, EconomyResponse.ResponseType.FAILURE, "Cannot withdraw negative funds!");
}
try {
com.earth2me.essentials.api.Economy.subtract(player.getUniqueId(), BigDecimal.valueOf(amount));
return new EconomyResponse(amount, getBalance(player), EconomyResponse.ResponseType.SUCCESS, null);
} catch (UserDoesNotExistException e) {
return new EconomyResponse(0, 0, EconomyResponse.ResponseType.FAILURE, "User does not exist!");
} catch (NoLoanPermittedException e) {
return new EconomyResponse(0, getBalance(player), EconomyResponse.ResponseType.FAILURE, "Loan was not permitted!");
} catch (MaxMoneyException e) {
return new EconomyResponse(0, getBalance(player), EconomyResponse.ResponseType.FAILURE, "User goes over maximum money limit!");
}
}
@Override
public EconomyResponse withdrawPlayer(String playerName, String worldName, double amount) {
return withdrawPlayer(playerName, amount);
}
@Override
public EconomyResponse withdrawPlayer(OfflinePlayer player, String worldName, double amount) {
return withdrawPlayer(player, amount);
}
@SuppressWarnings("deprecation")
@Override
public EconomyResponse depositPlayer(String playerName, double amount) {
if (playerName == null) {
return new EconomyResponse(0, 0, EconomyResponse.ResponseType.FAILURE, "Player name can not be null.");
}
if (amount < 0) {
return new EconomyResponse(0, 0, EconomyResponse.ResponseType.FAILURE, "Cannot deposit negative funds");
}
try {
com.earth2me.essentials.api.Economy.add(playerName, amount);
return new EconomyResponse(amount, getBalance(playerName), EconomyResponse.ResponseType.SUCCESS, null);
} catch (UserDoesNotExistException e) {
return new EconomyResponse(0, 0, EconomyResponse.ResponseType.FAILURE, "User does not exist!");
} catch (NoLoanPermittedException e) {
return new EconomyResponse(0, getBalance(playerName), EconomyResponse.ResponseType.FAILURE, "Loan was not permitted!");
} catch (MaxMoneyException e) {
return new EconomyResponse(0, getBalance(playerName), EconomyResponse.ResponseType.FAILURE, "User goes over maximum money limit!");
}
}
@Override
public EconomyResponse depositPlayer(OfflinePlayer player, double amount) {
if (player == null) {
return new EconomyResponse(0, 0, EconomyResponse.ResponseType.FAILURE, "Player can not be null.");
}
if (amount < 0) {
return new EconomyResponse(0, 0, EconomyResponse.ResponseType.FAILURE, "Cannot deposit negative funds");
}
try {
com.earth2me.essentials.api.Economy.add(player.getUniqueId(), BigDecimal.valueOf(amount));
return new EconomyResponse(amount, getBalance(player), EconomyResponse.ResponseType.SUCCESS, null);
} catch (UserDoesNotExistException e) {
return new EconomyResponse(0, 0, EconomyResponse.ResponseType.FAILURE, "User does not exist!");
} catch (NoLoanPermittedException e) {
return new EconomyResponse(0, getBalance(player), EconomyResponse.ResponseType.FAILURE, "Loan was not permitted!");
} catch (MaxMoneyException e) {
return new EconomyResponse(0, getBalance(player), EconomyResponse.ResponseType.FAILURE, "User goes over maximum money limit!");
}
}
@Override
public EconomyResponse depositPlayer(String playerName, String worldName, double amount) {
return depositPlayer(playerName, amount);
}
@Override
public EconomyResponse depositPlayer(OfflinePlayer player, String worldName, double amount) {
return depositPlayer(player, amount);
}
@Override
public boolean createPlayerAccount(String playerName) {
if (hasAccount(playerName)) {
return false;
}
// Assume we're creating an NPC here? If not, it's a lost cause anyway!
return com.earth2me.essentials.api.Economy.createNPC(playerName);
}
@Override
public boolean createPlayerAccount(OfflinePlayer player) {
if (hasAccount(player) || ess.getUserMap().isUUIDMatch(player.getUniqueId(), player.getName())) {
return false;
}
ess.getUserMap().trackUUID(player.getUniqueId(), player.getName(), false);
return true;
}
@Override
public boolean createPlayerAccount(String playerName, String worldName) {
return createPlayerAccount(playerName);
}
@Override
public boolean createPlayerAccount(OfflinePlayer player, String worldName) {
return createPlayerAccount(player);
}
@Override
public EconomyResponse createBank(String name, String player) {
return new EconomyResponse(0, 0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, "EssentialsX does not support bank accounts!");
}
@Override
public EconomyResponse createBank(String name, OfflinePlayer player) {
return new EconomyResponse(0, 0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, "EssentialsX does not support bank accounts!");
}
@Override
public EconomyResponse deleteBank(String name) {
return new EconomyResponse(0, 0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, "EssentialsX does not support bank accounts!");
}
@Override
public EconomyResponse bankBalance(String name) {
return new EconomyResponse(0, 0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, "EssentialsX does not support bank accounts!");
}
@Override
public EconomyResponse bankHas(String name, double amount) {
return new EconomyResponse(0, 0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, "EssentialsX does not support bank accounts!");
}
@Override
public EconomyResponse bankWithdraw(String name, double amount) {
return new EconomyResponse(0, 0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, "EssentialsX does not support bank accounts!");
}
@Override
public EconomyResponse bankDeposit(String name, double amount) {
return new EconomyResponse(0, 0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, "EssentialsX does not support bank accounts!");
}
@Override
public EconomyResponse isBankOwner(String name, String playerName) {
return new EconomyResponse(0, 0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, "EssentialsX does not support bank accounts!");
}
@Override
public EconomyResponse isBankOwner(String name, OfflinePlayer player) {
return new EconomyResponse(0, 0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, "EssentialsX does not support bank accounts!");
}
@Override
public EconomyResponse isBankMember(String name, String playerName) {
return new EconomyResponse(0, 0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, "EssentialsX does not support bank accounts!");
}
@Override
public EconomyResponse isBankMember(String name, OfflinePlayer player) {
return new EconomyResponse(0, 0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, "EssentialsX does not support bank accounts!");
}
@Override
public List<String> getBanks() {
return Collections.emptyList();
}
}

View File

@ -1,7 +1,8 @@
package com.earth2me.essentials.metrics;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.register.payment.Methods;
import com.earth2me.essentials.economy.EconomyLayer;
import com.earth2me.essentials.economy.EconomyLayers;
import com.google.common.collect.ImmutableList;
import org.bstats.bukkit.Metrics;
import org.bukkit.Bukkit;
@ -69,9 +70,10 @@ public class MetricsWrapper {
metrics.addCustomChart(new Metrics.DrilldownPie("econPlugin", () -> {
final Map<String, Map<String, Integer>> result = new HashMap<>();
final Map<String, Integer> backend = new HashMap<>();
if (Methods.hasMethod()) {
backend.put(Methods.getMethod().getBackend(), 1);
result.put(Methods.getMethod().getName(), backend);
final EconomyLayer layer = EconomyLayers.getSelectedLayer();
if (layer != null) {
backend.put(layer.getBackendName(), 1);
result.put(layer.getPluginName(), backend);
} else {
backend.put("Essentials", 1);
result.put("Essentials", backend);

View File

@ -1,218 +0,0 @@
package com.earth2me.essentials.register.payment;
import org.bukkit.plugin.Plugin;
/**
* Interface to be implemented by a payment method.
* Copyright (C) 2011
* AOL license &lt;http://aol.nexua.org&gt;
* <p>
* For more information about the licensing of this code in EssentialsX, see below:
* https://gist.github.com/mdcfe/0935441c9573c030c8bd5a2e604aeec3
*
* @author Nijikokun &lt;nijikokun@shortmail.com&gt; (@nijikokun)
*/
public interface Method {
/**
* Encodes the Plugin into an Object disguised as the Plugin. If you want the original Plugin Class you must cast it
* to the correct Plugin, to do so you have to verify the name and or version then cast.
* <p>
* <pre>
* if(method.getName().equalsIgnoreCase("iConomy"))
* iConomy plugin = ((iConomy)method.getPlugin());</pre>
*
* @return {@link Object}!
* @see #getName()
* @see #getVersion()
*/
Plugin getPlugin();
/**
* Set Plugin data.
*
* @param plugin Plugin
*/
void setPlugin(Plugin plugin);
/**
* Returns the actual name of this method.
*
* @return <code>String</code> Plugin name.
*/
String getName();
/**
* Returns the backend plugin of this economy method, if applicable.
*
* @return <code>String</code> Plugin name.
*/
String getBackend();
/**
* Returns the reported name of this method.
*
* @return <code>String</code> Plugin name.
*/
String getLongName();
/**
* Returns the actual version of this method.
*
* @return <code>String</code> Plugin version.
*/
String getVersion();
/**
* Returns the amount of decimal places that get stored NOTE: it will return -1 if there is no rounding
*
* @return <code>int</code> for each decimal place
*/
int fractionalDigits();
/**
* Formats amounts into this payment methods style of currency display.
*
* @param amount Double
* @return <code>String</code> - Formatted Currency Display.
*/
String format(double amount);
/**
* Allows the verification of bank API existence in this payment method.
*
* @return <code>boolean</code>
*/
boolean hasBanks();
/**
* Determines the existence of a bank via name.
*
* @param bank Bank name
* @return <code>boolean</code>
* @see #hasBanks
*/
boolean hasBank(String bank);
/**
* Determines the existence of an account via name.
*
* @param name Account name
* @return <code>boolean</code>
*/
boolean hasAccount(String name);
/**
* Check to see if an account <code>name</code> is tied to a <code>bank</code>.
*
* @param bank Bank name
* @param name Account name
* @return <code>boolean</code>
*/
boolean hasBankAccount(String bank, String name);
/**
* Forces an account creation
*
* @param name Account name
* @return <code>boolean</code>
*/
boolean createAccount(String name);
/**
* Forces an account creation
*
* @param name Account name
* @param balance Initial account balance
* @return <code>boolean</code>
*/
boolean createAccount(String name, Double balance);
/**
* Returns a <code>MethodAccount</code> class for an account <code>name</code>.
*
* @param name Account name
* @return <code>MethodAccount</code> <em>or</em> <code>Null</code>
*/
MethodAccount getAccount(String name);
/**
* Returns a <code>MethodBankAccount</code> class for an account <code>name</code>.
*
* @param bank Bank name
* @param name Account name
* @return <code>MethodBankAccount</code> <em>or</em> <code>Null</code>
*/
MethodBankAccount getBankAccount(String bank, String name);
/**
* Checks to verify the compatibility between this Method and a plugin. Internal usage only, for the most part.
*
* @param plugin Plugin
* @return <code>boolean</code>
*/
boolean isCompatible(Plugin plugin);
/**
* Contains Calculator and Balance functions for Accounts.
*/
interface MethodAccount {
double balance();
boolean set(double amount);
boolean add(double amount);
boolean subtract(double amount);
boolean multiply(double amount);
boolean divide(double amount);
boolean hasEnough(double amount);
boolean hasOver(double amount);
boolean hasUnder(double amount);
boolean isNegative();
boolean remove();
@Override
String toString();
}
/**
* Contains Calculator and Balance functions for Bank Accounts.
*/
interface MethodBankAccount {
double balance();
String getBankName();
int getBankId();
boolean set(double amount);
boolean add(double amount);
boolean subtract(double amount);
boolean multiply(double amount);
boolean divide(double amount);
boolean hasEnough(double amount);
boolean hasOver(double amount);
boolean hasUnder(double amount);
boolean isNegative();
boolean remove();
@Override
String toString();
}
}

View File

@ -1,247 +0,0 @@
package com.earth2me.essentials.register.payment;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import java.util.HashSet;
import java.util.Set;
/**
* The <code>Methods</code> initializes Methods that utilize the Method interface based on a "first come, first served"
* basis.
* <p>
* Allowing you to check whether a payment method exists or not.
* <p>
* Methods also allows you to set a preferred method of payment before it captures payment plugins in the initialization
* process.
* <p>
* in
* <code>bukkit.yml</code>: <blockquote><pre>
* economy:
* preferred: "iConomy"
* </pre></blockquote>
* <p>
* Copyright (C) 2011
* AOL license &lt;http://aol.nexua.org&gt;
* <p>
* For more information about the licensing of this code in EssentialsX, see below:
* https://gist.github.com/mdcfe/0935441c9573c030c8bd5a2e604aeec3
*
* @author Nijikokun &lt;nijikokun@shortmail.com&gt; (@nijikokun)
*/
public final class Methods {
private static final Set<Method> Methods = new HashSet<>();
private static final Set<String> Dependencies = new HashSet<>();
private static final Set<Method> Attachables = new HashSet<>();
private static String version = null;
private static boolean self = false;
private static Method Method = null;
private static String preferred = "";
private Methods() {
}
/**
* Implement all methods along with their respective name &amp; class.
*/
public static void init() {
if (!Methods.isEmpty()) {
throw new IllegalStateException("Methods already initialised!");
}
addMethod("Vault", new com.earth2me.essentials.register.payment.methods.VaultEco());
}
/**
* Use to reset methods during disable
*/
public static void reset() {
version = null;
self = false;
Method = null;
preferred = "";
Attachables.clear();
}
/**
* Use to get version of Register plugin
*
* @return version
*/
public static String getVersion() {
return version;
}
/**
* Used by the plugin to setup version
*
* @param v version
*/
public static void setVersion(final String v) {
version = v;
}
/**
* Returns an array of payment method names that have been loaded through the <code>_init</code> method.
*
* @return Set of names of payment methods that are loaded.
* @see #setMethod(PluginManager)
*/
public static Set<String> getDependencies() {
return Dependencies;
}
/**
* Interprets Plugin class data to verify whether it is compatible with an existing payment method to use for
* payments and other various economic activity.
*
* @param plugin Plugin data from bukkit, Internal Class file.
* @return Method <em>or</em> Null
*/
public static Method createMethod(final Plugin plugin) {
for (final Method method : Methods) {
if (method.isCompatible(plugin)) {
method.setPlugin(plugin);
return method;
}
}
return null;
}
private static void addMethod(final String name, final Method method) {
Dependencies.add(name);
Methods.add(method);
}
/**
* Verifies if Register has set a payment method for usage yet.
*
* @return <code>boolean</code>
* @see #setMethod(PluginManager)
* @see #checkDisabled(Plugin)
*/
public static boolean hasMethod() {
return Method != null;
}
/**
* Checks Plugin Class against a multitude of checks to verify it's usability as a payment method.
*
* @param manager the plugin manager for the server
* @return <code>boolean</code> True on success, False on failure.
*/
public static boolean setMethod(final PluginManager manager) {
if (hasMethod()) {
return true;
}
if (self) {
self = false;
return false;
}
int count = 0;
boolean match = false;
Plugin plugin;
for (final String name : getDependencies()) {
if (hasMethod()) {
break;
}
plugin = manager.getPlugin(name);
if (plugin == null || !plugin.isEnabled()) {
continue;
}
final Method current = createMethod(plugin);
if (current == null) {
continue;
}
if (preferred.isEmpty()) {
Method = current;
} else {
Attachables.add(current);
}
}
if (!preferred.isEmpty()) {
do {
if (hasMethod()) {
match = true;
} else {
for (final Method attached : Attachables) {
if (attached == null) {
continue;
}
if (hasMethod()) {
match = true;
break;
}
if (preferred.isEmpty()) {
Method = attached;
}
if (count == 0) {
if (preferred.equalsIgnoreCase(attached.getName())) {
Method = attached;
} else {
Method = attached;
}
}
}
count++;
}
} while (!match);
}
return hasMethod();
}
/**
* Sets the preferred economy
*
* @return <code>boolean</code>
*/
public static boolean setPreferred(final String check) {
if (getDependencies().contains(check)) {
preferred = check;
return true;
}
return false;
}
/**
* Grab the existing and initialized (hopefully) Method Class.
*
* @return <code>Method</code> <em>or</em> <code>Null</code>
*/
public static Method getMethod() {
return Method;
}
/**
* Verify is a plugin is disabled, only does this if we there is an existing payment method initialized in
* Register.
*
* @param method Plugin data from bukkit, Internal Class file.
* @return <code>boolean</code>
*/
public static boolean checkDisabled(final Plugin method) {
if (!hasMethod()) {
return true;
}
if (Method.isCompatible(method)) {
Method = null;
}
return Method == null;
}
}

View File

@ -1,280 +0,0 @@
package com.earth2me.essentials.register.payment.methods;
import com.earth2me.essentials.register.payment.Method;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
public class VaultEco implements Method {
private Plugin vault;
private Economy economy;
@Override
public Plugin getPlugin() {
return this.vault;
}
@Override
public void setPlugin(final Plugin plugin) {
this.vault = plugin;
final RegisteredServiceProvider<Economy> economyProvider = this.vault.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
if (economyProvider != null) {
this.economy = economyProvider.getProvider();
}
}
@Override
public boolean createAccount(final String name, final Double amount) {
if (hasAccount(name)) {
return false;
}
return false;
}
@Override
public String getName() {
return this.vault.getDescription().getName();
}
@Override
public String getBackend() {
return economy == null ? "NoEco" : economy.getName();
}
@Override
public String getLongName() {
return getName().concat(" - Economy: ").concat(getBackend());
}
@Override
public String getVersion() {
return this.vault.getDescription().getVersion();
}
@Override
public int fractionalDigits() {
return 0;
}
@Override
public String format(final double amount) {
return this.economy.format(amount);
}
@Override
public boolean hasBanks() {
return this.economy.hasBankSupport();
}
@Override
public boolean hasBank(final String bank) {
return this.economy.getBanks().contains(bank);
}
@Override
public boolean hasAccount(final String name) {
return this.economy.hasAccount(name);
}
@Override
public boolean hasBankAccount(final String bank, final String name) {
return this.economy.isBankOwner(bank, name).transactionSuccess() || this.economy.isBankMember(bank, name).transactionSuccess();
}
@Override
public boolean createAccount(final String name) {
return this.economy.createBank(name, "").transactionSuccess();
}
public boolean createAccount(final String name, final double balance) {
if (!this.economy.createBank(name, "").transactionSuccess()) {
return false;
}
return this.economy.bankDeposit(name, balance).transactionSuccess();
}
@Override
public MethodAccount getAccount(final String name) {
if (!hasAccount(name)) {
return null;
}
return new VaultAccount(name, this.economy);
}
@Override
public MethodBankAccount getBankAccount(final String bank, final String name) {
if (!hasBankAccount(bank, name)) {
return null;
}
return new VaultBankAccount(bank, economy);
}
@Override
public boolean isCompatible(final Plugin plugin) {
try {
final RegisteredServiceProvider<Economy> ecoPlugin = plugin.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
return plugin.getName().equals("Vault") && ecoPlugin != null && !ecoPlugin.getProvider().getName().equals("Essentials Economy");
} catch (final LinkageError | Exception e) {
return false;
}
}
public static class VaultAccount implements MethodAccount {
private final String name;
private final Economy economy;
VaultAccount(final String name, final Economy economy) {
this.name = name;
this.economy = economy;
}
@Override
public double balance() {
return this.economy.getBalance(this.name);
}
@Override
public boolean set(final double amount) {
if (!this.economy.withdrawPlayer(this.name, this.balance()).transactionSuccess()) {
return false;
}
if (amount == 0) {
return true;
}
return this.economy.depositPlayer(this.name, amount).transactionSuccess();
}
@Override
public boolean add(final double amount) {
return this.economy.depositPlayer(this.name, amount).transactionSuccess();
}
@Override
public boolean subtract(final double amount) {
return this.economy.withdrawPlayer(this.name, amount).transactionSuccess();
}
@Override
public boolean multiply(final double amount) {
final double balance = this.balance();
return this.set(balance * amount);
}
@Override
public boolean divide(final double amount) {
final double balance = this.balance();
return this.set(balance / amount);
}
@Override
public boolean hasEnough(final double amount) {
return this.balance() >= amount;
}
@Override
public boolean hasOver(final double amount) {
return this.balance() > amount;
}
@Override
public boolean hasUnder(final double amount) {
return this.balance() < amount;
}
@Override
public boolean isNegative() {
return this.balance() < 0;
}
@Override
public boolean remove() {
return this.set(0.0);
}
}
public static class VaultBankAccount implements MethodBankAccount {
private final String bank;
private final Economy economy;
public VaultBankAccount(final String bank, final Economy economy) {
this.bank = bank;
this.economy = economy;
}
@Override
public String getBankName() {
return this.bank;
}
@Override
public int getBankId() {
return -1;
}
@Override
public double balance() {
return this.economy.bankBalance(this.bank).balance;
}
@Override
public boolean set(final double amount) {
if (!this.economy.bankWithdraw(this.bank, this.balance()).transactionSuccess()) {
return false;
}
if (amount == 0) {
return true;
}
return this.economy.bankDeposit(this.bank, amount).transactionSuccess();
}
@Override
public boolean add(final double amount) {
return this.economy.bankDeposit(this.bank, amount).transactionSuccess();
}
@Override
public boolean subtract(final double amount) {
return this.economy.bankWithdraw(this.bank, amount).transactionSuccess();
}
@Override
public boolean multiply(final double amount) {
final double balance = this.balance();
return this.set(balance * amount);
}
@Override
public boolean divide(final double amount) {
final double balance = this.balance();
return this.set(balance / amount);
}
@Override
public boolean hasEnough(final double amount) {
return this.balance() >= amount;
}
@Override
public boolean hasOver(final double amount) {
return this.balance() > amount;
}
@Override
public boolean hasUnder(final double amount) {
return this.balance() < amount;
}
@Override
public boolean isNegative() {
return this.balance() < 0;
}
@Override
public boolean remove() {
return this.set(0.0);
}
}
}

View File

@ -5,6 +5,7 @@ import com.earth2me.essentials.api.UserDoesNotExistException;
import com.earth2me.essentials.commands.IEssentialsCommand;
import com.earth2me.essentials.commands.NoChargeException;
import net.ess3.api.Economy;
import net.ess3.api.MaxMoneyException;
import org.bukkit.World.Environment;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.InvalidDescriptionException;
@ -66,7 +67,7 @@ public class EconomyTest {
Assert.assertEquals("Divide money", 5.0, Economy.getMoney(PLAYERNAME), 0);
Economy.setMoney(PLAYERNAME, 10.0);
Assert.assertEquals("Set money", 10.0, Economy.getMoney(PLAYERNAME), 0);
} catch (final NoLoanPermittedException | UserDoesNotExistException ex) {
} catch (final NoLoanPermittedException | UserDoesNotExistException | MaxMoneyException ex) {
Assert.fail(ex.getMessage());
}
@ -84,7 +85,7 @@ public class EconomyTest {
Assert.assertEquals("Reset balance", 0.0, Economy.getMoney(PLAYERNAME), 0);
Economy.subtract(PLAYERNAME, 5.0);
Assert.fail("Did not throw exception");
} catch (final NoLoanPermittedException ignored) {
} catch (final NoLoanPermittedException | MaxMoneyException ignored) {
} catch (final UserDoesNotExistException ex) {
Assert.fail(ex.getMessage());
}
@ -92,7 +93,7 @@ public class EconomyTest {
try {
Economy.resetBalance("UnknownPlayer");
Assert.fail("Did not throw exception");
} catch (final NoLoanPermittedException ex) {
} catch (final NoLoanPermittedException | MaxMoneyException ex) {
Assert.fail(ex.getMessage());
} catch (final UserDoesNotExistException ignored) {
}

View File

@ -189,7 +189,7 @@ public class FakeServer implements Server {
@Override
public int scheduleSyncDelayedTask(final Plugin plugin, final Runnable r) {
throw new UnsupportedOperationException("Not supported yet.");
return -1;
}
@Override