org.spongepowered.api.service.economy.EconomyService Java Examples

The following examples show how to use org.spongepowered.api.service.economy.EconomyService. 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: GDClaim.java    From GriefDefender with MIT License 6 votes vote down vote up
@Override
public Optional<UUID> getEconomyAccountId() {
    if (this.isAdminClaim() || this.isSubdivision() || !GriefDefenderPlugin.getGlobalConfig().getConfig().economy.bankSystem) {
        return Optional.empty();
    }

    if (this.economyAccount != null) {
        return Optional.of(this.id);
    }
    EconomyService economyService = GriefDefenderPlugin.getInstance().economyService.orElse(null);
    if (economyService != null) {
        this.economyAccount = economyService.getOrCreateAccount(this.id.toString()).orElse(null);
        return Optional.ofNullable(this.id);
    }
    return Optional.empty();
}
 
Example #2
Source File: MoneyVariable.java    From UltimateCore with MIT License 6 votes vote down vote up
@Override
public Optional<Text> getValue(@Nullable Object player) {
    if (player == null) return Optional.empty();
    if (player instanceof Player) {
        Player p = (Player) player;
        if (Sponge.getServiceManager().provide(EconomyService.class).isPresent()) {
            EconomyService es = Sponge.getServiceManager().provide(EconomyService.class).get();
            if (es.getOrCreateAccount(p.getUniqueId()).isPresent()) {
                BigDecimal balance = es.getOrCreateAccount(p.getUniqueId()).get().getBalance(es.getDefaultCurrency());
                return Optional.of(Text.of(balance.toString()));
            }
        }
        return Optional.empty();
    }
    return Optional.empty();
}
 
Example #3
Source File: VirtualServiceCommon.java    From EconomyLite with MIT License 6 votes vote down vote up
public List<VirtualAccount> getTopAccounts(int start, int end, Cause cause) {
    debug("virtcommon: Getting top accounts - " + cause.toString());
    String mid = start + "-" + end + ":" + EconomyLite.getEconomyService().getDefaultCurrency().getId();
    List<VirtualAccount> accounts = topCache.getIfPresent(mid);
    if (accounts != null) {
        return accounts;
    }
    int offset = start - 1;
    int limit = end - offset;
    accounts = new ArrayList<>();
    List<String> ids =
            manager.queryTypeList("id", String.class, "SELECT id FROM economylitevirts WHERE currency = ? ORDER BY balance DESC LIMIT ?, ?",
                    EconomyLite.getEconomyService().getDefaultCurrency().getId(), offset, limit);
    EconomyService ecoService = EconomyLite.getEconomyService();
    for (String id : ids) {
        Optional<Account> vOpt = ecoService.getOrCreateAccount(id);
        if (vOpt.isPresent() && (vOpt.get() instanceof VirtualAccount)) {
            accounts.add((VirtualAccount) vOpt.get());
        }
    }
    topCache.update(mid, accounts);
    return accounts;
}
 
Example #4
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 #5
Source File: GPClaim.java    From GriefPrevention with MIT License 6 votes vote down vote up
@Override
public Optional<Account> getEconomyAccount() {
    if (this.isAdminClaim() || this.isSubdivision() || !GriefPreventionPlugin.getGlobalConfig().getConfig().claim.bankTaxSystem) {
        return Optional.empty();
    }

    if (this.economyAccount != null) {
        return Optional.of(this.economyAccount);
    }
    EconomyService economyService = GriefPreventionPlugin.instance.economyService.orElse(null);
    if (economyService != null) {
        this.economyAccount = economyService.getOrCreateAccount(this.claimStorage.filePath.getFileName().toString()).orElse(null);
        return Optional.ofNullable(this.economyAccount);
    }
    return Optional.empty();
}
 
Example #6
Source File: EconomyServlet.java    From Web-API with MIT License 6 votes vote down vote up
@GET
@Path("/account/{id}")
@Permission({ "account", "one" })
@ApiOperation(
        value = "List currencies",
        notes = "Lists all the currencies that the current economy supports.")
public Account getAccount(@PathParam("id") String id) {
    EconomyService srv = getEconomyService();
    if (!srv.hasAccount(id))
        throw new NotFoundException("Could not find account with id " + id);

    Optional<Account> optAcc = srv.getOrCreateAccount(id);
    if (!optAcc.isPresent())
        throw new InternalServerErrorException("Could not get account " + id);

    return optAcc.get();
}
 
Example #7
Source File: GDClaim.java    From GriefDefender with MIT License 6 votes vote down vote up
public Account getEconomyAccount() {
    if (this.isAdminClaim() || this.isSubdivision() || !GriefDefenderPlugin.getGlobalConfig().getConfig().economy.bankSystem) {
        return null;
    }

    if (this.economyAccount != null) {
        return this.economyAccount;
    }
    EconomyService economyService = GriefDefenderPlugin.getInstance().economyService.orElse(null);
    if (economyService != null) {
        this.economyAccount = economyService.getOrCreateAccount(this.id.toString()).orElse(null);
        return this.economyAccount;
    }

    return null;
}
 
Example #8
Source File: VirtualChestEconomyManager.java    From VirtualChest with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void init()
{
    Optional<EconomyService> serviceOptional = Sponge.getServiceManager().provide(EconomyService.class);
    if (serviceOptional.isPresent())
    {
        economyService = serviceOptional.get();
        defaultCurrency = economyService.getDefaultCurrency();
        economyService.getCurrencies().forEach(this::addCurrency);
        Optional.ofNullable(defaultCurrency).ifPresent(this::addCurrency);
    }
    else
    {
        this.logger.warn("VirtualChest could not find the economy service. ");
        this.logger.warn("Features related to the economy may not work normally.");
    }
}
 
Example #9
Source File: NationsPlugin.java    From Nations with MIT License 5 votes vote down vote up
@Listener
public void onChangeServiceProvider(ChangeServiceProviderEvent event)
{
	if (event.getService().equals(EconomyService.class))
	{
		economyService = (EconomyService) event.getNewProviderRegistration().getProvider();
	}
}
 
Example #10
Source File: EconomyServlet.java    From Web-API with MIT License 5 votes vote down vote up
@GET
@Path("/currency")
@Permission({ "currency", "list" })
@ApiOperation(
        value = "List currencies",
        notes = "Lists all the currencies that the current economy supports.")
public Collection<Currency> getCurrencies() {
    EconomyService srv = getEconomyService();
    return srv.getCurrencies();
}
 
Example #11
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 #12
Source File: Stats.java    From UltimateCore with MIT License 4 votes vote down vote up
public static HashMap<String, Object> collect() {
    final HashMap<String, Object> data = new HashMap<>();
    data.put("serverid", ServerID.getUUID());
    data.put("statsversion", 1);
    data.put("apitype", Sponge.getPlatform().getContainer(Platform.Component.API).getName().toLowerCase());
    data.put("apiversion", Sponge.getPlatform().getContainer(Platform.Component.API).getVersion().orElse("Not Available"));
    data.put("implname", Sponge.getPlatform().getContainer(Platform.Component.IMPLEMENTATION).getName().toLowerCase());
    data.put("implversion", Sponge.getPlatform().getContainer(Platform.Component.IMPLEMENTATION).getVersion().orElse("Not Available"));
    data.put("servertype", Sponge.getPlatform().getType().isServer() ? "server" : "client");
    data.put("mcversion", Sponge.getPlatform().getMinecraftVersion().getName());
    data.put("ucversion", Sponge.getPluginManager().fromInstance(UltimateCore.get()).get().getVersion().orElse("Not Available"));
    data.put("playersonline", Sponge.getServer().getOnlinePlayers().size());
    data.put("worldsloaded", Sponge.getServer().getWorlds().size());
    data.put("osname", System.getProperty("os.name"));
    data.put("osarch", System.getProperty("os.arch").contains("64") ? 64 : 32);
    data.put("osversion", System.getProperty("os.version"));
    data.put("cores", Runtime.getRuntime().availableProcessors());
    data.put("maxram", Runtime.getRuntime().maxMemory());
    data.put("freeram", Runtime.getRuntime().freeMemory());
    data.put("onlinemode", Sponge.getServer().getOnlineMode());
    data.put("javaversion", System.getProperty("java.version"));
    data.put("modules", StringUtil.join(", ", UltimateCore.get().getModuleService().getModules().stream().map(Module::getIdentifier).collect(Collectors.toList())));
    data.put("language", UltimateCore.get().getGeneralConfig().get().getNode("language", "language").getString("EN_US"));
    //Plugins
    StringBuilder pluginbuilder = new StringBuilder();
    for (PluginContainer plugin : Sponge.getPluginManager().getPlugins()) {
        pluginbuilder.append("\n" + plugin.getId() + " / " + plugin.getName() + " / " + plugin.getVersion().orElse("Not Available"));
    }
    data.put("plugins", pluginbuilder.toString());
    //Permissions plugin
    Optional<ProviderRegistration<PermissionService>> permplugin = Sponge.getServiceManager().getRegistration(PermissionService.class);
    if (permplugin.isPresent()) {
        data.put("permissionsplugin", permplugin.get().getPlugin().getId() + " / " + permplugin.get().getPlugin().getName() + " / " + permplugin.get().getPlugin().getVersion().orElse("Not Available"));
    } else {
        data.put("permissionsplugin", "None");
    }
    //Economy plugin
    Optional<ProviderRegistration<EconomyService>> economyplugin = Sponge.getServiceManager().getRegistration(EconomyService.class);
    if (economyplugin.isPresent()) {
        data.put("economyplugin", economyplugin.get().getPlugin().getId() + " / " + economyplugin.get().getPlugin().getName() + " / " + economyplugin.get().getPlugin().getVersion().orElse("Not Available"));
    } else {
        data.put("economyplugin", "None");
    }
    //Return
    return data;
}
 
Example #13
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 #14
Source File: GriefDefenderPlugin.java    From GriefDefender with MIT License 4 votes vote down vote up
public EconomyService getEconomyService() {
    return this.economyService.orElse(null);
}
 
Example #15
Source File: EconomyLite.java    From EconomyLite with MIT License 4 votes vote down vote up
public static EconomyService getEconomyService() {
    return economyService;
}
 
Example #16
Source File: EconomyLite.java    From EconomyLite with MIT License 4 votes vote down vote up
@Listener
public void onServerInitialize(GamePreInitializationEvent event) {
    logger.info("EconomyLite " + PluginInfo.VERSION + " is initializing!");
    instance = this;
    // File setup
    configManager = ConfigManager.create(configDir, "config.conf", logger);
    currencyManager = ConfigManager.create(configDir, "currencies.conf", logger);
    initializeFiles();
    initializeCurrencies();
    // Load Message Storage
    messageStorage = MessageStorage.create(configDir, "messages", logger);
    // Load modules
    List<Module> postInitModules = new ArrayList<>();
    getModules().forEach(m -> {
        m.initializeConfig();
        if (m.isEnabled()) {
            if (m.initialize(logger, instance)) {
                logger.info("Loaded the " + m.getName() + " module!");
                postInitModules.add(m);
            } else {
                logger.error("Failed to load the " + m.getName() + " module!");
            }
        } else {
            logger.info("The " + m.getName() + " module is disabled!");
        }
    });
    // If the services have not been set, set them to default.
    if (playerEconService == null || virtualEconService == null) {
        playerEconService = new PlayerDataService();
        virtualEconService = new VirtualDataService();
    }
    // Load the economy service
    economyService = new LiteEconomyService();
    // Register the Economy Service
    game.getServiceManager().setProvider(this, EconomyService.class, economyService);
    // Post-initialize modules
    postInitModules.forEach(module -> {
        module.postInitialization(logger, instance);
    });
    // Register commands
    CommandLoader.registerCommands(this, TextSerializers.FORMATTING_CODE.serialize(messageStorage.getMessage("command.invalidsource")),
            new CurrencyCommand(),
            new CurrencySetCommand(),
            new CurrencyDeleteCommand(),
            new CurrencyCreateCommand(),
            new BalanceCommand(),
            new EconCommand(),
            new SetCommand(),
            new SetAllCommand(),
            new RemoveCommand(),
            new AddCommand(),
            new PayCommand(),
            new BalTopCommand(),
            new VirtualBalanceCommand(),
            new VirtualEconCommand(),
            new VirtualAddCommand(),
            new VirtualSetCommand(),
            new VirtualRemoveCommand(),
            new VirtualPayCommand(),
            new PayVirtualCommand(),
            new MigrateCommand(),
            new RefreshCommand()
    );
    // Register currency registry
    game.getRegistry().registerModule(Currency.class, new CurrencyRegistryModule());
}
 
Example #17
Source File: RedProtect.java    From RedProtect with GNU General Public License v3.0 4 votes vote down vote up
@Listener
public void onChangeServiceProvider(ChangeServiceProviderEvent event) {
    if (event.getService().equals(EconomyService.class)) {
        economy = (EconomyService) event.getNewProviderRegistration().getProvider();
    }
}
 
Example #18
Source File: CommandHelper.java    From GriefPrevention with MIT License 4 votes vote down vote up
public static void displayClaimBankInfo(CommandSource src, GPClaim claim, boolean checkTown, boolean returnToClaimInfo) {
    final EconomyService economyService = GriefPreventionPlugin.instance.economyService.orElse(null);
    if (economyService == null) {
        GriefPreventionPlugin.sendMessage(src, GriefPreventionPlugin.instance.messageData.economyNotInstalled.toText());
        return;
    }

    if (checkTown && !claim.isInTown()) {
        GriefPreventionPlugin.sendMessage(src, GriefPreventionPlugin.instance.messageData.townNotIn.toText());
        return;
    }

    if (!checkTown && (claim.isSubdivision() || claim.isAdminClaim())) {
        return;
    }

    final GPClaim town = claim.getTownClaim();
    Account bankAccount = checkTown ? town.getEconomyAccount().orElse(null) : claim.getEconomyAccount().orElse(null);
    if (bankAccount == null) {
        GriefPreventionPlugin.sendMessage(src, GriefPreventionPlugin.instance.messageData.economyVirtualNotSupported.toText());
        return;
    }

    final GPPlayerData playerData = GriefPreventionPlugin.instance.dataStore.getPlayerData(claim.getWorld(), claim.getOwnerUniqueId());
    final double claimBalance = bankAccount.getBalance(economyService.getDefaultCurrency()).doubleValue();
    double taxOwed = -1;
    final double playerTaxRate = GPOptionHandler.getClaimOptionDouble(playerData.getPlayerSubject(), claim, GPOptions.Type.TAX_RATE, playerData);
    if (checkTown) {
        if (!town.getOwnerUniqueId().equals(playerData.playerID)) {
            for (Claim playerClaim : playerData.getInternalClaims()) {
                GPClaim playerTown = (GPClaim) playerClaim.getTown().orElse(null);
                if (!playerClaim.isTown() && playerTown != null && playerTown.getUniqueId().equals(claim.getUniqueId())) {
                    taxOwed += playerTown.getClaimBlocks() * playerTaxRate;
                }
            }
        } else {
            taxOwed = town.getClaimBlocks() * playerTaxRate;
        }
    } else {
        taxOwed = claim.getClaimBlocks() * playerTaxRate;
    }

    final GriefPreventionConfig<?> activeConfig = GriefPreventionPlugin.getActiveConfig(claim.getWorld().getProperties());
    final ZonedDateTime withdrawDate = TaskUtils.getNextTargetZoneDate(activeConfig.getConfig().claim.taxApplyHour, 0, 0);
    Duration duration = Duration.between(Instant.now().truncatedTo(ChronoUnit.SECONDS), withdrawDate.toInstant()) ;
    final long s = duration.getSeconds();
    final String timeLeft = String.format("%d:%02d:%02d", s / 3600, (s % 3600) / 60, (s % 60));
    final Text message = GriefPreventionPlugin.instance.messageData.claimBankInfo
            .apply(ImmutableMap.of(
            "balance", claimBalance,
            "amount", taxOwed,
            "time_remaining", timeLeft,
            "tax_balance", claim.getData().getEconomyData().getTaxBalance())).build();
    Text transactions = Text.builder()
            .append(Text.of(TextStyles.ITALIC, TextColors.AQUA, "Bank Transactions"))
            .onClick(TextActions.executeCallback(createBankTransactionsConsumer(src, claim, checkTown, returnToClaimInfo)))
            .onHover(TextActions.showText(Text.of("Click here to view bank transactions")))
            .build();
    List<Text> textList = new ArrayList<>();
    if (returnToClaimInfo) {
        textList.add(Text.builder().append(Text.of(
                TextColors.WHITE, "\n[", TextColors.AQUA, "Return to claim info", TextColors.WHITE, "]\n"))
            .onClick(TextActions.executeCallback(CommandHelper.createCommandConsumer(src, "claiminfo", ""))).build());
    }
    textList.add(message);
    textList.add(transactions);
    PaginationService paginationService = Sponge.getServiceManager().provide(PaginationService.class).get();
    PaginationList.Builder paginationBuilder = paginationService.builder()
            .title(Text.of(TextColors.AQUA, "Bank Info")).padding(Text.of(TextStyles.STRIKETHROUGH, "-")).contents(textList);
    paginationBuilder.sendTo(src);
}
 
Example #19
Source File: UChat.java    From UltimateChat with GNU General Public License v3.0 4 votes vote down vote up
@Listener
public void onChangeServiceProvider(ChangeServiceProviderEvent event) {
    if (event.getService().equals(EconomyService.class)) {
        econ = (EconomyService) event.getNewProviderRegistration().getProvider();
    }
}
 
Example #20
Source File: GriefPreventionPlugin.java    From GriefPrevention with MIT License 4 votes vote down vote up
@Listener
public void onServerAboutToStart(GameAboutToStartServerEvent event) {
    if (!validateSpongeVersion()) {
        return;
    }

    if (this.permissionService == null) {
        this.logger.error("Unable to initialize plugin. GriefPrevention requires a permissions plugin such as LuckPerms.");
        return;
    }

    this.loadConfig();
    this.customLogger = new CustomLogger();
    this.executor = Executors.newFixedThreadPool(GriefPreventionPlugin.getGlobalConfig().getConfig().thread.numExecutorThreads);
    this.economyService = Sponge.getServiceManager().provide(EconomyService.class);
    if (Sponge.getPluginManager().getPlugin("mcclans").isPresent()) {
        this.clanApiProvider = new MCClansApiProvider();
    }
    if (Sponge.getPluginManager().getPlugin("nucleus").isPresent()) {
        this.nucleusApiProvider = new NucleusApiProvider();
    }
    if (Sponge.getPluginManager().getPlugin("worldedit").isPresent() || Sponge.getPluginManager().getPlugin("fastasyncworldedit").isPresent()) {
        this.worldEditProvider = new WorldEditApiProvider();
    }

    if (this.dataStore == null) {
        try {
            this.dataStore = new FlatFileDataStore();
            // Migrator currently only handles pixelmon
            // Remove pixelmon check after GP 5.0.0 update
            if (Sponge.getPluginManager().getPlugin("pixelmon").isPresent()) {
                if (this.dataStore.getMigrationVersion() < DataStore.latestMigrationVersion) {
                    GPPermissionMigrator.getInstance().migrateSubject(GLOBAL_SUBJECT);
                    permissionService.getUserSubjects().applyToAll(GPPermissionMigrator.getInstance().migrateSubjectPermissions());
                    permissionService.getGroupSubjects().applyToAll(GPPermissionMigrator.getInstance().migrateSubjectPermissions());
                    this.dataStore.setMigrationVersion(DataStore.latestMigrationVersion);
                }
            }
            this.dataStore.initialize();
        } catch (Exception e) {
            this.getLogger().info("Unable to initialize the file system data store.  Details:");
            this.getLogger().info(e.getMessage());
            e.printStackTrace();
            return;
        }
    }

    String dataMode = (this.dataStore instanceof FlatFileDataStore) ? "(File Mode)" : "(Database Mode)";
    Sponge.getEventManager().registerListeners(this, new BlockEventHandler(dataStore));
    Sponge.getEventManager().registerListeners(this, new PlayerEventHandler(dataStore, this));
    Sponge.getEventManager().registerListeners(this, new EntityEventHandler(dataStore));
    Sponge.getEventManager().registerListeners(this, new WorldEventHandler());
    if (this.nucleusApiProvider != null) {
        Sponge.getEventManager().registerListeners(this, new NucleusEventHandler());
        this.nucleusApiProvider.registerTokens();
    }
    if (this.clanApiProvider != null) {
        Sponge.getEventManager().registerListeners(this, new MCClansEventHandler());
    }
    addLogEntry("Finished loading data " + dataMode + ".");

    PUBLIC_USER = Sponge.getServiceManager().provide(UserStorageService.class).get()
            .getOrCreate(GameProfile.of(GriefPreventionPlugin.PUBLIC_UUID, GriefPreventionPlugin.PUBLIC_NAME));
    WORLD_USER = Sponge.getServiceManager().provide(UserStorageService.class).get()
            .getOrCreate(GameProfile.of(GriefPreventionPlugin.WORLD_USER_UUID, GriefPreventionPlugin.WORLD_USER_NAME));

    // run cleanup task
    int cleanupTaskInterval = GriefPreventionPlugin.getGlobalConfig().getConfig().claim.expirationCleanupInterval;
    if (cleanupTaskInterval > 0) {
        CleanupUnusedClaimsTask cleanupTask = new CleanupUnusedClaimsTask();
        Sponge.getScheduler().createTaskBuilder().delay(cleanupTaskInterval, TimeUnit.MINUTES).execute(cleanupTask)
                .submit(GriefPreventionPlugin.instance);
    }

    // if economy is enabled
    if (this.economyService.isPresent()) {
        GriefPreventionPlugin.addLogEntry("GriefPrevention economy integration enabled.");
        GriefPreventionPlugin.addLogEntry(
                "Hooked into economy: " + Sponge.getServiceManager().getRegistration(EconomyService.class).get().getPlugin().getId() + ".");
        GriefPreventionPlugin.addLogEntry("Ready to buy/sell claim blocks!");
    }

    // load ignore lists for any already-online players
    Collection<Player> players = Sponge.getGame().getServer().getOnlinePlayers();
    for (Player player : players) {
        new IgnoreLoaderThread(player.getUniqueId(), this.dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId()).ignoredPlayers)
                .start();
    }

    // TODO - rewrite /gp command
    //Sponge.getGame().getCommandManager().register(this, CommandGriefPrevention.getCommand().getCommandSpec(),
    //CommandGriefPrevention.getCommand().getAliases());
    registerBaseCommands();
    this.dataStore.loadClaimTemplates();
}
 
Example #21
Source File: EconomyServlet.java    From Web-API with MIT License 4 votes vote down vote up
private EconomyService getEconomyService() {
    Optional<EconomyService> optSrv = Sponge.getServiceManager().provide(EconomyService.class);
    if (!optSrv.isPresent())
        throw new NotFoundException("Economy service was not found");
    return optSrv.get();
}
 
Example #22
Source File: UChat.java    From UltimateChat with GNU General Public License v3.0 4 votes vote down vote up
EconomyService getEco() {
    return this.econ;
}
 
Example #23
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 #24
Source File: NationsPlugin.java    From Nations with MIT License 4 votes vote down vote up
public static EconomyService getEcoService()
{
	return getInstance().economyService;
}
 
Example #25
Source File: NationsPlugin.java    From Nations with MIT License 4 votes vote down vote up
@Listener
public void onStart(GameStartedServerEvent event)
{
	LanguageHandler.load();
	ConfigHandler.load();
	DataHandler.load();
	
	Sponge.getServiceManager()
			.getRegistration(EconomyService.class)
			.ifPresent(prov -> economyService = prov.getProvider());


	NationCmds.create(this);

	Sponge.getEventManager().registerListeners(this, new PlayerConnectionListener());
	Sponge.getEventManager().registerListeners(this, new PlayerMoveListener());
	Sponge.getEventManager().registerListeners(this, new GoldenAxeListener());
	Sponge.getEventManager().registerListeners(this, new PvpListener());
	Sponge.getEventManager().registerListeners(this, new FireListener());
	Sponge.getEventManager().registerListeners(this, new ExplosionListener());
	Sponge.getEventManager().registerListeners(this, new MobSpawningListener());
	Sponge.getEventManager().registerListeners(this, new BuildPermListener());
	Sponge.getEventManager().registerListeners(this, new InteractPermListener());
	Sponge.getEventManager().registerListeners(this, new ChatListener());

	LocalDateTime localNow = LocalDateTime.now();
	ZonedDateTime zonedNow = ZonedDateTime.of(localNow, ZoneId.systemDefault());
	ZonedDateTime zonedNext = zonedNow.withHour(12).withMinute(0).withSecond(0);
	if (zonedNow.compareTo(zonedNext) > 0)
		zonedNext = zonedNext.plusDays(1);
	long initalDelay = Duration.between(zonedNow, zonedNext).getSeconds();

	Sponge.getScheduler()
			.createTaskBuilder()
			.execute(new TaxesCollectRunnable())
			.delay(initalDelay, TimeUnit.SECONDS)
			.interval(1, TimeUnit.DAYS)
			.async()
			.submit(this);

	logger.info("Plugin ready");
}