org.spongepowered.api.scheduler.Task Java Examples

The following examples show how to use org.spongepowered.api.scheduler.Task. 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: PlayerListener.java    From RedProtect with GNU General Public License v3.0 6 votes vote down vote up
public void SendNotifyMsg(Player p, String notify) {
    if (RedProtect.get().config.configRoot().notify.region_enter_mode.equalsIgnoreCase("OFF")) {
        return;
    }
    if (!notify.equals("")) {
        if (RedProtect.get().config.configRoot().notify.region_enter_mode.equalsIgnoreCase("BOSSBAR")) {
            ServerBossBar boss = ServerBossBar.builder()
                    .name(RedProtect.get().getUtil().toText(notify))
                    .overlay(BossBarOverlays.NOTCHED_12)
                    .color(BossBarColors.YELLOW)
                    .percent(1).build();
            boss.addPlayer(p);
            //start timer
            Task.builder()
                    .interval(1, TimeUnit.SECONDS)
                    .execute(new BossBarTimer(boss))
                    .submit(RedProtect.get().container);
        }
        if (RedProtect.get().config.configRoot().notify.region_enter_mode.equalsIgnoreCase("CHAT")) {
            p.sendMessage(RedProtect.get().getUtil().toText(notify));
        }
    }
}
 
Example #2
Source File: ForgotPasswordCommand.java    From FlexibleLogin with MIT License 6 votes vote down vote up
private void prepareSend(Player player, Account account, String email) {
    String newPassword = passwordSupplier.get();

    MailConfig emailConfig = settings.getGeneral().getMail();
    Session session = buildSession(emailConfig);

    try {
        Message message = buildMessage(player, email, newPassword, emailConfig, session);

        //send email
        Task.builder()
                .async()
                .execute(new SendMailTask(plugin, player, session, message))
                .submit(plugin);

        //set new password here if the email sending fails fails we have still the old password
        account.setPasswordHash(plugin.getHasher().hash(newPassword));
        Task.builder()
                .async()
                .execute(() -> plugin.getDatabase().save(account))
                .submit(plugin);
    } catch (Exception ex) {
        logger.error("Error executing command", ex);
        player.sendMessage(settings.getText().getErrorExecutingCommand());
    }
}
 
Example #3
Source File: HomeCommand.java    From EagleFactions with MIT License 6 votes vote down vote up
private void startHomeCooldown(UUID playerUUID)
{
    EagleFactionsPlugin.HOME_COOLDOWN_PLAYERS.put(playerUUID, this.factionsConfig.getHomeCooldown());

    final Task.Builder taskBuilder = Sponge.getScheduler().createTaskBuilder();

    taskBuilder.interval(1, TimeUnit.SECONDS).execute(task ->
    {
        if (EagleFactionsPlugin.HOME_COOLDOWN_PLAYERS.containsKey(playerUUID))
        {
            int seconds = EagleFactionsPlugin.HOME_COOLDOWN_PLAYERS.get(playerUUID);

            if (seconds < 1)
            {
                EagleFactionsPlugin.HOME_COOLDOWN_PLAYERS.remove(playerUUID);
                task.cancel();
            }
            EagleFactionsPlugin.HOME_COOLDOWN_PLAYERS.replace(playerUUID, seconds, seconds - 1);
        }
    }).submit(super.getPlugin());
}
 
Example #4
Source File: PowerIncrementTask.java    From EagleFactions with MIT License 6 votes vote down vote up
@Override
public void accept(final Task task)
{
    if (!this.playerManager.isPlayerOnline(playerUUID))
        task.cancel();

    final Optional<FactionPlayer> optionalFactionPlayer = this.playerManager.getFactionPlayer(playerUUID);
    if (!optionalFactionPlayer.isPresent())
        return;

    final FactionPlayer factionPlayer=  optionalFactionPlayer.get();

    if(factionPlayer.getPower() + this.powerConfig.getPowerIncrement() < factionPlayer.getMaxPower())
        this.powerManager.addPower(playerUUID, false);
    else
        this.powerManager.setPlayerPower(playerUUID, factionPlayer.getMaxPower());
}
 
Example #5
Source File: AllyCommand.java    From EagleFactions with MIT License 6 votes vote down vote up
private void sendInvite(final Player player, final Faction playerFaction, final Faction targetFaction) throws CommandException
{
	final AllyRequest invite = new AllyRequest(playerFaction.getName(), targetFaction.getName());
	if(EagleFactionsPlugin.ALLY_INVITE_LIST.contains(invite))
		throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, Messages.YOU_HAVE_ALREADY_INVITED_THIS_FACTION_TO_THE_ALLIANCE));

	EagleFactionsPlugin.ALLY_INVITE_LIST.add(invite);

	final Optional<Player> optionalInvitedFactionLeader = super.getPlugin().getPlayerManager().getPlayer(targetFaction.getLeader());

	optionalInvitedFactionLeader.ifPresent(x-> optionalInvitedFactionLeader.get().sendMessage(getInviteGetMessage(playerFaction)));
	targetFaction.getOfficers().forEach(x-> super.getPlugin().getPlayerManager().getPlayer(x).ifPresent(y-> getInviteGetMessage(playerFaction)));

	player.sendMessage(Text.of(PluginInfo.PLUGIN_PREFIX, MessageLoader.parseMessage(Messages.YOU_HAVE_INVITED_FACTION_TO_THE_ALLIANCE, TextColors.GREEN, ImmutableMap.of(Placeholders.FACTION_NAME, Text.of(TextColors.GOLD, targetFaction.getName())))));

	final Task.Builder taskBuilder = Sponge.getScheduler().createTaskBuilder();
	taskBuilder.execute(() -> EagleFactionsPlugin.ALLY_INVITE_LIST.remove(invite)).delay(2, TimeUnit.MINUTES).name("EagleFaction - Remove Invite").submit(super.getPlugin());
}
 
Example #6
Source File: TruceCommand.java    From EagleFactions with MIT License 6 votes vote down vote up
private void sendInvite(final Player player, final Faction playerFaction, final Faction targetFaction) throws CommandException
{
	final AllyRequest invite = new AllyRequest(playerFaction.getName(), targetFaction.getName());
	if(EagleFactionsPlugin.TRUCE_INVITE_LIST.contains(invite))
		throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, Messages.YOU_HAVE_ALREADY_INVITED_THIS_FACTION_TO_THE_TRUCE));

	EagleFactionsPlugin.TRUCE_INVITE_LIST.add(invite);

	final Optional<Player> optionalInvitedFactionLeader = super.getPlugin().getPlayerManager().getPlayer(targetFaction.getLeader());

	optionalInvitedFactionLeader.ifPresent(x-> optionalInvitedFactionLeader.get().sendMessage(getInviteGetMessage(playerFaction)));
	targetFaction.getOfficers().forEach(x-> super.getPlugin().getPlayerManager().getPlayer(x).ifPresent(y-> getInviteGetMessage(playerFaction)));

	player.sendMessage(Text.of(PluginInfo.PLUGIN_PREFIX, MessageLoader.parseMessage(Messages.YOU_HAVE_INVITED_FACTION_TO_THE_TRUCE, TextColors.GREEN, ImmutableMap.of(Placeholders.FACTION_NAME, Text.of(TextColors.GOLD, targetFaction.getName())))));

	final Task.Builder taskBuilder = Sponge.getScheduler().createTaskBuilder();
	taskBuilder.execute(() -> EagleFactionsPlugin.TRUCE_INVITE_LIST.remove(invite)).delay(2, TimeUnit.MINUTES).name("EagleFaction - Remove Invite").submit(super.getPlugin());
}
 
Example #7
Source File: Metrics.java    From EagleFactions with MIT License 6 votes vote down vote up
private void startSubmitting()
{
    // We use a timer cause want to be independent from the server tps
    final Timer timer = new Timer(true);
    timerTask = new TimerTask() {
        @Override
        public void run() {
            // The data collection (e.g. for custom graphs) is done sync
            // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
            Scheduler scheduler = Sponge.getScheduler();
            Task.Builder taskBuilder = scheduler.createTaskBuilder();
            taskBuilder.execute(() -> submitData()).submit(plugin);
        }
    };
    timer.scheduleAtFixedRate(timerTask, 1000 * 60 * 5, 1000 * 60 * 30);
    // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
    // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
    // WARNING: Just don't do it!
}
 
Example #8
Source File: AttackLogicImpl.java    From EagleFactions with MIT License 6 votes vote down vote up
@Override
public void runClaimingRestorer(String factionName)
{

    Task.Builder taskBuilder = Sponge.getScheduler().createTaskBuilder();

    taskBuilder.interval(1, TimeUnit.SECONDS).execute(task ->
    {
        if(EagleFactionsPlugin.ATTACKED_FACTIONS.containsKey(factionName))
        {
            int seconds = EagleFactionsPlugin.ATTACKED_FACTIONS.get(factionName);

            if (seconds <= 0)
            {
                EagleFactionsPlugin.ATTACKED_FACTIONS.remove(factionName);
                task.cancel();
            }
            else
            {
                EagleFactionsPlugin.ATTACKED_FACTIONS.replace(factionName, seconds, seconds - 1);
            }
        }
    }).submit(EagleFactionsPlugin.getPlugin());
}
 
Example #9
Source File: ParticlesUtil.java    From EagleFactions with MIT License 6 votes vote down vote up
@Override
		public void accept(Task task)
		{
//			double x = this.location.getX() + r * Math.cos(Math.toDegrees(angle));
//			double z = this.location.getZ() + r * Math.sin(Math.toDegrees(angle));

			double x = this.location.getX() + r * Math.cos(angle);
			double z = this.location.getZ() + r * Math.sin(angle);


			world.spawnParticles(ParticleEffect.builder().type(ParticleTypes.END_ROD).quantity(5).offset(Vector3d.from(0, 0.5, 0)).build(), Vector3d.from(x, location.getY() + 0.5, z));

			if (angle + angleIncrement > 360)
			{
				angle = (angle + angleIncrement) - 360;
			}
			else
			{
				angle += angleIncrement;
			}

			//TODO: This code runs forever until player changes location. We should count delay seconds here as well maybe?
			if (!this.lastBlockPosition.equals(this.player.getLocation().getBlockPosition()))
				task.cancel();
		}
 
Example #10
Source File: VirtualChestActions.java    From VirtualChest with GNU Lesser General Public License v3.0 6 votes vote down vote up
private CompletableFuture<CommandResult> processDelay(CommandResult parent, String command,
                                                      ClassToInstanceMap<Context> contextMap)
{
    CompletableFuture<CommandResult> future = new CompletableFuture<>();
    try
    {
        int delayTick = Integer.parseInt(command.replaceFirst("\\s++$", ""));
        if (delayTick <= 0)
        {
            throw new NumberFormatException();
        }
        Runnable taskExecutor = () -> future.complete(CommandResult.success());
        Task.builder().delayTicks(delayTick).execute(taskExecutor).submit(this.plugin);
    }
    catch (NumberFormatException e)
    {
        future.complete(CommandResult.empty());
    }
    return future;
}
 
Example #11
Source File: ForceLoginCommand.java    From FlexibleLogin with MIT License 6 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
    Player player = args.<Player>getOne("account").get();
    if (plugin.getDatabase().isLoggedIn(player)) {
        throw new CommandException(settings.getText().getForceLoginAlreadyLoggedIn());
    }

    Task.builder()
            //we are executing a SQL Query which is blocking
            .async()
            .execute(new ForceLoginTask(plugin, attemptManager, protectionManager, player, src))
            .name("Force Login Query")
            .submit(plugin);

    return CommandResult.success();
}
 
Example #12
Source File: ForceLoginTask.java    From FlexibleLogin with MIT License 6 votes vote down vote up
@Override
public void run() {
    Optional<Account> optAccount = plugin.getDatabase().loadAccount(player);
    if (!optAccount.isPresent()) {
        src.sendMessage(plugin.getConfigManager().getText().getAccountNotFound());
        return;
    }

    Account account = optAccount.get();

    attemptManager.clearAttempts(player.getUniqueId());

    account.setLoggedIn(true);
    //update the ip
    account.setIP(player.getConnection().getAddress().getAddress());

    player.sendMessage(plugin.getConfigManager().getText().getLoggedIn());
    src.sendMessage(plugin.getConfigManager().getText().getForceLoginSuccess());
    Task.builder().execute(() -> protectionManager.unprotect(player)).submit(plugin);

    //flushes the ip update
    plugin.getDatabase().save(account);
}
 
Example #13
Source File: UChat.java    From UltimateChat with GNU General Public License v3.0 6 votes vote down vote up
private void registerJDA(boolean start) {
    Task.builder().async().execute(() -> {
        if (checkJDA()) {
            this.logger.info("JDA LibLoader is present...");
            if (this.UCJDA != null) {
                this.UCJDA.shutdown();
                this.UCJDA = null;
            }
            if (config.root().discord.use) {
                this.UCJDA = new UCDiscord(this);
                if (!this.UCJDA.JDAAvailable()) {
                    this.UCJDA = null;
                    this.logger.info("JDA is not available due errors before.\n" +
                            "Hint: If you updated UChat, check if you need to update JDALibLoader too!");
                } else {
                    this.sync = new UCDiscordSync(this.factory);
                    this.logger.info("JDA connected and ready to use!");
                    if (start) this.UCJDA.sendRawToDiscord(lang.get("discord.start"));
                }
            }
        }
    }).submit(this);
}
 
Example #14
Source File: PasswordRegisterCommand.java    From FlexibleLogin with MIT License 6 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
    if (!(src instanceof Player)) {
        throw new CommandException(settings.getText().getPlayersOnly());
    }

    Collection<String> passwords = args.getAll("password");
    List<String> indexPasswords = Lists.newArrayList(passwords);
    String password = indexPasswords.get(0);
    if (!password.equals(indexPasswords.get(1))) {
        //Check if the first two passwords are equal to prevent typos
        throw new CommandException(settings.getText().getUnequalPasswords());
    }

    if (password.length() < settings.getGeneral().getMinPasswordLength()) {
        throw new CommandException(settings.getText().getTooShortPassword());
    }

    Task.builder()
            //we are executing a SQL Query which is blocking
            .async()
            .execute(new RegisterTask(plugin, protectionManager, (Player) src, password))
            .name("Register Query")
            .submit(plugin);
    return CommandResult.success();
}
 
Example #15
Source File: AccountsCommand.java    From FlexibleLogin with MIT License 6 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
    Optional<InetAddress> optIP = args.getOne("ip");
    optIP.ifPresent(inetAddress -> Task.builder()
            //we are executing a SQL Query which is blocking
            .async()
            .execute(() -> {
                Set<Account> accounts = plugin.getDatabase().getAccountsByIp(inetAddress);
                sendAccountNames(src, inetAddress.getHostAddress(), accounts);
            })
            .submit(plugin));

    Optional<User> optUser = args.getOne("user");
    optUser.ifPresent(user -> Task.builder()
            //we are executing a SQL Query which is blocking
            .async()
            .execute(() -> queryAccountsByName(src, user.getName()))
            .submit(plugin));

    return CommandResult.success();
}
 
Example #16
Source File: FlatFileDataStore.java    From GriefPrevention with MIT License 6 votes vote down vote up
public void unloadWorldData(WorldProperties worldProperties) {
    GPClaimManager claimWorldManager = this.getClaimWorldManager(worldProperties);
    for (Claim claim : claimWorldManager.getWorldClaims()) {
        ((GPClaim) claim).unload();
    }
    // Task must be cancelled before removing the claimWorldManager reference to avoid a memory leak
    Task cleanupTask = cleanupClaimTasks.get(worldProperties.getUniqueId());
    if (cleanupTask != null) {
       cleanupTask.cancel();
       cleanupClaimTasks.remove(worldProperties.getUniqueId());
    }

    claimWorldManager.unload();
    this.claimWorldManagers.remove(worldProperties.getUniqueId());
    DataStore.dimensionConfigMap.remove(worldProperties.getUniqueId());
    DataStore.worldConfigMap.remove(worldProperties.getUniqueId());
}
 
Example #17
Source File: PlayerListener.java    From RedProtect with GNU General Public License v3.0 6 votes vote down vote up
public void SendWelcomeMsg(Player p, String wel) {
    if (RedProtect.get().config.configRoot().notify.welcome_mode.equalsIgnoreCase("OFF")) {
        return;
    }
    if (RedProtect.get().config.configRoot().notify.welcome_mode.equalsIgnoreCase("BOSSBAR")) {
        ServerBossBar boss = ServerBossBar.builder()
                .name(RedProtect.get().getUtil().toText(wel))
                .overlay(BossBarOverlays.NOTCHED_12)
                .color(BossBarColors.GREEN)
                .percent(1).build();
        boss.addPlayer(p);
        //start timer
        Task.builder()
                .interval(1, TimeUnit.SECONDS)
                .execute(new BossBarTimer(boss))
                .submit(RedProtect.get().container);
    }
    if (RedProtect.get().config.configRoot().notify.welcome_mode.equalsIgnoreCase("CHAT")) {
        p.sendMessage(RedProtect.get().getUtil().toText(wel));
    }
}
 
Example #18
Source File: SetMailCommand.java    From FlexibleLogin with MIT License 6 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
    if (!(src instanceof Player)) {
        throw new CommandException(settings.getText().getPlayersOnly());
    }

    String email = args.<String>getOne("email").get();

    plugin.getDatabase().getAccount((Player) src).ifPresent(account -> {
        account.setMail(email);
        src.sendMessage(settings.getText().getMailSet());
        Task.builder()
                .async()
                .execute(() -> plugin.getDatabase().save(account))
                .submit(plugin);
    });

    return CommandResult.success();
}
 
Example #19
Source File: UploadCommand.java    From ChangeSkin with MIT License 6 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext args) {
    String url = args.<String>getOne("url").get();
    if (url.startsWith("http://") || url.startsWith("https://")) {
        List<Account> accounts = plugin.getCore().getUploadAccounts();
        if (accounts.isEmpty()) {
            plugin.sendMessage(src, "no-accounts");
        } else {
            Account uploadAccount = accounts.get(0);
            Runnable skinUploader = new SkinUploader(plugin, src, uploadAccount, url);
            Task.builder().async().execute(skinUploader).submit(plugin);
        }
    } else {
        plugin.sendMessage(src, "no-valid-url");
    }

    return CommandResult.success();
}
 
Example #20
Source File: RedProtect.java    From RedProtect with GNU General Public License v3.0 6 votes vote down vote up
private void shutDown() {
    // Unregister commands
    commandHandler.unregisterAll();

    // Save and unload all regions
    rm.saveAll(true);
    rm.unloadAll();

    // Cancel tasks from sponge scheduler and save logs
    for (Task task : Sponge.getScheduler().getScheduledTasks(this)) task.cancel();
    logger.SaveLogs();

    // Unregister listeners
    logger.info("Unregistering listeners...");
    Sponge.getEventManager().unregisterPluginListeners(this.container);
    Sponge.getEventManager().unregisterPluginListeners(this.container);

    logger.info(container.getName() + " turned off...");
}
 
Example #21
Source File: GDPlayerData.java    From GriefDefender with MIT License 6 votes vote down vote up
public void revertClaimVisual(GDClaim claim, UUID visualUniqueId) {
    final Player player = this.getSubject().getOnlinePlayer();
    if (player == null) {
        return;
    }

    for (Map.Entry<UUID, Task> mapEntry : this.claimVisualRevertTasks.entrySet()) {
        if (visualUniqueId.equals(mapEntry.getKey())) {
            mapEntry.getValue().cancel();
            break;
        }
    }
    if (GriefDefenderPlugin.getInstance().getWorldEditProvider() != null) {
        GriefDefenderPlugin.getInstance().getWorldEditProvider().revertClaimCUIVisual(visualUniqueId, this.playerID);
    }

    this.revertVisualBlocks(player, claim, visualUniqueId);
}
 
Example #22
Source File: LogoutCommand.java    From FlexibleLogin with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
    if (!(src instanceof Player)) {
        throw new CommandException(settings.getText().getPlayersOnly());
    }

    Player player = (Player) src;

    if (!plugin.getDatabase().isLoggedIn(player)) {
        throw new CommandException(settings.getText().getNotLoggedIn());
    }

    Account account = plugin.getDatabase().getAccount(player).get();

    src.sendMessage(settings.getText().getLoggedOut());
    account.setLoggedIn(false);
    Task.builder().execute(() -> protectionManager.protect(player)).submit(plugin);

    Task.builder()
            .async()
            .execute(() -> {
                //flushes the ip update
                plugin.getDatabase().save(account);
            })
            .submit(plugin);

    return CommandResult.success();
}
 
Example #23
Source File: ConnectionListener.java    From FlexibleLogin with MIT License 5 votes vote down vote up
@Listener
public void loadAccountOnJoin(Join playerJoinEvent, @First Player player) {
    Task.builder()
            .async()
            .execute(() -> onAccountLoaded(player))
            .submit(plugin);
}
 
Example #24
Source File: FlexibleLogin.java    From FlexibleLogin with MIT License 5 votes vote down vote up
private void init() {
    config.load();
    try {
        if (config.getGeneral().getSQL().getAuthMeTable().isEmpty()) {
            database = new FlexibleDatabase(logger, config);
            database.createTable(this, config);
        } else {
            database = new AuthMeDatabase(logger, config);
        }
    } catch (SQLException | UncheckedExecutionException | IOException ex) {
        logger.error("Cannot connect to auth storage", ex);
        Task.builder().execute(() -> Sponge.getServer().shutdown()).submit(this);
    }

    //delete existing mapping
    commandManager.getOwnedBy(this).stream()
            .filter(mapping -> "register".equalsIgnoreCase(mapping.getPrimaryAlias()))
            .forEach(commandManager::removeMapping);

    //use bcrypt as fallback for now
    hasher = config.getGeneral().getHashAlgo().createHasher();
    if (config.getGeneral().getHashAlgo() == HashingAlgorithm.TOTP) {
        commandManager.register(this, injector.getInstance(TwoFactorRegisterCommand.class).buildSpec(config),
                "register", "reg");
    } else if (config.getGeneral().getHashAlgo() == HashingAlgorithm.BCrypt) {
        commandManager.register(this, injector.getInstance(PasswordRegisterCommand.class).buildSpec(config),
                "register", "reg");
    }

    //schedule tasks
    Task.builder().execute(new MessageTask(this, config))
            .interval(config.getGeneral().getMessageInterval().getSeconds(), TimeUnit.SECONDS)
            .submit(this);
}
 
Example #25
Source File: SpongePlugin.java    From ViaVersion with MIT License 5 votes vote down vote up
@Override
public TaskId runRepeatingSync(Runnable runnable, Long ticks) {
    return new SpongeTaskId(
            Task.builder()
                    .execute(runnable)
                    .intervalTicks(ticks)
                    .submit(this)
    );
}
 
Example #26
Source File: UCListener.java    From UltimateChat with GNU General Public License v3.0 5 votes vote down vote up
@Listener
public void onDeath(DestructEntityEvent.Death e, @Getter("getTargetEntity") Player p) {
    if (UChat.get().getUCJDA() != null && !p.hasPermission(UChat.get().getConfig().root().discord.vanish_perm)) {
        Task.builder().async().execute(() ->
                UChat.get().getUCJDA().sendRawToDiscord(UChat.get().getLang().get("discord.death").replace("{player}", p.getName())));
    }
}
 
Example #27
Source File: SpongeSchedulerAdapter.java    From LuckPerms with MIT License 5 votes vote down vote up
@Override
public SchedulerTask asyncRepeating(Runnable task, long interval, TimeUnit unit) {
    Task t = this.scheduler.createTaskBuilder()
            .async()
            .interval(interval, unit)
            .delay(interval, unit)
            .execute(task)
            .submit(this.bootstrap);

    this.tasks.add(t);
    return t::cancel;
}
 
Example #28
Source File: TwoFactorRegisterCommand.java    From FlexibleLogin with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
    if (!(src instanceof Player)) {
        throw new CommandException(settings.getText().getPlayersOnly());
    }

    Task.builder()
            //we are executing a SQL Query which is blocking
            .async()
            .execute(new RegisterTask(plugin, protectionManager, (Player) src))
            .name("Register Query")
            .submit(plugin);

    return CommandResult.success();
}
 
Example #29
Source File: SpongeTaskMan.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@Override
public int repeatAsync(Runnable runnable, int interval) {
    int val = this.i.incrementAndGet();
    Task.Builder builder = Sponge.getGame().getScheduler().createTaskBuilder();
    Task.Builder built = builder.delayTicks(interval).async().intervalTicks(interval).execute(runnable);
    Task task = built.submit(plugin);
    this.tasks.put(val, task);
    return val;
}
 
Example #30
Source File: LoginTask.java    From FlexibleLogin with MIT License 5 votes vote down vote up
@Override
public void run() {
    Optional<Account> optAccount = plugin.getDatabase().loadAccount(player);
    if (!optAccount.isPresent()) {
        player.sendMessage(plugin.getConfigManager().getText().getAccountNotFound());
        return;
    }

    try {
        Account account = optAccount.get();
        if (account.checkPassword(plugin.getHasher(), userInput)) {
            attemptManager.clearAttempts(player.getUniqueId());

            //update the ip
            account.setIP(player.getConnection().getAddress().getAddress());
            account.setLoggedIn(true);

            player.sendMessage(plugin.getConfigManager().getText().getLoggedIn());
            Task.builder().execute(() -> protectionManager.unprotect(player)).submit(plugin);

            //flushes the ip update
            plugin.getDatabase().save(account);
        } else {
            player.sendMessage(plugin.getConfigManager().getText().getIncorrectPassword());
        }
    } catch (Exception ex) {
        plugin.getLogger().error("Unexpected error while password checking", ex);
        player.sendMessage(plugin.getConfigManager().getText().getErrorExecutingCommand());
    }
}