Rewritten Economy API. Please update your plugins.

This Economy API is now supported by Essentials.
Do not use NPC Accounts as bank accounts. Bank accounts are not supported yet.
New config: currency-symbol

git-svn-id: https://svn.java.net/svn/essentials~svn/trunk@1431 e251c2fe-e539-e718-e476-b85c1f46cddb
This commit is contained in:
snowleo 2011-05-13 16:57:45 +00:00
parent fdb9473baa
commit 82dd4e88b4
12 changed files with 310 additions and 308 deletions

View File

@ -51,8 +51,8 @@ public class EssentialsEcoBlockListener extends BlockListener
{
String[] l1 = sign.getLines()[1].split("[ :-]+");
String[] l2 = sign.getLines()[2].split("[ :-]+");
boolean m1 = l1[0].matches("\\$[0-9]+(\\.[0-9]+)?");
boolean m2 = l2[0].matches("\\$[0-9]+(\\.[0-9]+)?");
boolean m1 = l1[0].matches("[^0-9][0-9]+(\\.[0-9]+)?");
boolean m2 = l2[0].matches("[^0-9][0-9]+(\\.[0-9]+)?");
double q1 = Double.parseDouble(m1 ? l1[0].substring(1) : l1[0]);
double q2 = Double.parseDouble(m2 ? l2[0].substring(1) : l2[0]);
double r1 = Double.parseDouble(l1[m1 ? 1 : 2]);
@ -159,8 +159,8 @@ public class EssentialsEcoBlockListener extends BlockListener
{
String[] l1 = event.getLines()[1].split("[ :-]+");
String[] l2 = event.getLines()[2].split("[ :-]+");
boolean m1 = l1[0].matches("\\$[0-9]+(\\.[0-9]+)?");
boolean m2 = l2[0].matches("\\$[0-9]+(\\.[0-9]+)?");
boolean m1 = l1[0].matches("[^0-9][0-9]+(\\.[0-9]+)?");
boolean m2 = l2[0].matches("[^0-9][0-9]+(\\.[0-9]+)?");
double q1 = Double.parseDouble(m1 ? l1[0].substring(1) : l1[0]);
double q2 = Double.parseDouble(m2 ? l2[0].substring(1) : l2[0]);
double r2 = Double.parseDouble(l2[m2 ? 1 : 2]);
@ -195,16 +195,16 @@ public class EssentialsEcoBlockListener extends BlockListener
}
event.setLine(0, "§1[Trade]");
event.setLine(1, (m1 ? "$" + q1 : String.format("%.0f",q1) + " " + l1[1]) + ":0");
event.setLine(2, (m2 ? "$" + q2 : String.format("%.0f", q2)+ " " + l2[1]) + ":" + String.format("%.0f",r2));
event.setLine(1, (m1 ? ess.getSettings().getCurrencySymbol() + q1 : String.format("%.0f",q1) + " " + l1[1]) + ":0");
event.setLine(2, (m2 ? ess.getSettings().getCurrencySymbol() + q2 : String.format("%.0f", q2)+ " " + l2[1]) + ":" + String.format("%.0f",r2));
event.setLine(3, "§8" + username);
}
catch (Throwable ex)
{
user.sendMessage("§cError: " + ex.getMessage());
event.setLine(0, "§4[Trade]");
event.setLine(1, "# ItemOr$");
event.setLine(2, "# ItemOr$:#");
event.setLine(1, "# ItemOr"+ess.getSettings().getCurrencySymbol());
event.setLine(2, "# ItemOr"+ess.getSettings().getCurrencySymbol()+":#");
event.setLine(3, "§8" + username);
}
return;

View File

@ -44,7 +44,7 @@ public class EssentialsEcoPlayerListener extends PlayerListener
{
int amount = Integer.parseInt(sign.getLine(1));
ItemStack item = ItemDb.get(sign.getLine(2), amount);
double cost = Double.parseDouble(sign.getLine(3).substring(1).replaceAll(",", "."));
double cost = Double.parseDouble(sign.getLine(3).substring(1));
if (user.getMoney() < cost)
{
throw new Exception(Util.i18n("notEnoughMoney"));
@ -70,7 +70,7 @@ public class EssentialsEcoPlayerListener extends PlayerListener
{
int amount = Integer.parseInt(sign.getLine(1));
ItemStack item = ItemDb.get(sign.getLine(2), amount);
double cost = Double.parseDouble(sign.getLine(3).substring(1).replaceAll(",", "."));
double cost = Double.parseDouble(sign.getLine(3).substring(1));
if (!InventoryWorkaround.containsItem(user.getInventory(), true, item))
{
@ -93,8 +93,8 @@ public class EssentialsEcoPlayerListener extends PlayerListener
{
String[] l1 = sign.getLines()[1].split("[ :-]+");
String[] l2 = sign.getLines()[2].split("[ :-]+");
boolean m1 = l1[0].matches("\\$[0-9]+(\\.[0-9]+)?");
boolean m2 = l2[0].matches("\\$[0-9]+(\\.[0-9]+)?");
boolean m1 = l1[0].matches("[^0-9][0-9]+(\\.[0-9]+)?");
boolean m2 = l2[0].matches("[^0-9][0-9]+(\\.[0-9]+)?");
double q1 = Double.parseDouble(m1 ? l1[0].substring(1) : l1[0]);
double q2 = Double.parseDouble(m2 ? l2[0].substring(1) : l2[0]);
double r1 = Double.parseDouble(l1[m1 ? 1 : 2]);
@ -126,7 +126,7 @@ public class EssentialsEcoPlayerListener extends PlayerListener
user.updateInventory();
}
r1 = 0;
sign.setLine(1, (m1 ? Util.formatCurrency(q1) : String.format("%.0f", q1) + " " + l1[1]) + ":" + r1);
sign.setLine(1, (m1 ? Util.formatCurrency(q1) : ((int)q1) + " " + l1[1]) + ":" + r1);
sign.update();
}
else
@ -180,8 +180,8 @@ public class EssentialsEcoPlayerListener extends PlayerListener
sign.setLine(0, "§1[Trade]");
sign.setLine(1, (m1 ? Util.formatCurrency(q1) : String.format("%.0f", q1) + " " + l1[1]) + ":" + String.format((m1 ? "%.2f" : "%.0f"), Util.roundDouble(r1)));
sign.setLine(2, (m2 ? Util.formatCurrency(q2) : String.format("%.0f", q2) + " " + l2[1]) + ":" + String.format((m2 ? "%.2f" : "%.0f"), Util.roundDouble(r2)));
sign.setLine(1, (m1 ? Util.formatCurrency(q1) : ((int)q1) + " " + l1[1]) + ":" + String.format((m1 ? "%.2f" : "%.0f"), Util.roundDouble(r1)));
sign.setLine(2, (m2 ? Util.formatCurrency(q2) : ((int)q2) + " " + l2[1]) + ":" + String.format((m2 ? "%.2f" : "%.0f"), Util.roundDouble(r2)));
sign.update();
user.sendMessage(Util.i18n("tradeCompleted"));
}

View File

@ -258,6 +258,7 @@ public class EssentialsPlayerListener extends PlayerListener
return;
}
User user = ess.getUser(event.getPlayer());
user.setNPC(false);
if (user.isBanned())
{

View File

@ -48,16 +48,6 @@ public class Settings implements IConf
return config.getInt("default-stack-size", 64);
}
public String getCurrency()
{
return config.getString("currency-name", "Coin");
}
public String getCurrencyPlural()
{
return config.getString("currency-name-plural", "Coins");
}
public int getStartingBalance()
{
return config.getInt("starting-balance", 0);
@ -498,4 +488,9 @@ public class Settings implements IConf
{
return config.getString("locale", "");
}
public String getCurrencySymbol()
{
return config.getString("currency-symbol", "$").substring(0, 1).replaceAll("[0-9]", "$");
}
}

View File

@ -269,4 +269,36 @@ public class User extends UserData implements Comparable<User>, IReplyTo
{
lastActivity = timestamp;
}
@Override
public double getMoney()
{
if (ess.isIConomyFallbackEnabled())
{
try
{
return com.iConomy.iConomy.getAccount(getName()).getHoldings().balance();
}
catch (Throwable ex)
{
}
}
return super.getMoney();
}
@Override
public void setMoney(double value)
{
if (ess.isIConomyFallbackEnabled())
{
try
{
com.iConomy.iConomy.getAccount(getName()).getHoldings().set(value);
}
catch (Throwable ex)
{
}
}
super.setMoney(value);
}
}

View File

@ -36,6 +36,7 @@ public abstract class UserData extends PlayerExtension implements IConf
public final void reloadConfig()
{
config.load();
money = _getMoney();
unlimited = _getUnlimited();
powertools = getPowertools();
lastLocation = _getLastLocation();
@ -57,38 +58,28 @@ public abstract class UserData extends PlayerExtension implements IConf
geolocation = _getGeoLocation();
isSocialSpyEnabled = _isSocialSpyEnabled();
}
public double getMoney()
{
double money;
private double _getMoney() {
if (config.hasProperty("money"))
{
return config.getDouble("money", ess.getSettings().getStartingBalance());
}
if (ess.isIConomyFallbackEnabled())
else
{
try
{
return com.iConomy.iConomy.getAccount(getName()).getHoldings().balance();
}
catch (Throwable ex)
{
}
return ess.getSettings().getStartingBalance();
}
return ess.getSettings().getStartingBalance();
}
public double getMoney()
{
return money;
}
public void setMoney(double value)
{
if (ess.isIConomyFallbackEnabled())
{
try
{
com.iConomy.iConomy.getAccount(getName()).getHoldings().set(value);
}
catch (Throwable ex)
{
}
}
money = value;
config.setProperty("money", value);
config.save();
}
@ -690,10 +681,29 @@ public abstract class UserData extends PlayerExtension implements IConf
return isSocialSpyEnabled;
}
public void setSocialSpyEnabled(Boolean status)
public void setSocialSpyEnabled(boolean status)
{
isSocialSpyEnabled = status;
config.setProperty("socialspy", status);
config.save();
}
private boolean isNPC;
private boolean _isNPC()
{
return config.getBoolean("npc", false);
}
public boolean isNPC()
{
return isNPC;
}
void setNPC(boolean set)
{
isNPC = set;
config.setProperty("npc", set);
config.save();
}
}

View File

@ -270,11 +270,15 @@ public class Util
}
return isBlockAboveAir(world, x, y, z);
}
private static DecimalFormat df = new DecimalFormat("#.00");
private static DecimalFormat df = new DecimalFormat("#0.##");
public static String formatCurrency(double value)
{
return "$"+df.format(value);
String str = Essentials.getStatic().getSettings().getCurrencySymbol()+df.format(value);
if (str.endsWith(".")) {
return str.substring(0, str.length()-1);
}
return str;
}
public static double roundDouble(double d)

View File

@ -1,324 +1,260 @@
package com.earth2me.essentials.api;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.EssentialsConf;
import com.earth2me.essentials.User;
import com.earth2me.essentials.UserData;
import com.earth2me.essentials.Util;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import org.bukkit.Bukkit;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.entity.Player;
public class Economy
{
protected static Essentials ess = Essentials.getStatic();
private static final Logger logger = Logger.getLogger("Minecraft");
//Does the file exists?
protected static boolean accountCreated(String name)
private static void createNPCFile(String name)
{
File folder = new File(ess.getDataFolder(), "userdata");
File account = new File(folder, name.toLowerCase() + ".yml");
return account.exists();
File folder = new File(Essentials.getStatic().getDataFolder(), "userdata");
EssentialsConf npcConfig = new EssentialsConf(new File(folder, Util.sanitizeFileName(name) + ".yml"));
npcConfig.load();
npcConfig.setProperty("npc", true);
npcConfig.setProperty("money", Essentials.getStatic().getSettings().getStartingBalance());
npcConfig.save();
}
//We create the file for the NPC
protected static void createAccount(String name)
private static void deleteNPC(String name)
{
//Where we will store npc accounts!
File folder = new File(ess.getDataFolder(), "userdata");
File npcFile = new File(folder, name + ".yml");
try
{
if (!npcFile.createNewFile())
{
System.out.println("Failed file creation");
}
return;
}
catch (IOException e)
{
System.out.println("Could not create Non-player account file!");
}
FileWriter fileWriter = null;
BufferedWriter bufferWriter = null;
try
{
if (!npcFile.exists())
{
npcFile.createNewFile();
}
fileWriter = new FileWriter(npcFile);
bufferWriter = new BufferedWriter(fileWriter);
//This is the default for NPC's, 0
bufferWriter.append("money: ");
bufferWriter.append(((Integer)0).toString());
bufferWriter.newLine();
}
catch (IOException e)
{
System.out.println("Exception on config creation: ");
}
finally
{
try
{
if (bufferWriter != null)
{
bufferWriter.flush();
bufferWriter.close();
}
if (fileWriter != null)
{
fileWriter.close();
}
}
catch (IOException e)
{
System.out.println("IO Exception writing file: " + npcFile.getName());
File folder = new File(Essentials.getStatic().getDataFolder(), "userdata");
File config = new File(folder, Util.sanitizeFileName(name) + ".yml");
EssentialsConf npcConfig = new EssentialsConf(config);
npcConfig.load();
if (npcConfig.hasProperty("npc") && npcConfig.getBoolean("npc", false)) {
if (!config.delete()) {
logger.log(Level.WARNING, Util.format("deleteFileError", config));
}
}
}
//Convert a string into an essentials User
protected static User usrConv(String name)
private static User getUserByName(String name)
{
User user = null;
if (Bukkit.getServer().getPlayer(name) != null)
User user;
Player player = Essentials.getStatic().getServer().getPlayer(name);
if (player != null)
{
user = ess.getUser(Bukkit.getServer().getPlayer(name));
return user;
user = Essentials.getStatic().getUser(player);
}
else
{
user = ess.getOfflineUser(name);
user = Essentials.getStatic().getOfflineUser(name);
}
return user;
}
//We have to make sure the user exists, or they are an NPC!
public static boolean exist(String name)
/**
* Returns the balance of a user
* @param name Name of the user
* @return balance
* @throws UserDoesNotExistException
*/
public static double getMoney(String name) throws UserDoesNotExistException
{
if (name == null)
{
System.out.println("EcoAPI - Whatever plugin is calling for users that are null is BROKEN!");
return false;
User user = getUserByName(name);
if (user == null) {
throw new UserDoesNotExistException(name);
}
if (Bukkit.getServer().getPlayer(name) != null)
{
return true;
}
return false;
// Use UserData to avoid calls to iConomy and Register
return ((UserData)user).getMoney();
}
//Eco return balance
public static double getMoney(String name)
/**
* Sets the balance of a user
* @param name Name of the user
* @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
*/
public static void setMoney(String name, double balance) throws UserDoesNotExistException, NoLoanPermittedException
{
if (!exist(name))
{
if (accountCreated(name))
{
User user = usrConv(name);
return user.getMoney();
}
return 0;
User user = getUserByName(name);
if (user == null) {
throw new UserDoesNotExistException(name);
}
User user = usrConv(name);
return user.getMoney();
}
//Eco Set Money
public static void setMoney(String name, double bal)
{
if (!exist(name))
if (balance < 0.0 && !user.isAuthorized("essentials.eco.loan"))
{
if (accountCreated(name))
{
User user = usrConv(name);
user.setMoney(bal);
}
return;
throw new NoLoanPermittedException();
}
User user = usrConv(name);
user.setMoney(bal);
return;
// Use UserData to avoid calls to iConomy and Register
((UserData)user).setMoney(balance);
}
//Eco add balance
public static void add(String name, double money)
/**
* Adds money to the balance of a user
* @param name Name of the user
* @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
*/
public static void add(String name, double amount) throws UserDoesNotExistException, NoLoanPermittedException
{
double result;
if (!exist(name))
{
if (accountCreated(name))
{
result = getMoney(name) + money;
setMoney(name,result);
}
return;
}
result = getMoney(name) + money;
setMoney(name,result);
return;
double result = getMoney(name) + amount;
setMoney(name, result);
}
//Eco divide balance
public static void divide(String name, double money)
/**
* Substracts money from the balance of a user
* @param name Name of the user
* @param amount The money you want to substract
* @throws UserDoesNotExistException If a user by that name does not exists
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
*/
public static void subtract(String name, double amount) throws UserDoesNotExistException, NoLoanPermittedException
{
double result;
if (!exist(name))
{
if (accountCreated(name))
{
result = getMoney(name)/ money;
setMoney(name,result);
return;
}
return;
}
result = getMoney(name) / money;
setMoney(name,result);
return;
double result = getMoney(name) - amount;
setMoney(name, result);
}
//Eco multiply balance
public static void multiply(String name, double money)
/**
* Divides the balance of a user by a value
* @param name Name of the user
* @param value 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
*/
public static void divide(String name, double value) throws UserDoesNotExistException, NoLoanPermittedException
{
double result;
if (!exist(name))
{
if (accountCreated(name))
{
result = getMoney(name) * money;
setMoney(name,result);
return;
}
return;
}
result = getMoney(name) * money;
setMoney(name,result);
return;
double result = getMoney(name) / value;
setMoney(name, result);
}
//Eco subtract balance
public static void subtract(String name, double money)
/**
* Multiplies the balance of a user by a value
* @param name Name of the user
* @param value 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
*/
public static void multiply(String name, double value) throws UserDoesNotExistException, NoLoanPermittedException
{
double result;
if (!exist(name))
{
if (accountCreated(name))
{
result = getMoney(name) - money;
setMoney(name,result);
return;
}
return;
}
result = getMoney(name) - money;
setMoney(name,result);
return;
double result = getMoney(name) * value;
setMoney(name, result);
}
//Eco reset balance!
public static void resetBalance(String name)
/**
* Resets the balance of a user to the starting balance
* @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
*/
public static void resetBalance(String name) throws UserDoesNotExistException, NoLoanPermittedException
{
setMoney(name, 0);
setMoney(name, Essentials.getStatic().getSettings().getStartingBalance());
}
//Eco has enough check
public static boolean hasEnough(String name, double amount)
/**
* @param name Name of the user
* @param amount The amount of money the user should have
* @return true, if the user has more or an equal amount of money
* @throws UserDoesNotExistException If a user by that name does not exists
*/
public static boolean hasEnough(String name, double amount) throws UserDoesNotExistException
{
return amount <= getMoney(name);
}
//Eco hasMore balance check
public static boolean hasMore(String name, double amount)
/**
* @param name Name of the user
* @param amount The amount of money the user should have
* @return true, if the user has more money
* @throws UserDoesNotExistException If a user by that name does not exists
*/
public static boolean hasMore(String name, double amount) throws UserDoesNotExistException
{
return amount < getMoney(name);
}
//Eco hasLess balance check
public static boolean hasLess(String name, double amount)
/**
* @param name Name of the user
* @param amount The amount of money the user should not have
* @return true, if the user has less money
* @throws UserDoesNotExistException If a user by that name does not exists
*/
public static boolean hasLess(String name, double amount) throws UserDoesNotExistException
{
return amount > getMoney(name);
}
//Eco currency
public static String getCurrency()
{
return ess.getSettings().getCurrency();
}
//Eco currency Plural
public static String getCurrencyPlural()
{
return ess.getSettings().getCurrencyPlural();
}
//Eco is negative check!
public static boolean isNegative(String name)
/**
* Test if the user has a negative balance
* @param name Name of the user
* @return true, if the user has a negative balance
* @throws UserDoesNotExistException If a user by that name does not exists
*/
public static boolean isNegative(String name) throws UserDoesNotExistException
{
return getMoney(name) < 0.0;
}
//Eco Formatter
/**
* Formats the amount of money like all other Essentials functions.
* Example: $100000 or $12345.67
* @param amount The amount of money
* @return Formatted money
*/
public static String format(double amount)
{
DecimalFormat ecoForm = new DecimalFormat("#,##0.##");
String formed = ecoForm.format(amount);
if (formed.endsWith("."))
{
formed = formed.substring(0, formed.length() - 1);
return Util.formatCurrency(amount);
}
/**
* Test if a player exists to avoid the UserDoesNotExistException
* @param name Name of the user
* @return true, if the user exists
*/
public static boolean playerExists(String name) {
return getUserByName(name) != null;
}
/**
* Test if a player is a npc
* @param name Name of the player
* @return true, if it's a npc
* @throws UserDoesNotExistException
*/
public static boolean isNPC(String name) throws UserDoesNotExistException
{
User user = getUserByName(name);
if (user == null) {
throw new UserDoesNotExistException(name);
}
return user.isNPC();
}
/**
* Creates dummy files for a npc, if there is no player yet with that name.
* @param name Name of the player
*/
public static void createNPC(String name)
{
User user = getUserByName(name);
if (user == null) {
createNPCFile(name);
}
return formed + " " + ((amount <= 1 && amount >= -1) ? getCurrency() : getCurrencyPlural());
}
//************************!WARNING!**************************
//**********DO NOT USING THE FOLLOWING FOR PLAYERS!**********
//**************THESE ARE FOR NPC ACCOUNTS ONLY!*************
//Eco account exist for NPCs ONLY!
public static boolean accountExist(String account)
/**
* Deletes a user, if it is marked as npc.
* @param name Name of the player
* @throws UserDoesNotExistException
*/
public static void removeNPC(String name) throws UserDoesNotExistException
{
return accountCreated(account);
}
//Eco NPC account creator! Will return false if it already exists.
public static boolean newAccount(String account)
{
if (!exist(account))
{
if (!accountCreated(account))
{
createAccount(account);
return true;
}
return false;
User user = getUserByName(name);
if (user == null) {
throw new UserDoesNotExistException(name);
}
return false;
}
//Eco remove account, only use this for NPCS!
public static void removeAccount(String name)
{
if (!exist(name))
{
if (accountCreated(name))
{
File folder = new File(ess.getDataFolder(), "userdata");
File account = new File(folder, Util.sanitizeFileName(name) + ".yml");
account.delete();
}
}
return;
deleteNPC(name);
}
}

View File

@ -0,0 +1,13 @@
package com.earth2me.essentials.api;
import com.earth2me.essentials.Util;
public class NoLoanPermittedException extends Exception
{
public NoLoanPermittedException()
{
super(Util.i18n("negativeBalanceError"));
}
}

View File

@ -0,0 +1,13 @@
package com.earth2me.essentials.api;
import com.earth2me.essentials.Util;
public class UserDoesNotExistException extends Exception
{
public UserDoesNotExistException(String name)
{
super(Util.format("userDoesNotExist", name));
}
}

View File

@ -223,15 +223,10 @@ command-costs:
# /example costs $1000 PER USE
#example: 1000
# /kit tools costs $1500 PER USE
# kit-tools: 1500
#kit-tools: 1500
#This defines the name of your currencies, in singular and plural
currency-name: Coin
currency-name-plural: Coins
# Set this to a currency symbol you want to use.
currency-symbol: '$'
############################################################
# +------------------------------------------------------+ #

View File

@ -243,4 +243,7 @@ suicideMessage = \u00a77Goodbye Cruel World...
suicideSuccess = \u00a77{0} took their own life
tempBanned = Temporarily banned from server for {0}
thunderDuration = You {0} thunder in your world {1}
thunder = You {0} thunder in your world
thunder = You {0} thunder in your world
deleteFileError = Could not delete file: {0}
userDoesNotExist = The user {0} does not exist.
negativeBalanceError = User is not allowed to have a negative balance.