Reduce future join call usage

This commit is contained in:
William committed 2022-09-24 22:00:48 +01:00
1 parent 8a4ed7c565
commit 649d4c0600
18 files changed
+316 -291

No files matched your search

@@ -121,9 +121,9 @@ public class DelHomeCommand extends CommandBase implements TabCompletable {
for (final Home toDelete : homes) {
homeDeletionFuture.add(plugin.getSavedPositionManager().deleteHome(homeOwner, toDelete.meta.name));
}
CompletableFuture.allOf(homeDeletionFuture.toArray(new CompletableFuture[0])).thenRunAsync(() ->
plugin.getLocales().getLocale("delete_all_homes_success", Integer.toString(homeDeletionFuture.size()))
.ifPresent(deleter::sendMessage)).join();
CompletableFuture.allOf(homeDeletionFuture.toArray(new CompletableFuture[0]))
.thenRun(() -> plugin.getLocales().getLocale("delete_all_homes_success",
Integer.toString(homeDeletionFuture.size())).ifPresent(deleter::sendMessage));
});
}
@@ -68,9 +68,9 @@ public class DelWarpCommand extends CommandBase implements TabCompletable {
for (final Warp toDelete : warps) {
homeDeletionFuture.add(plugin.getSavedPositionManager().deleteWarp(toDelete.meta.name));
}
CompletableFuture.allOf(homeDeletionFuture.toArray(new CompletableFuture[0])).thenRunAsync(() ->
plugin.getLocales().getLocale("delete_all_warps_success", Integer.toString(homeDeletionFuture.size()))
.ifPresent(deleter::sendMessage)).join();
CompletableFuture.allOf(homeDeletionFuture.toArray(new CompletableFuture[0]))
.thenRun(() -> plugin.getLocales().getLocale("delete_all_warps_success",
Integer.toString(homeDeletionFuture.size())).ifPresent(deleter::sendMessage));
});
}
@@ -188,12 +188,12 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
.ifPresent(editor::sendMessage);
return;
}
boolean newIsPublic = !home.isPublic;
final AtomicBoolean newIsPublic = new AtomicBoolean(!home.isPublic);
if (editArgs != null && !editArgs.isBlank()) {
if (editArgs.equalsIgnoreCase("private")) {
newIsPublic = false;
newIsPublic.set(false);
} else if (editArgs.equalsIgnoreCase("public")) {
newIsPublic = true;
newIsPublic.set(true);
} else {
plugin.getLocales().getLocale("error_invalid_syntax",
"/edithome <name> privacy [private|public]")
@@ -201,57 +201,60 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
return;
}
}
final String privacyKeyedString = newIsPublic ? "public" : "private";
if (newIsPublic == home.isPublic) {
final String privacyKeyedString = newIsPublic.get() ? "public" : "private";
if (newIsPublic.get() == home.isPublic) {
plugin.getLocales().getLocale(
"error_edit_home_privacy_already_" + privacyKeyedString)
.ifPresent(editor::sendMessage);
return;
}
// Perform checks if making the home public
if (newIsPublic && !otherOwner) {
// Check against maximum public homes
final List<Home> existingPublicHomes = plugin.getDatabase().getHomes(editor).join().stream()
.filter(existingHome -> existingHome.isPublic).toList();
final int maxPublicHomes = editor.getMaxPublicHomes(plugin.getSettings().maxPublicHomes,
plugin.getSettings().stackPermissionLimits);
if (existingPublicHomes.size() >= maxPublicHomes) {
plugin.getLocales().getLocale("error_edit_home_maximum_public_homes",
Integer.toString(maxPublicHomes))
.ifPresent(editor::sendMessage);
return;
// Get the homes of the editor
plugin.getDatabase().getHomes(editor).thenAccept(editorHomes -> {
// Perform checks if making the home public
if (newIsPublic.get() && !otherOwner) {
// Check against maximum public homes
final List<Home> existingPublicHomes = editorHomes.stream()
.filter(existingHome -> existingHome.isPublic).toList();
final int maxPublicHomes = editor.getMaxPublicHomes(plugin.getSettings().maxPublicHomes,
plugin.getSettings().stackPermissionLimits);
if (existingPublicHomes.size() >= maxPublicHomes) {
plugin.getLocales().getLocale("error_edit_home_maximum_public_homes",
Integer.toString(maxPublicHomes))
.ifPresent(editor::sendMessage);
return;
}
// Check against economy
if (!plugin.validateEconomyCheck(editor, Settings.EconomyAction.MAKE_HOME_PUBLIC)) {
return;
}
}
// Check against economy
if (!plugin.validateEconomyCheck(editor, Settings.EconomyAction.MAKE_HOME_PUBLIC)) {
return;
}
}
// Execute the update
plugin.getSavedPositionManager().updateHomePrivacy(home, newIsPublic.get()).thenRun(() -> {
if (home.owner.uuid.equals(editor.uuid)) {
editor.sendMessage(plugin.getLocales().getLocale(
"edit_home_privacy_" + privacyKeyedString + "_success",
home.meta.name).orElse(new MineDown("")));
} else {
editor.sendMessage(plugin.getLocales().getLocale(
"edit_home_privacy_" + privacyKeyedString + "_success_other",
home.owner.username, home.meta.name).orElse(new MineDown("")));
}
// Execute the update
plugin.getSavedPositionManager().updateHomePrivacy(home, newIsPublic).join();
if (home.owner.uuid.equals(editor.uuid)) {
editor.sendMessage(plugin.getLocales().getLocale(
"edit_home_privacy_" + privacyKeyedString + "_success",
home.meta.name).orElse(new MineDown("")));
} else {
editor.sendMessage(plugin.getLocales().getLocale(
"edit_home_privacy_" + privacyKeyedString + "_success_other",
home.owner.username, home.meta.name).orElse(new MineDown("")));
}
// Perform necessary economy transaction
plugin.performEconomyTransaction(editor, Settings.EconomyAction.MAKE_HOME_PUBLIC);
// Perform necessary economy transaction
plugin.performEconomyTransaction(editor, Settings.EconomyAction.MAKE_HOME_PUBLIC);
// Show the menu if the menu flag is set
if (showMenuFlag.get()) {
getHomeEditorWindow(home, false, otherOwner,
!otherOwner || editor.hasPermission(Permission.COMMAND_HOME_OTHER.node),
editor.hasPermission(Permission.COMMAND_EDIT_HOME_PRIVACY.node))
.forEach(editor::sendMessage);
}
// Show the menu if the menu flag is set
if (showMenuFlag.get()) {
getHomeEditorWindow(home, false, otherOwner,
!otherOwner || editor.hasPermission(Permission.COMMAND_HOME_OTHER.node),
editor.hasPermission(Permission.COMMAND_EDIT_HOME_PRIVACY.node))
.forEach(editor::sendMessage);
}
});
});
}
default -> plugin.getLocales().getLocale("error_invalid_syntax",
"/edithome <name> [" + String.join("|", EDIT_HOME_COMPLETIONS) + "] [args]")
@@ -30,7 +30,7 @@ public class HomeCommand extends CommandBase implements TabCompletable, ConsoleE
switch (homes.size()) {
case 0 -> plugin.getLocales().getLocale("error_no_homes_set").ifPresent(onlineUser::sendMessage);
case 1 -> plugin.getTeleportManager().timedTeleport(onlineUser, homes.get(0)).thenAccept(result ->
plugin.getTeleportManager().finishTeleport(onlineUser, result)).join();
plugin.getTeleportManager().finishTeleport(onlineUser, result));
default -> plugin.getCache().getHomeList(onlineUser, onlineUser,
plugin.getLocales(), homes, plugin.getSettings().listItemsPerPage, 1)
.ifPresent(onlineUser::sendMessage);
@@ -54,9 +54,8 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable {
final OnlineUser userToTeleport = target;
final boolean isExecutorTeleporting = userToTeleport.uuid.equals(onlineUser.uuid);
CompletableFuture.runAsync(() -> {
plugin.getDatabase().getUserData(onlineUser.uuid).thenAccept(userData -> {
// Check the user is not still on /rtp cooldown
final Optional<UserData> userData = plugin.getDatabase().getUserData(onlineUser.uuid).join();
if (userData.isEmpty()) {
return;
}
@@ -6,12 +6,12 @@ import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.UserData;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.position.SavedPositionManager;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
public class SetHomeCommand extends CommandBase {
@@ -62,52 +62,58 @@ public class SetHomeCommand extends CommandBase {
return;
}
// Check against economy if needed
boolean newSlotNeeded = false;
UserData userDataToUpdate = null;
if (plugin.getSettings().economy) {
final int freeHomes = onlineUser.getFreeHomes(plugin.getSettings().freeHomeSlots, plugin.getSettings().stackPermissionLimits);
final Optional<UserData> fetchedData = plugin.getDatabase().getUserData(onlineUser.uuid).join();
if (fetchedData.isPresent()) {
newSlotNeeded = (currentHomes.size() + 1) > (freeHomes + fetchedData.get().homeSlots());
}
// Get their user data
plugin.getDatabase().getUserData(onlineUser.uuid).thenAccept(fetchedData -> {
// Check against economy if needed
final AtomicBoolean newSlotNeeded = new AtomicBoolean(false);
final AtomicReference<UserData> userDataToUpdate = new AtomicReference<>(null);
if (plugin.getSettings().economy) {
final int freeHomes = onlineUser.getFreeHomes(plugin.getSettings().freeHomeSlots,
plugin.getSettings().stackPermissionLimits);
if (fetchedData.isPresent()) {
newSlotNeeded.set((currentHomes.size() + 1) > (freeHomes + fetchedData.get().homeSlots()));
// If a new slot is needed, validate the user has enough funds to purchase one
if (newSlotNeeded) {
if (!plugin.validateEconomyCheck(onlineUser, Settings.EconomyAction.ADDITIONAL_HOME_SLOT)) {
return;
}
userDataToUpdate = new UserData(onlineUser, (currentHomes.size() + 1) - freeHomes,
fetchedData.get().ignoringTeleports(), fetchedData.get().rtpCooldown());
} else {
if (currentHomes.size() == freeHomes) {
plugin.getLocales().getLocale("set_home_used_free_slots", Integer.toString(freeHomes))
.ifPresent(onlineUser::sendMessage);
// If a new slot is needed, validate the user has enough funds to purchase one
if (newSlotNeeded.get()) {
if (!plugin.validateEconomyCheck(onlineUser, Settings.EconomyAction.ADDITIONAL_HOME_SLOT)) {
return;
}
userDataToUpdate.set(new UserData(onlineUser, (currentHomes.size() + 1) - freeHomes,
fetchedData.get().ignoringTeleports(), fetchedData.get().rtpCooldown()));
} else {
if (currentHomes.size() == freeHomes) {
plugin.getLocales().getLocale("set_home_used_free_slots", Integer.toString(freeHomes))
.ifPresent(onlineUser::sendMessage);
}
}
}
}
}
// Set the home in the saved position manager
final SavedPositionManager.SaveResult setResult = plugin.getSavedPositionManager()
.setHome(new PositionMeta(homeName, ""), onlineUser, onlineUser.getPosition()).join();
// Set the home in the saved position manager
plugin.getSavedPositionManager()
.setHome(new PositionMeta(homeName, ""), onlineUser, onlineUser.getPosition())
.thenAccept(setResult -> {
// Display feedback of the result of the set operation
(switch (setResult.resultType()) {
case SUCCESS -> {
assert setResult.savedPosition().isPresent();
// Display feedback of the result of the set operation
(switch (setResult.resultType()) {
case SUCCESS -> {
assert setResult.savedPosition().isPresent();
// If the user needed to buy a new slot, perform the transaction and update their data
if (newSlotNeeded.get()) {
plugin.performEconomyTransaction(onlineUser, Settings.EconomyAction.ADDITIONAL_HOME_SLOT);
plugin.getDatabase().updateUserData(userDataToUpdate.get());
}
yield plugin.getLocales().getLocale("set_home_success", setResult.savedPosition().get().meta.name);
}
case FAILED_DUPLICATE -> plugin.getLocales().getLocale("error_home_name_taken");
case FAILED_NAME_LENGTH -> plugin.getLocales().getLocale("error_home_name_length");
case FAILED_NAME_CHARACTERS -> plugin.getLocales().getLocale("error_home_name_characters");
default -> plugin.getLocales().getLocale("error_home_description_characters");
}).ifPresent(onlineUser::sendMessage);
});
// If the user needed to buy a new slot, perform the transaction and update their data
if (newSlotNeeded) {
plugin.performEconomyTransaction(onlineUser, Settings.EconomyAction.ADDITIONAL_HOME_SLOT);
plugin.getDatabase().updateUserData(userDataToUpdate).join();
}
yield plugin.getLocales().getLocale("set_home_success", setResult.savedPosition().get().meta.name);
}
case FAILED_DUPLICATE -> plugin.getLocales().getLocale("error_home_name_taken");
case FAILED_NAME_LENGTH -> plugin.getLocales().getLocale("error_home_name_length");
case FAILED_NAME_CHARACTERS -> plugin.getLocales().getLocale("error_home_name_characters");
default -> plugin.getLocales().getLocale("error_home_description_characters");
}).ifPresent(onlineUser::sendMessage);
});
}
}
@@ -19,31 +19,32 @@ public class SetSpawnCommand extends CommandBase {
@Override
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
CompletableFuture.supplyAsync(() -> {
if (args.length > 0) {
plugin.getLocales().getLocale("error_invalid_syntax", "/setspawn")
.ifPresent(onlineUser::sendMessage);
return false;
}
final Position position = onlineUser.getPosition();
if (plugin.getSettings().crossServer && plugin.getSettings().globalSpawn) {
final Optional<Warp> warp = plugin.getDatabase().getWarp(plugin.getSettings().globalSpawnName).join();
if (args.length > 0) {
plugin.getLocales().getLocale("error_invalid_syntax", "/setspawn")
.ifPresent(onlineUser::sendMessage);
return;
}
final Position position = onlineUser.getPosition();
if (plugin.getSettings().crossServer && plugin.getSettings().globalSpawn) {
plugin.getDatabase().getWarp(plugin.getSettings().globalSpawnName).thenApply(warp -> {
if (warp.isPresent()) {
return plugin.getSavedPositionManager().updateWarpPosition(warp.get(), position).join();
return plugin.getSavedPositionManager().updateWarpPosition(warp.get(), position);
} else {
return plugin.getSavedPositionManager().setWarp(new PositionMeta(plugin.getSettings().globalSpawnName,
plugin.getLocales().getRawLocale("spawn_warp_default_description")
.orElse("")), position).join().resultType().successful;
plugin.getLocales().getRawLocale("spawn_warp_default_description").orElse("")), position)
.thenApply(result -> result.resultType().successful);
}
} else {
plugin.setServerSpawn(position);
return true;
}
}).thenAccept(succeeded -> {
if (succeeded) {
plugin.getLocales().getLocale("set_spawn_success")
.ifPresent(onlineUser::sendMessage);
}
});
}).thenAccept(result -> result.thenAccept(successful -> {
if (successful) {
plugin.getLocales().getLocale("set_spawn_success")
.ifPresent(onlineUser::sendMessage);
}
}));
} else {
plugin.setServerSpawn(position);
plugin.getLocales().getLocale("set_spawn_success")
.ifPresent(onlineUser::sendMessage);
}
}
}
@@ -6,8 +6,6 @@ import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.CompletableFuture;
public class SetWarpCommand extends CommandBase {
protected SetWarpCommand(@NotNull HuskHomes implementor) {
@@ -17,7 +15,7 @@ public class SetWarpCommand extends CommandBase {
@Override
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
if (args.length == 1) {
CompletableFuture.runAsync(() -> setWarp(onlineUser, args[0]));
setWarp(onlineUser, args[0]);
} else {
plugin.getLocales().getLocale("error_invalid_syntax", "/setwarp <name>")
.ifPresent(onlineUser::sendMessage);
@@ -10,7 +10,6 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
import java.util.stream.Collectors;
@@ -22,23 +21,22 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
@Override
public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) {
CompletableFuture.runAsync(() -> {
// Ensure a valid target was found
final Optional<TeleportTarget> teleportTarget = getTeleportTarget(args, onlineUser);
if (teleportTarget.isEmpty()) {
plugin.getLocales().getLocale("error_invalid_syntax", "/tp <target> [destination]")
.ifPresent(onlineUser::sendMessage);
return;
}
// Ensure a valid target was found
final Optional<TeleportTarget> teleportTarget = getTeleportTarget(args, onlineUser);
if (teleportTarget.isEmpty()) {
plugin.getLocales().getLocale("error_invalid_syntax", "/tp <target> [destination]")
.ifPresent(onlineUser::sendMessage);
return;
}
// Determine the player to teleport
final String targetPlayerToTeleport = ((teleportTarget.get() instanceof TargetPlayer) && args.length == 2)
? args[0] : ((teleportTarget.get() instanceof TargetPosition)
? args.length > 3 ? (isCoordinate(args[1]) && isCoordinate(args[2]) && isCoordinate(args[3]) ? args[0] : onlineUser.username)
: onlineUser.username : onlineUser.username);
// Determine the player to teleport
final String targetPlayerToTeleport = ((teleportTarget.get() instanceof TargetPlayer) && args.length == 2)
? args[0] : ((teleportTarget.get() instanceof TargetPosition)
? args.length > 3 ? (isCoordinate(args[1]) && isCoordinate(args[2]) && isCoordinate(args[3]) ? args[0] : onlineUser.username)
: onlineUser.username : onlineUser.username);
// Find the online user to teleport
plugin.getCache().updatePlayerListCache(plugin, onlineUser).join();
// Find the online user to teleport
plugin.getCache().updatePlayerListCache(plugin, onlineUser).thenRun(() -> {
final String playerToTeleport = plugin.getCache().players.stream()
.filter(user -> user.equalsIgnoreCase(targetPlayerToTeleport)).findFirst()
.or(() -> Optional.ofNullable(targetPlayerToTeleport.equals("@s") ? onlineUser.username : null))
@@ -101,9 +99,6 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
.ifPresent(onlineUser::sendMessage);
}));
}
}).exceptionally(throwable -> {
plugin.getLoggingAdapter().log(Level.SEVERE, "An error occurred whilst executing a teleport command", throwable);
return null;
});
}
@@ -183,7 +178,7 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
// Execute the console teleport
if (teleportTarget instanceof TargetPlayer targetPlayer) {
plugin.getLoggingAdapter().log(Level.INFO, "Teleporting " + playerToTeleport.username
+ " to " + targetPlayer.playerName);
+ " to " + targetPlayer.playerName);
plugin.getTeleportManager().teleportToPlayerByName(playerToTeleport, targetPlayer.playerName, false);
} else {
final TargetPosition targetPosition = (TargetPosition) teleportTarget;
@@ -193,7 +188,7 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
plugin.getLoggingAdapter().log(Level.INFO, "Successfully teleported " + playerToTeleport.username);
} else {
plugin.getLoggingAdapter().log(Level.WARNING, "Failed to teleport " + playerToTeleport.username
+ " (" + teleportResult.name() + ")");
+ " (" + teleportResult.name() + ")");
}
plugin.getTeleportManager().finishTeleport(playerToTeleport, teleportResult);
});
@@ -25,12 +25,12 @@ public class TpIgnoreCommand extends CommandBase {
final boolean isIgnoringRequests = !plugin.getRequestManager().isIgnoringRequests(onlineUser);
plugin.getRequestManager().setIgnoringRequests(onlineUser, isIgnoringRequests);
// Update value on the database and send a message
plugin.getDatabase().getUserData(onlineUser.uuid).thenAcceptAsync(
userData -> userData.ifPresent(data -> plugin.getDatabase().updateUserData(new UserData(onlineUser,
data.homeSlots(), isIgnoringRequests, data.rtpCooldown())).join())).thenRun(
() -> plugin.getLocales().getRawLocale("tpignore_toggle_" + (isIgnoringRequests ? "on" : "off"),
plugin.getLocales().getRawLocale("tpignore_toggle_button").orElse(""))
.ifPresent(locale -> onlineUser.sendMessage(new MineDown(locale))));
// Update value on the database and send a message | todo: Clean this up
plugin.getDatabase().getUserData(onlineUser.uuid)
.thenAcceptAsync(userData -> userData.ifPresent(data -> plugin.getDatabase()
.updateUserData(new UserData(onlineUser, data.homeSlots(), isIgnoringRequests, data.rtpCooldown()))
.thenRun(() -> plugin.getLocales().getRawLocale("tpignore_toggle_" + (isIgnoringRequests ? "on" : "off"),
plugin.getLocales().getRawLocale("tpignore_toggle_button").orElse(""))
.ifPresent(locale -> onlineUser.sendMessage(new MineDown(locale))))));
}
}
@@ -54,21 +54,22 @@ public class WarpCommand extends CommandBase implements TabCompletable, ConsoleE
plugin.getLoggingAdapter().log(Level.WARNING, "Invalid syntax. Usage: warp <player> <warp>");
return;
}
CompletableFuture.runAsync(() -> {
final OnlineUser playerToTeleport = plugin.findPlayer(args[0]).orElse(null);
if (playerToTeleport == null) {
plugin.getLoggingAdapter().log(Level.WARNING, "Player not found: " + args[0]);
return;
}
final OnlineUser playerToTeleport = plugin.findPlayer(args[0]).orElse(null);
if (playerToTeleport == null) {
plugin.getLoggingAdapter().log(Level.WARNING, "Player not found: " + args[0]);
return;
}
final Warp warp = plugin.getDatabase().getWarp(args[1]).join().orElse(null);
if (warp == null) {
plugin.getDatabase().getWarp(args[1]).thenAccept(optionalWarp -> {
if (optionalWarp.isEmpty()) {
plugin.getLoggingAdapter().log(Level.WARNING, "Could not find warp '" + args[1] + "'");
return;
}
final Warp warp = optionalWarp.get();
plugin.getLoggingAdapter().log(Level.INFO, "Teleporting " + playerToTeleport.username + " to " + warp.meta.name);
plugin.getTeleportManager().teleport(playerToTeleport, warp)
plugin.getTeleportManager()
.teleport(playerToTeleport, warp)
.thenAccept(result -> plugin.getTeleportManager().finishTeleport(playerToTeleport, result));
});
}
@@ -63,11 +63,10 @@ public class WarpListCommand extends CommandBase implements ConsoleExecutable {
@Override
public void onConsoleExecute(@NotNull String[] args) {
CompletableFuture.runAsync(() -> {
final List<Warp> warps = plugin.getDatabase().getWarps().join();
StringJoiner rowJoiner = new StringJoiner(" ");
plugin.getDatabase().getWarps().thenAccept(warps -> {
plugin.getLoggingAdapter().log(Level.INFO, "List of " + warps.size() + " warps:");
StringJoiner rowJoiner = new StringJoiner(" ");
for (int i = 1; i <= warps.size(); i++) {
final String warp = warps.get(i - 1).meta.name;
rowJoiner.add(warp.length() < 16 ? warp + " ".repeat(16 - warp.length()) : warp);