org.spongepowered.api.service.economy.account.UniqueAccount Java Examples

The following examples show how to use org.spongepowered.api.service.economy.account.UniqueAccount. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SetCommand.java    From EconomyLite with MIT License 6 votes vote down vote up
@Override
public void run(CommandSource src, CommandContext args) {
    if (args.getOne("player").isPresent() && args.getOne("balance").isPresent()) {
        User target = args.<User>getOne("player").get();
        String targetName = target.getName();
        BigDecimal newBal = BigDecimal.valueOf(args.<Double>getOne("balance").get());
        Optional<UniqueAccount> uOpt = EconomyLite.getEconomyService().getOrCreateAccount(target.getUniqueId());
        if (uOpt.isPresent()) {
            UniqueAccount targetAccount = uOpt.get();
            if (targetAccount.setBalance(EconomyLite.getCurrencyService().getCurrentCurrency(), newBal,
                    Cause.of(EventContext.empty(),(EconomyLite.getInstance()))).getResult().equals(ResultType.SUCCESS)) {
                src.sendMessage(messageStorage.getMessage("command.econ.setsuccess", "name", targetName));
                attemptNotify(target);
            } else {
                src.sendMessage(messageStorage.getMessage("command.econ.setfail", "name", targetName));
            }
        } else {
            src.sendMessage(messageStorage.getMessage("command.error"));
        }
    } else {
        src.sendMessage(messageStorage.getMessage("command.error"));
    }
}
 
Example #2
Source File: LiteEconomyService.java    From EconomyLite with MIT License 6 votes vote down vote up
@Override
public Optional<UniqueAccount> getOrCreateAccount(UUID uuid) {
    if (playerService.accountExists(uuid, getDefaultCurrency(), CauseFactory.create("New account check"))) {
        // Return the account
        return Optional.of(new LiteUniqueAccount(uuid));
    } else {
        // Make a new account
        UniqueAccount account = new LiteUniqueAccount(uuid);
        if (playerService.setBalance(uuid, account.getDefaultBalance(getDefaultCurrency()), getDefaultCurrency(),
                CauseFactory.create("Creating account"))) {
            return Optional.of(account);
        } else {
            return Optional.empty();
        }
    }
}
 
Example #3
Source File: PlayerServiceCommon.java    From EconomyLite with MIT License 6 votes vote down vote up
public List<UniqueAccount> getTopAccounts(int start, int end, Cause cause) {
    debug("playercommon: Getting top accounts - " + cause.toString());
    String mid = start + "-" + end + ":" + EconomyLite.getEconomyService().getDefaultCurrency().getId();
    List<UniqueAccount> accounts = topCache.getIfPresent(mid);
    if (accounts != null) {
        return accounts;
    }
    int offset = start - 1;
    int limit = end - offset;
    accounts = new ArrayList<>();
    List<String> uuids =
            manager.queryTypeList("uuid", String.class,
                    "SELECT uuid FROM economyliteplayers WHERE currency = ? ORDER BY balance DESC LIMIT ?, ?",
                    EconomyLite.getEconomyService().getDefaultCurrency().getId(), offset, limit);
    EconomyService ecoService = EconomyLite.getEconomyService();
    for (String uuid : uuids) {
        Optional<UniqueAccount> uOpt = ecoService.getOrCreateAccount(UUID.fromString(uuid));
        if (uOpt.isPresent()) {
            accounts.add(uOpt.get());
        }
    }
    topCache.update(mid, accounts);
    return accounts;
}
 
Example #4
Source File: PayVirtualCommand.java    From EconomyLite with MIT License 6 votes vote down vote up
@Override
public void run(Player src, CommandContext args) {
    if (args.getOne("target").isPresent() && args.getOne("amount").isPresent()) {
        String target = args.<String>getOne("target").get();
        BigDecimal amount = BigDecimal.valueOf(args.<Double>getOne("amount").get());
        Optional<Account> aOpt = EconomyLite.getEconomyService().getOrCreateAccount(target);
        Optional<UniqueAccount> uOpt = EconomyLite.getEconomyService().getOrCreateAccount(src.getUniqueId());
        // Check for negative payments
        if (amount.doubleValue() <= 0) {
            src.sendMessage(messageStorage.getMessage("command.pay.invalid"));
        } else {
            if (aOpt.isPresent() && uOpt.isPresent()) {
                Account receiver = aOpt.get();
                UniqueAccount payer = uOpt.get();
                if (payer.transfer(receiver, ecoService.getDefaultCurrency(), amount, Cause.of(EventContext.empty(), (EconomyLite.getInstance())))
                        .getResult().equals(ResultType.SUCCESS)) {
                    src.sendMessage(messageStorage.getMessage("command.pay.success", "target", receiver.getDisplayName().toPlain()));
                } else {
                    src.sendMessage(messageStorage.getMessage("command.pay.failed", "target", receiver.getDisplayName().toPlain()));
                }
            }
        }
    } else {
        src.sendMessage(messageStorage.getMessage("command.error"));
    }
}
 
Example #5
Source File: AddCommand.java    From EconomyLite with MIT License 6 votes vote down vote up
@Override
public void run(CommandSource src, CommandContext args) {
    if (args.getOne("player").isPresent() && args.getOne("amount").isPresent()) {
        User target = args.<User>getOne("player").get();
        String targetName = target.getName();
        BigDecimal toAdd = BigDecimal.valueOf(args.<Double>getOne("amount").get());
        Optional<UniqueAccount> uOpt = EconomyLite.getEconomyService().getOrCreateAccount(target.getUniqueId());
        if (uOpt.isPresent()) {
            UniqueAccount targetAccount = uOpt.get();
            if (targetAccount.deposit(EconomyLite.getCurrencyService().getCurrentCurrency(), toAdd,
                    Cause.of(EventContext.empty(),(EconomyLite.getInstance()))).getResult().equals(ResultType.SUCCESS)) {
                src.sendMessage(messageStorage.getMessage("command.econ.addsuccess", "name", targetName));
                attemptNotify(target);
            } else {
                src.sendMessage(messageStorage.getMessage("command.econ.addfail", "name", targetName));
            }
        } else {
            src.sendMessage(messageStorage.getMessage("command.error"));
        }
    } else {
        src.sendMessage(messageStorage.getMessage("command.error"));
    }
}
 
Example #6
Source File: RemoveCommand.java    From EconomyLite with MIT License 6 votes vote down vote up
@Override
public void run(CommandSource src, CommandContext args) {
    if (args.getOne("player").isPresent() && args.getOne("amount").isPresent()) {
        User target = args.<User>getOne("player").get();
        String targetName = target.getName();
        BigDecimal toRemove = BigDecimal.valueOf(args.<Double>getOne("amount").get());
        Optional<UniqueAccount> uOpt = EconomyLite.getEconomyService().getOrCreateAccount(target.getUniqueId());
        if (uOpt.isPresent()) {
            UniqueAccount targetAccount = uOpt.get();
            if (targetAccount.withdraw(EconomyLite.getCurrencyService().getCurrentCurrency(), toRemove,
                    Cause.of(EventContext.empty(),(EconomyLite.getInstance()))).getResult().equals(ResultType.SUCCESS)) {
                src.sendMessage(messageStorage.getMessage("command.econ.removesuccess", "name", targetName));
                attemptNotify(target);
            } else {
                src.sendMessage(messageStorage.getMessage("command.econ.removefail", "name", targetName));
            }
        } else {
            src.sendMessage(messageStorage.getMessage("command.error"));
        }
    } else {
        src.sendMessage(messageStorage.getMessage("command.error"));
    }
}
 
Example #7
Source File: PayCommand.java    From EconomyLite with MIT License 5 votes vote down vote up
private void pay(User target, BigDecimal amount, Player src) {
    String targetName = target.getName();
    if (!target.getUniqueId().equals(src.getUniqueId())) {
        Optional<UniqueAccount> uOpt = ecoService.getOrCreateAccount(src.getUniqueId());
        Optional<UniqueAccount> tOpt = ecoService.getOrCreateAccount(target.getUniqueId());
        if (uOpt.isPresent() && tOpt.isPresent()) {
            if (uOpt.get()
                    .transfer(tOpt.get(), ecoService.getDefaultCurrency(), amount, Cause.of(EventContext.empty(), (EconomyLite.getInstance())))
                    .getResult().equals(ResultType.SUCCESS)) {
                Text label = ecoService.getDefaultCurrency().getPluralDisplayName();
                if (amount.equals(BigDecimal.ONE)) {
                    label = ecoService.getDefaultCurrency().getDisplayName();
                }
                src.sendMessage(messageStorage.getMessage("command.pay.success", "target", targetName, "amountandlabel",
                        String.format(Locale.ENGLISH, "%,.2f", amount) + " " + label.toPlain()));
                final Text curLabel = label;
                Sponge.getServer().getPlayer(target.getUniqueId()).ifPresent(p -> {
                    p.sendMessage(messageStorage.getMessage("command.pay.target", "amountandlabel",
                            String.format(Locale.ENGLISH, "%,.2f", amount) + " " + curLabel.toPlain(), "sender",
                            uOpt.get().getDisplayName().toPlain()));
                });
            } else {
                src.sendMessage(messageStorage.getMessage("command.pay.failed", "target", targetName));
            }
        } else {
            src.sendMessage(messageStorage.getMessage("command.error"));
        }
    } else {
        src.sendMessage(messageStorage.getMessage("command.pay.notyou"));
    }
}
 
Example #8
Source File: VirtualPayCommand.java    From EconomyLite with MIT License 5 votes vote down vote up
@Override
public void run(CommandSource src, CommandContext args) {
    if (args.getOne("account").isPresent() && args.getOne("target").isPresent() && args.getOne("amount").isPresent()) {
        String account = args.<String>getOne("account").get();
        User target = args.<User>getOne("target").get();
        BigDecimal amount = BigDecimal.valueOf(args.<Double>getOne("amount").get());
        Optional<Account> aOpt = EconomyLite.getEconomyService().getOrCreateAccount(account);
        Optional<UniqueAccount> uOpt = EconomyLite.getEconomyService().getOrCreateAccount(target.getUniqueId());
        // Check for negative payments
        if (amount.compareTo(BigDecimal.ONE) == -1) {
            src.sendMessage(messageStorage.getMessage("command.pay.invalid"));
        } else {
            if (aOpt.isPresent() && uOpt.isPresent()) {
                Account payer = aOpt.get();
                UniqueAccount receiver = uOpt.get();
                if (payer.transfer(receiver, ecoService.getDefaultCurrency(), amount, Cause.of(EventContext.empty(), EconomyLite.getInstance
                        ()))
                        .getResult().equals(ResultType.SUCCESS)) {
                    src.sendMessage(messageStorage.getMessage("command.pay.success", "target", target.getName()));
                    if (target instanceof Player) {
                        Text label = ecoService.getDefaultCurrency().getPluralDisplayName();
                        if (amount.equals(BigDecimal.ONE)) {
                            label = ecoService.getDefaultCurrency().getDisplayName();
                        }
                        ((Player) target).sendMessage(messageStorage.getMessage("command.pay.target", "amountandlabel",
                                String.format(Locale.ENGLISH, "%,.2f", amount) + " " + label.toPlain(), "sender",
                                payer.getDisplayName().toPlain()));
                    }
                } else {
                    src.sendMessage(messageStorage.getMessage("command.pay.failed", "target", target.getName()));
                }
            }
        }
    } else {
        src.sendMessage(messageStorage.getMessage("command.error"));
    }
}
 
Example #9
Source File: LoanManager.java    From EconomyLite with MIT License 5 votes vote down vote up
/**
 * Adds currency to a player's loan balance. Automatically charges interest
 * and adds to the player's account.
 *
 * @param uuid The player.
 * @param amount The amount to add.
 * @return If the amount was added successfully.
 */
public boolean addLoanBalance(UUID uuid, double amount) {
    Currency cur = eco.getDefaultCurrency();
    Optional<Double> bOpt = getLoanBalance(uuid);
    Optional<UniqueAccount> uOpt = eco.getOrCreateAccount(uuid);
    if (bOpt.isPresent() && uOpt.isPresent()) {
        double bal = bOpt.get();
        if (amount < 0 || bal + (amount * module.getInterestRate()) > module.getMaxLoan()) {
            return false;
        }
        return (setLoanBalance(uuid, (amount * module.getInterestRate()) + bal) && uOpt.get()
                .deposit(cur, BigDecimal.valueOf(amount), CauseFactory.stringCause("loan")).getResult().equals(ResultType.SUCCESS));
    }
    return false;
}
 
Example #10
Source File: LoanManager.java    From EconomyLite with MIT License 5 votes vote down vote up
/**
 * Removes loan balance from a player. Automatically removes funds from the
 * player's account.
 *
 * @param uuid The player.
 * @param amount The amount to remove.
 * @return If the amount was removed successfully.
 */
public boolean removeLoanBalance(UUID uuid, double amount) {
    Currency cur = eco.getDefaultCurrency();
    Optional<Double> bOpt = getLoanBalance(uuid);
    Optional<UniqueAccount> uOpt = eco.getOrCreateAccount(uuid);
    if (bOpt.isPresent() && uOpt.isPresent()) {
        double bal = bOpt.get();
        if (bal - amount < 0 || amount < 0) {
            return false;
        }
        return (uOpt.get().withdraw(cur, BigDecimal.valueOf(amount), CauseFactory.stringCause("loan")).getResult()
                .equals(ResultType.SUCCESS) && setLoanBalance(uuid, bal - amount));
    }
    return false;
}
 
Example #11
Source File: NationWithdrawExecutor.java    From Nations with MIT License 4 votes vote down vote up
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
{
	if (src instanceof Player)
	{
		if (!ctx.<Double>getOne("amount").isPresent())
		{
			src.sendMessage(Text.of(TextColors.YELLOW, "/n deposit <amount>\n/n withdraw <amount>"));
			return CommandResult.success();
		}
		
		Player player = (Player) src;
		Nation nation = DataHandler.getNationOfPlayer(player.getUniqueId());
		if (nation == null)
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NONATION));
			return CommandResult.success();
		}
		if (!nation.isStaff(player.getUniqueId()))
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_PERM_NATIONSTAFF));
			return CommandResult.success();
		}
		
		if (NationsPlugin.getEcoService() == null)
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NOECO));
			return CommandResult.success();
		}
		Optional<UniqueAccount> optAccount = NationsPlugin.getEcoService().getOrCreateAccount(player.getUniqueId());
		if (!optAccount.isPresent())
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_ECONOACCOUNT));
			return CommandResult.success();
		}
		Optional<Account> optNationAccount = NationsPlugin.getEcoService().getOrCreateAccount("nation-" + nation.getUUID().toString());
		if (!optNationAccount.isPresent())
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_ECONONATION));
			return CommandResult.success();
		}
		BigDecimal amount = BigDecimal.valueOf(ctx.<Double>getOne("amount").get());
		TransactionResult result = optNationAccount.get().transfer(optAccount.get(), NationsPlugin.getEcoService().getDefaultCurrency(), amount, NationsPlugin.getCause());
		if (result.getResult() == ResultType.ACCOUNT_NO_FUNDS)
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NOENOUGHMONEYNATION));
			return CommandResult.success();
		}
		else if (result.getResult() != ResultType.SUCCESS)
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_ECOTRANSACTION));
			return CommandResult.success();
		}
		
		String[] s1 = LanguageHandler.SUCCESS_WITHDRAW.split("\\{AMOUNT\\}");
		Builder builder = Text.builder();
		if (s1[0].indexOf("\\{BALANCE\\}") >= 0)
		{
			builder
			.append(Text.of(TextColors.GREEN, s1[0].split("\\{BALANCE\\}")[0]))
			.append(Utils.formatPrice(TextColors.GREEN, optNationAccount.get().getBalance(NationsPlugin.getEcoService().getDefaultCurrency())))
			.append(Text.of(TextColors.GREEN, s1[0].split("\\{BALANCE\\}")[1]));
		}
		builder.append(Utils.formatPrice(TextColors.GREEN, amount));
		if (s1[1].indexOf("\\{BALANCE\\}") >= 0)
		{
			builder
			.append(Text.of(TextColors.GREEN, s1[1].split("\\{BALANCE\\}")[0]))
			.append(Utils.formatPrice(TextColors.GREEN, optNationAccount.get().getBalance(NationsPlugin.getEcoService().getDefaultCurrency())))
			.append(Text.of(TextColors.GREEN, s1[1].split("\\{BALANCE\\}")[1]));
		}
		src.sendMessage(builder.build());
	}
	else
	{
		src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NOPLAYER));
	}
	return CommandResult.success();
}
 
Example #12
Source File: Utils.java    From Nations with MIT License 4 votes vote down vote up
public static Text formatCitizenDescription(String name)
{
	UUID uuid = DataHandler.getPlayerUUID(name);
	if (uuid == null)
	{
		return Text.of(TextColors.RED, LanguageHandler.FORMAT_UNKNOWN);
	}

	Builder builder = Text.builder("");
	builder.append(
			Text.of(TextColors.GOLD, "----------{ "),
			Text.of(TextColors.YELLOW,
					DataHandler.getCitizenTitle(uuid) + " - " + name),
			Text.of(TextColors.GOLD, " }----------")
			);

	BigDecimal balance = null;
	EconomyService service = NationsPlugin.getEcoService();
	if (service != null)
	{
		Optional<UniqueAccount> optAccount = NationsPlugin.getEcoService().getOrCreateAccount(uuid);
		if (optAccount.isPresent())
		{
			balance = optAccount.get().getBalance(NationsPlugin.getEcoService().getDefaultCurrency());
		}
	}
	builder.append(
			Text.of(TextColors.GOLD, "\n" + LanguageHandler.FORMAT_MONEY + ": "),
			((balance == null) ? Text.of(TextColors.GRAY, LanguageHandler.FORMAT_UNKNOWN) : Text.builder()
					.append(Text.of(TextColors.YELLOW, NationsPlugin.getEcoService().getDefaultCurrency().format(balance)))
					.append(Text.of(TextColors.YELLOW, NationsPlugin.getEcoService().getDefaultCurrency().getSymbol()))
					.build())
			);

	builder.append(Text.of(TextColors.GOLD, "\n" + LanguageHandler.FORMAT_NATION + ": "));
	Nation nation = DataHandler.getNationOfPlayer(uuid);
	if (nation != null)
	{
		builder.append(nationClickable(TextColors.YELLOW, nation.getRealName()));
		if (nation.isPresident(uuid))
		{
			builder.append(Text.of(TextColors.YELLOW, " (" + LanguageHandler.FORMAT_PRESIDENT + ")"));
		}
		else if (nation.isMinister(uuid))
		{
			builder.append(Text.of(TextColors.YELLOW, " (" + LanguageHandler.FORMAT_MINISTERS + ")"));
		}

		builder.append(Text.of(TextColors.GOLD, "\n" + LanguageHandler.FORMAT_ZONES + ": "));
		boolean ownNothing = true;
		for (Zone zone : nation.getZones().values())
		{
			if (uuid.equals(zone.getOwner()) && zone.isNamed())
			{
				if (ownNothing)
				{
					ownNothing = false;
				}
				else
				{
					builder.append(Text.of(TextColors.YELLOW, ", "));
				}
				builder.append(zoneClickable(TextColors.YELLOW, zone.getRealName()));
			}
		}
		if (ownNothing)
		{
			builder.append(Text.of(TextColors.GRAY, LanguageHandler.FORMAT_NONE));
		}
	}
	else
	{
		builder.append(Text.of(TextColors.GRAY, LanguageHandler.FORMAT_NONE));
	}

	return builder.build();
}
 
Example #13
Source File: GPClaimManager.java    From GriefPrevention with MIT License 4 votes vote down vote up
public void deleteClaimInternal(Claim claim, boolean deleteChildren) {
    final GPClaim gpClaim = (GPClaim) claim;
    List<Claim> subClaims = claim.getChildren(false);
    for (Claim child : subClaims) {
        if (deleteChildren || (gpClaim.parent == null && child.isSubdivision())) {
            this.deleteClaimInternal(child, true);
            continue;
        }

        final GPClaim parentClaim = (GPClaim) claim;
        final GPClaim childClaim = (GPClaim) child;
        if (parentClaim.parent != null) {
            migrateChildToNewParent(parentClaim.parent, childClaim);
        } else {
            // move child to parent folder
            migrateChildToNewParent(null, childClaim);
        }
    }

    resetPlayerClaimVisuals(claim);
    // transfer bank balance to owner
    final Account bankAccount = claim.getEconomyAccount().orElse(null);
    if (bankAccount != null) {
        try (final CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) {
            Sponge.getCauseStackManager().pushCause(GriefPreventionPlugin.instance);
            final EconomyService economyService = GriefPreventionPlugin.instance.economyService.get();
            final UniqueAccount ownerAccount = economyService.getOrCreateAccount(claim.getOwnerUniqueId()).orElse(null);
            if (ownerAccount != null) {
                ownerAccount.deposit(economyService.getDefaultCurrency(), bankAccount.getBalance(economyService.getDefaultCurrency()),
                    Sponge.getCauseStackManager().getCurrentCause());
            }
            bankAccount.resetBalance(economyService.getDefaultCurrency(), Sponge.getCauseStackManager().getCurrentCause());
        }
    }
    this.worldClaims.remove(claim);
    this.claimUniqueIdMap.remove(claim.getUniqueId());
    this.deleteChunkHashes((GPClaim) claim);
    if (gpClaim.parent != null) {
        gpClaim.parent.children.remove(claim);
    }

    DATASTORE.deleteClaimFromSecondaryStorage((GPClaim) claim);
}
 
Example #14
Source File: CommandHandlers.java    From RedProtect with GNU General Public License v3.0 4 votes vote down vote up
public static void handleDelete(Player p) {
    Region r = RedProtect.get().rm.getTopRegion(p.getLocation(), CommandHandlers.class.getName());
    if (RedProtect.get().ph.hasRegionPermLeader(p, "delete", r)) {
        if (r == null) {
            RedProtect.get().lang.sendMessage(p, "cmdmanager.region.todo.that");
            return;
        }

        int claims = RedProtect.get().config.configRoot().region_settings.can_delete_first_home_after_claims;
        if (!r.canDelete() && (claims == -1 || RedProtect.get().rm.getPlayerRegions(p.getName(), p.getWorld().getName()) < claims) && !p.hasPermission("redprotect.bypass")) {
            if (claims != -1) {
                RedProtect.get().lang.sendMessage(p, RedProtect.get().lang.get("cmdmanager.region.cantdeletefirst-claims").replace("{claims}", "" + claims));
            } else {
                RedProtect.get().lang.sendMessage(p, RedProtect.get().lang.get("cmdmanager.region.cantdeletefirst"));
            }
            return;
        }

        DeleteRegionEvent event = new DeleteRegionEvent(r, p);
        if (Sponge.getEventManager().post(event)) {
            return;
        }

        String rname = r.getName();
        String w = r.getWorld();
        RedProtect.get().rm.remove(r, w);
        RedProtect.get().lang.sendMessage(p, RedProtect.get().lang.get("cmdmanager.region.deleted") + " " + rname);
        RedProtect.get().logger.addLog("(World " + w + ") Player " + p.getName() + " REMOVED region " + rname);

        // Handle money
        if (RedProtect.get().config.ecoRoot().claim_cost_per_block.enable && !p.hasPermission("redprotect.eco.bypass")) {
            UniqueAccount acc = RedProtect.get().economy.getOrCreateAccount(p.getUniqueId()).get();
            long reco = r.getArea() * RedProtect.get().config.ecoRoot().claim_cost_per_block.cost_per_block;

            if (!RedProtect.get().config.ecoRoot().claim_cost_per_block.y_is_free) {
                reco = reco * Math.abs(r.getMaxY() - r.getMinY());
            }

            if (reco > 0) {
                acc.deposit(RedProtect.get().economy.getDefaultCurrency(), BigDecimal.valueOf(reco), RedProtect.get().getVersionHelper().getCause(p));
                p.sendMessage(RedProtect.get().getUtil().toText(RedProtect.get().lang.get("economy.region.deleted").replace("{price}", RedProtect.get().config.ecoRoot().economy_symbol + reco + " " + RedProtect.get().config.ecoRoot().economy_name)));
            }
        }
    } else {
        RedProtect.get().lang.sendMessage(p, "no.permission");
    }
}
 
Example #15
Source File: NationCreateExecutor.java    From Nations with MIT License 4 votes vote down vote up
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
{
	if (!ctx.<String>getOne("name").isPresent())
	{
		src.sendMessage(Text.of(TextColors.YELLOW, "/n create <name>"));
		return CommandResult.success();
	}
	if (src instanceof Player)
	{
		Player player = (Player) src;
		if (!ConfigHandler.getNode("worlds").getNode(player.getWorld().getName()).getNode("enabled").getBoolean())
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_PLUGINDISABLEDINWORLD));
			return CommandResult.success();
		}
		if (DataHandler.getNationOfPlayer(player.getUniqueId()) != null)
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NEEDLEAVE));
			return CommandResult.success();
		}
		String nationName = ctx.<String>getOne("name").get();
		if (DataHandler.getNation(nationName) != null)
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NAMETAKEN));
			return CommandResult.success();
		}
		if (!nationName.matches("[\\p{Alnum}\\p{IsIdeographic}\\p{IsLetter}\"_\"]*"))
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NAMEALPHA));
			return CommandResult.success();
		}
		if (nationName.length() < ConfigHandler.getNode("others", "minNationNameLength").getInt() || nationName.length() > ConfigHandler.getNode("others", "maxNationNameLength").getInt())
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NAMELENGTH
					.replaceAll("\\{MIN\\}", ConfigHandler.getNode("others", "minNationNameLength").getString())
					.replaceAll("\\{MAX\\}", ConfigHandler.getNode("others", "maxNationNameLength").getString())));
			return CommandResult.success();
		}
		
		if (NationsPlugin.getEcoService() == null)
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NOECO));
			return CommandResult.success();
		}
		Optional<UniqueAccount> optAccount = NationsPlugin.getEcoService().getOrCreateAccount(player.getUniqueId());
		if (!optAccount.isPresent())
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_ECONOACCOUNT));
			return CommandResult.success();
		}
		BigDecimal price = BigDecimal.valueOf(ConfigHandler.getNode("prices", "nationCreationPrice").getDouble());
		TransactionResult result = optAccount.get().withdraw(NationsPlugin.getEcoService().getDefaultCurrency(), price, NationsPlugin.getCause());
		if (result.getResult() == ResultType.ACCOUNT_NO_FUNDS)
		{
			src.sendMessage(Text.builder()
					.append(Text.of(TextColors.RED, LanguageHandler.ERROR_NEEDMONEY.split("\\{AMOUNT\\}")[0]))
					.append(Utils.formatPrice(TextColors.RED, price))
					.append(Text.of(TextColors.RED, LanguageHandler.ERROR_NEEDMONEY.split("\\{AMOUNT\\}")[1])).build());
			return CommandResult.success();
		}
		else if (result.getResult() != ResultType.SUCCESS)
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_ECOTRANSACTION));
			return CommandResult.success();
		}
		
		Nation nation = new Nation(UUID.randomUUID(), nationName);
		nation.addCitizen(player.getUniqueId());
		nation.setPresident(player.getUniqueId());
		Optional<Account> optNationAccount = NationsPlugin.getEcoService().getOrCreateAccount("nation-" + nation.getUUID().toString());
		if (!optNationAccount.isPresent())
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_CREATEECONATION));
			NationsPlugin.getLogger().error("Could not create nation's account on the economy service !");
			return CommandResult.success();
		}
		optNationAccount.get().setBalance(NationsPlugin.getEcoService().getDefaultCurrency(), BigDecimal.ZERO, NationsPlugin.getCause());
		DataHandler.addNation(nation);
		MessageChannel.TO_ALL.send(Text.of(TextColors.AQUA, LanguageHandler.INFO_NEWNATIONANNOUNCE.replaceAll("\\{PLAYER\\}", player.getName()).replaceAll("\\{NATION\\}", nation.getName())));
		src.sendMessage(Text.of(TextColors.GREEN, LanguageHandler.INFO_NEWNATION.replaceAll("\\{NATION\\}", nation.getName())));
	}
	else
	{
		src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NOPLAYER));
	}
	return CommandResult.success();
}
 
Example #16
Source File: GDClaimManager.java    From GriefDefender with MIT License 4 votes vote down vote up
public ClaimResult deleteClaimInternal(Claim claim, boolean deleteChildren) {
    final GDClaim gdClaim = (GDClaim) claim;
    Set<Claim> subClaims = claim.getChildren(false);
    for (Claim child : subClaims) {
        if (deleteChildren || (gdClaim.parent == null && child.isSubdivision())) {
            this.deleteClaimInternal(child, true);
            continue;
        }

        final GDClaim parentClaim = (GDClaim) claim;
        final GDClaim childClaim = (GDClaim) child;
        if (parentClaim.parent != null) {
            migrateChildToNewParent(parentClaim.parent, childClaim);
        } else {
            // move child to parent folder
            migrateChildToNewParent(null, childClaim);
        }
    }

    resetPlayerClaimVisuals(claim);
    // transfer bank balance to owner
    final Account bankAccount = ((GDClaim) claim).getEconomyAccount();
    if (bankAccount != null) {
        try (final CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) {
            Sponge.getCauseStackManager().pushCause(GriefDefenderPlugin.getInstance());
            final EconomyService economyService = GriefDefenderPlugin.getInstance().economyService.get();
            final UniqueAccount ownerAccount = economyService.getOrCreateAccount(claim.getOwnerUniqueId()).orElse(null);
            if (ownerAccount != null) {
                ownerAccount.deposit(economyService.getDefaultCurrency(), bankAccount.getBalance(economyService.getDefaultCurrency()),
                    Sponge.getCauseStackManager().getCurrentCause());
            }
            bankAccount.resetBalance(economyService.getDefaultCurrency(), Sponge.getCauseStackManager().getCurrentCause());
        }
    }
    this.worldClaims.remove(claim);
    this.claimUniqueIdMap.remove(claim.getUniqueId());
    this.deleteChunkHashes((GDClaim) claim);
    if (gdClaim.parent != null) {
        gdClaim.parent.children.remove(claim);
    }
    for (UUID playerUniqueId : gdClaim.playersWatching) {
        final GDPermissionUser user = PermissionHolderCache.getInstance().getOrCreateUser(playerUniqueId);
        if (user != null && user.getOnlinePlayer() != null) {
            user.getInternalPlayerData().revertClaimVisual(gdClaim);
        }
    }

    return DATASTORE.deleteClaimFromStorage((GDClaim) claim);
}
 
Example #17
Source File: NationDepositExecutor.java    From Nations with MIT License 4 votes vote down vote up
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
{
	if (src instanceof Player)
	{
		if (!ctx.<Double>getOne("amount").isPresent())
		{
			src.sendMessage(Text.of(TextColors.YELLOW, "/n deposit <amount>\n/n withdraw <amount>"));
			return CommandResult.success();
		}
		
		Player player = (Player) src;
		Nation nation = DataHandler.getNationOfPlayer(player.getUniqueId());
		if (nation == null)
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NONATION));
			return CommandResult.success();
		}
		
		if (NationsPlugin.getEcoService() == null)
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NOECO));
			return CommandResult.success();
		}
		Optional<UniqueAccount> optAccount = NationsPlugin.getEcoService().getOrCreateAccount(player.getUniqueId());
		if (!optAccount.isPresent())
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_ECONOACCOUNT));
			return CommandResult.success();
		}
		Optional<Account> optNationAccount = NationsPlugin.getEcoService().getOrCreateAccount("nation-" + nation.getUUID().toString());
		if (!optNationAccount.isPresent())
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_ECONONATION));
			return CommandResult.success();
		}
		BigDecimal amount = BigDecimal.valueOf(ctx.<Double>getOne("amount").get());
		TransactionResult result = optAccount.get().transfer(optNationAccount.get(), NationsPlugin.getEcoService().getDefaultCurrency(), amount, NationsPlugin.getCause());
		if (result.getResult() == ResultType.ACCOUNT_NO_FUNDS)
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NOENOUGHMONEY));
			return CommandResult.success();
		}
		else if (result.getResult() != ResultType.SUCCESS)
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_ECOTRANSACTION));
			return CommandResult.success();
		}
		
		String[] s1 = LanguageHandler.SUCCESS_DEPOSIT.split("\\{AMOUNT\\}");
		Builder builder = Text.builder();
		if (s1[0].indexOf("{BALANCE}") >= 0)
		{
			String[] splited0 = s1[0].split("\\{BALANCE\\}");
			builder
			.append(Text.of(TextColors.GREEN, (splited0.length > 0) ? splited0[0] : ""))
			.append(Utils.formatPrice(TextColors.GREEN, optNationAccount.get().getBalance(NationsPlugin.getEcoService().getDefaultCurrency())))
			.append(Text.of(TextColors.GREEN, (splited0.length > 1) ? splited0[1] : ""));
		}
		else
		{
			builder.append(Text.of(TextColors.GREEN, s1[0]));
		}
		builder.append(Utils.formatPrice(TextColors.GREEN, amount));
		if (s1[1].indexOf("{BALANCE}") >= 0)
		{
			String[] splited1 = s1[1].split("\\{BALANCE\\}");
			builder
			.append(Text.of(TextColors.GREEN, (splited1.length > 0) ? splited1[0] : ""))
			.append(Utils.formatPrice(TextColors.GREEN, optNationAccount.get().getBalance(NationsPlugin.getEcoService().getDefaultCurrency())))
			.append(Text.of(TextColors.GREEN, (splited1.length > 1) ? splited1[1] : ""));
		}
		else
		{
			builder.append(Text.of(TextColors.GREEN, s1[1]));
		}
		src.sendMessage(builder.build());
	}
	else
	{
		src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NOPLAYER));
	}
	return CommandResult.success();
}
 
Example #18
Source File: BalTopCommand.java    From EconomyLite with MIT License 4 votes vote down vote up
@Override
public void run(CommandSource src, CommandContext args) {
    Currency current = EconomyLite.getCurrencyService().getCurrentCurrency();
    TreeMap<String, BigDecimal> bals = new TreeMap<>();
    Optional<Integer> pOpt = args.<Integer>getOne("page");
    int pageNumber = 1;
    if (pOpt.isPresent()) {
        pageNumber = pOpt.get();
    }
    if (pageNumber < 1) {
        src.sendMessage(messages.getMessage("command.baltop.invalidpage"));
        return;
    }
    int start, end;
    if (pageNumber == 1) {
        start = 1;
        end = 5;
    } else {
        start = ((pageNumber - 1) * 5) + 1;
        end = pageNumber * 10;
    }
    for (UniqueAccount account : EconomyLite.getPlayerService().getTopAccounts(start, end + 1, CauseFactory.create("Baltop command."))) {
        bals.put(account.getDisplayName().toPlain(), account.getBalance(current));
    }
    boolean nextPage = true;
    if (bals.size() < 1) {
        src.sendMessage(messages.getMessage("command.baltop.nodata"));
        return;
    }
    if (bals.size() < 6) {
        nextPage = false;
    }
    src.sendMessage(messages.getMessage("command.baltop.head", "page", String.valueOf(pageNumber)));
    count = start;
    bals.entrySet().stream().sorted(Map.Entry.<String, BigDecimal>comparingByValue().reversed()).limit(5).forEachOrdered(e -> {
        Text label = current.getPluralDisplayName();
        if (e.getValue().equals(BigDecimal.ONE)) {
            label = current.getDisplayName();
        }
        src.sendMessage(messages.getMessage(
                "command.baltop.data", "position", Integer.toString(count), "name", e.getKey(), "balance",
                String.format(Locale.ENGLISH, "%,.2f", e.getValue()), "label", label.toPlain()));
        count++;
    });
    Text toSend = Text.of();
    if (pageNumber > 1) {
        toSend = toSend.toBuilder().append(
                messages.getMessage("command.baltop.navigation", "button", "<-").toBuilder()
                        .onClick(TextActions.runCommand("/baltop " + (pageNumber - 1)))
                        .onHover(TextActions.showText(Text.of(TextColors.GREEN, "BACK"))).build()).build();
        toSend = toSend.toBuilder().append(Text.of(" ")).build();
    }
    toSend = toSend.toBuilder().append(messages.getMessage("command.baltop.navigation", "button", String.valueOf(pageNumber))).build();
    if (nextPage) {
        toSend = toSend.toBuilder().append(Text.of(" ")).build();
        toSend = toSend.toBuilder().append(
                messages.getMessage("command.baltop.navigation", "button", "->").toBuilder()
                        .onClick(TextActions.runCommand("/baltop " + (pageNumber + 1)))
                        .onHover(TextActions.showText(Text.of(TextColors.GREEN, "NEXT"))).build()).build();
    }
    if (!toSend.toPlain().isEmpty()) {
        src.sendMessage(toSend);
    }
    count = 0;
}
 
Example #19
Source File: VirtualChestEconomyManager.java    From VirtualChest with GNU Lesser General Public License v3.0 4 votes vote down vote up
private boolean depositBalance(Currency currency, UniqueAccount account, BigDecimal cost)
{
    BigDecimal balance = account.getBalance(currency);
    ResultType result = account.deposit(currency, cost, cause).getResult();
    return ResultType.SUCCESS.equals(result);
}
 
Example #20
Source File: VirtualChestEconomyManager.java    From VirtualChest with GNU Lesser General Public License v3.0 4 votes vote down vote up
private boolean withdrawBalance(Currency currency, UniqueAccount account, BigDecimal cost)
{
    BigDecimal balance = account.getBalance(currency);
    ResultType result = account.withdraw(currency, cost, cause).getResult();
    return ResultType.SUCCESS.equals(result);
}
 
Example #21
Source File: VirtualChestEconomyManager.java    From VirtualChest with GNU Lesser General Public License v3.0 4 votes vote down vote up
private UniqueAccount getAccountByPlayer(Player player)
{
    UUID uniqueId = player.getUniqueId();
    String message = "Unsupported account for uuid: " + uniqueId.toString();
    return economyService.getOrCreateAccount(uniqueId).orElseThrow(() -> new IllegalArgumentException(message));
}
 
Example #22
Source File: PlayerEconService.java    From EconomyLite with MIT License 2 votes vote down vote up
/**
 * Gets the top unique accounts registered in the EconomyLite system.
 *
 * @param start The starting account to get.
 * @param end The ending account to get.
 * @param cause What is getting the accounts.
 * @return The top unique accounts registered in the EconomyLite system.
 */
public List<UniqueAccount> getTopAccounts(int start, int end, Cause cause);