More refactor work, encapsulate classes

This commit is contained in:
William278 committed 2023-03-02 15:00:02 +00:00
1 parent 3e1ec09487
commit 1cebdac9b8
51 files changed
+756 -621

No files matched your search

@@ -163,8 +163,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
this.eventDispatcher = new BukkitEventDispatcher(this);
// Initialize the cache
cache = new Cache(eventDispatcher);
cache.initialize(database);
this.cache = new Cache(this);
// Prepare the home and warp position manager
this.manager = new Manager(this);
@@ -445,7 +444,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask
final int y = snapshot.getHighestBlockYAt(x, z);
final Material blockType = snapshot.getBlockType(chunkX, y, chunkZ);
if (!isBlockUnsafe(blockType.getKey().toString())) {
return new Location((location.x + dX) + 0.5d, y + 1.25d, (location.z + dZ) + 0.5d, location.world);
return new Location((location.getX() + dX) + 0.5d, y + 1.25d, (location.getZ() + dZ) + 0.5d, location.getWorld());
}
}
}
@@ -18,7 +18,6 @@ import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
/**
* Hook to display warps and public homes on Dynmap
@@ -35,7 +34,8 @@ public class DynMapHook extends MapHook {
@Override
protected CompletableFuture<Void> initializeMap() {
return CompletableFuture.runAsync(() -> {
final CompletableFuture<Void> initializedFuture = new CompletableFuture<>();
plugin.runAsync(() -> {
final MarkerAPI markerAPI = dynmapAPI.getMarkerAPI();
if (plugin.getSettings().isPublicHomesOnMap()) {
markerAPI.getMarkerIcons().stream()
@@ -57,10 +57,9 @@ public class DynMapHook extends MapHook {
markerAPI.createMarkerSet(WARPS_MARKER_SET_ID,
"Warps", dynmapAPI.getMarkerAPI().getMarkerIcons(), false);
}
}).exceptionally(throwable -> {
plugin.getLoggingAdapter().log(Level.SEVERE, "Failed to initialize Dynmap integration", throwable);
return null;
initializedFuture.complete(null);
});
return initializedFuture;
}
@Override
@@ -70,13 +69,13 @@ public class DynMapHook extends MapHook {
final CompletableFuture<Void> updatedFuture = new CompletableFuture<>();
removeHome(home).thenRun(() -> Bukkit.getScheduler().runTask((BukkitHuskHomes) plugin, () -> {
dynmapAPI.getMarkerAPI().getMarkerSet(PUBLIC_HOMES_MARKER_SET_ID).createMarker(
home.owner.uuid + ":" + home.uuid, home.meta.name, home.world.name,
home.x, home.y, home.z, dynmapAPI.getMarkerAPI().getMarkerIcon(PUBLIC_HOME_MARKER_IMAGE_NAME), false)
.setDescription(MarkerInformationPopup.create(home.meta.name)
home.getOwner().uuid + ":" + home.getUuid(), home.getMeta().getName(), home.getWorld().getName(),
home.getX(), home.getY(), home.getZ(), dynmapAPI.getMarkerAPI().getMarkerIcon(PUBLIC_HOME_MARKER_IMAGE_NAME), false)
.setDescription(MarkerInformationPopup.create(home.getMeta().getName())
.setThumbnailMarker(PUBLIC_HOME_MARKER_IMAGE_NAME)
.addField("Owner", home.owner.username)
.addField("Description", plugin.getLocales().formatDescription(home.meta.description))
.addField("Command", "/" + BukkitCommandType.PUBLIC_HOME_COMMAND.commandBase.command + " " + home.meta.name)
.addField("Owner", home.getOwner().username)
.addField("Description", plugin.getLocales().formatDescription(home.getMeta().getDescription()))
.addField("Command", "/" + BukkitCommandType.PUBLIC_HOME_COMMAND.commandBase.command + " " + home.getMeta().getName())
.toHtml());
updatedFuture.complete(null);
}));
@@ -90,7 +89,7 @@ public class DynMapHook extends MapHook {
final CompletableFuture<Void> removedFuture = new CompletableFuture<>();
Bukkit.getScheduler().runTask((BukkitHuskHomes) plugin, () -> {
dynmapAPI.getMarkerAPI().getMarkerSet(PUBLIC_HOMES_MARKER_SET_ID).getMarkers().stream()
.filter(marker -> marker.getMarkerID().equals(home.owner.uuid + ":" + home.uuid))
.filter(marker -> marker.getMarkerID().equals(home.getOwner().uuid + ":" + home.getUuid()))
.findFirst()
.ifPresent(Marker::deleteMarker);
removedFuture.complete(null);
@@ -117,12 +116,12 @@ public class DynMapHook extends MapHook {
final CompletableFuture<Void> updatedFuture = new CompletableFuture<>();
removeWarp(warp).thenRun(() -> Bukkit.getScheduler().runTask((BukkitHuskHomes) plugin, () -> {
dynmapAPI.getMarkerAPI().getMarkerSet(WARPS_MARKER_SET_ID).createMarker(
warp.uuid.toString(), warp.meta.name, warp.world.name,
warp.x, warp.y, warp.z, dynmapAPI.getMarkerAPI().getMarkerIcon(WARP_MARKER_IMAGE_NAME), false)
.setDescription(MarkerInformationPopup.create(warp.meta.name)
warp.getUuid().toString(), warp.getMeta().getName(), warp.getWorld().getName(),
warp.getX(), warp.getY(), warp.getZ(), dynmapAPI.getMarkerAPI().getMarkerIcon(WARP_MARKER_IMAGE_NAME), false)
.setDescription(MarkerInformationPopup.create(warp.getMeta().getName())
.setThumbnailMarker(WARP_MARKER_IMAGE_NAME)
.addField("Description", plugin.getLocales().formatDescription(warp.meta.description))
.addField("Command", "/" + BukkitCommandType.WARP_COMMAND.commandBase.command + " " + warp.meta.name)
.addField("Description", plugin.getLocales().formatDescription(warp.getMeta().getDescription()))
.addField("Command", "/" + BukkitCommandType.WARP_COMMAND.commandBase.command + " " + warp.getMeta().getName())
.toHtml());
updatedFuture.complete(null);
}));
@@ -136,7 +135,7 @@ public class DynMapHook extends MapHook {
final CompletableFuture<Void> removedFuture = new CompletableFuture<>();
CompletableFuture.runAsync(() -> Bukkit.getScheduler().runTask((BukkitHuskHomes) plugin, () -> {
dynmapAPI.getMarkerAPI().getMarkerSet(WARPS_MARKER_SET_ID).getMarkers().stream()
.filter(marker -> marker.getMarkerID().equals(warp.uuid.toString()))
.filter(marker -> marker.getMarkerID().equals(warp.getUuid().toString()))
.findFirst()
.ifPresent(Marker::deleteMarker);
removedFuture.complete(null);
@@ -74,9 +74,9 @@ public class BukkitEventListener extends EventListener implements Listener {
BukkitAdapter.adaptLocation(location).ifPresent(adaptedLocation -> {
final OnlineUser onlineUser = BukkitPlayer.adapt(event.getPlayer());
super.handlePlayerUpdateSpawnPoint(onlineUser, new Position(
adaptedLocation.x, adaptedLocation.y, adaptedLocation.z,
adaptedLocation.yaw, adaptedLocation.pitch,
adaptedLocation.world, plugin.getServerName()));
adaptedLocation.getX(), adaptedLocation.getY(), adaptedLocation.getZ(),
adaptedLocation.getYaw(), adaptedLocation.getPitch(),
adaptedLocation.getWorld(), plugin.getServerName()));
});
}
@@ -78,18 +78,18 @@ public class PluginMessenger extends Messenger implements PluginMessageListener
return fetchOnlineServerList(onlineUser).thenApply(onlineServers -> {
// Ensure the server is online
final Optional<String> targetServer = Arrays.stream(onlineServers)
.filter(serverName -> serverName.equals(server.name))
.filter(serverName -> serverName.equals(server.getName()))
.findFirst();
if (targetServer.isEmpty()) {
plugin.getLoggingAdapter().log(Level.WARNING,
"Failed to send " + dispatcher.username + " to " + server.name + "; server offline?");
"Failed to send " + dispatcher.username + " to " + server.getName() + "; server offline?");
return false;
}
// Send player to target server
final ByteArrayDataOutput messageWriter = ByteStreams.newDataOutput();
messageWriter.writeUTF("Connect");
messageWriter.writeUTF(server.name);
messageWriter.writeUTF(server.getName());
dispatcher.sendPluginMessage(BUNGEE_PLUGIN_CHANNEL_NAME, messageWriter.toByteArray());
return true;
});
@@ -19,15 +19,15 @@ public final class BukkitAdapter {
* @return the adapted {@link Location}
*/
public static Optional<org.bukkit.Location> adaptLocation(@NotNull Location location) {
org.bukkit.World world = Bukkit.getWorld(location.world.name);
org.bukkit.World world = Bukkit.getWorld(location.getWorld().getName());
if (world == null) {
world = Bukkit.getWorld(location.world.uuid);
world = Bukkit.getWorld(location.getWorld().getUuid());
}
if (world == null) {
return Optional.empty();
}
return Optional.of(new org.bukkit.Location(world, location.x, location.y, location.z,
location.yaw, location.pitch));
return Optional.of(new org.bukkit.Location(world, location.getX(), location.getY(), location.getZ(),
location.getYaw(), location.getPitch()));
}
/**
@@ -4,7 +4,6 @@ import de.themoep.minedown.adventure.MineDown;
import net.william278.huskhomes.command.CommandBase;
import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.database.Database;
import net.william278.huskhomes.event.EventDispatcher;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.position.Home;
@@ -23,79 +22,35 @@ import java.util.stream.Collectors;
*/
public class Cache {
/**
* Cached home names - maps a {@link UUID} to a list of their homes
*/
public final HashMap<UUID, List<String>> homes;
/**
* Cached home names - maps a username to a list of their public homes
*/
public final HashMap<String, List<String>> publicHomes;
/**
* Cached warp names
*/
public final List<String> warps;
/**
* Cached player list
*/
public final Set<String> players;
/**
* Cached lists of private homes for pagination, mapped to the username of the home owner
*/
public final HashMap<String, PaginatedList> privateHomeLists;
/**
* Cached lists of public homes for pagination
*/
public final HashMap<UUID, PaginatedList> publicHomeLists;
/**
* Cached lists of warps for pagination
*/
public final HashMap<UUID, PaginatedList> warpLists;
/**
* Cached user UUIDs currently on warmup countdowns for {@link TimedTeleport}s
*/
public final HashSet<UUID> currentlyOnWarmup;
/**
* Plugin event dispatcher
*/
private final EventDispatcher eventDispatcher;
private final HuskHomes plugin;
private final Map<UUID, List<String>> homes = new HashMap<>();
private final Map<String, List<String>> publicHomes = new HashMap<>();
private final List<String> warps = new ArrayList<>();
private final Set<String> players = new HashSet<>();
private final Map<String, PaginatedList> privateHomeLists = new HashMap<>();
private final Map<UUID, PaginatedList> publicHomeLists = new HashMap<>();
private final Map<UUID, PaginatedList> warpLists = new HashMap<>();
private final Set<UUID> currentlyOnWarmup = new HashSet<>();
/**
* Create a new cache
*/
public Cache(@NotNull EventDispatcher eventDispatcher) {
this.homes = new HashMap<>();
this.publicHomes = new HashMap<>();
this.warps = new ArrayList<>();
this.players = new HashSet<>();
this.privateHomeLists = new HashMap<>();
this.publicHomeLists = new HashMap<>();
this.warpLists = new HashMap<>();
this.currentlyOnWarmup = new HashSet<>();
this.eventDispatcher = eventDispatcher;
public Cache(@NotNull HuskHomes plugin) {
this.plugin = plugin;
this.initialize();
}
/**
* Initialize the cache, request basic data to load into memory
*
* @param database the database to load data from
* Initialize the cache with public home and warp names
*/
public void initialize(@NotNull Database database) {
CompletableFuture.runAsync(() -> {
database.getPublicHomes().thenAccept(publicHomeList -> publicHomeList.forEach(home -> {
this.publicHomes.putIfAbsent(home.owner.username, new ArrayList<>());
this.publicHomes.get(home.owner.username).add(home.meta.name);
}));
database.getWarps().thenAccept(warpsList -> warpsList.forEach(warp ->
this.warps.add(warp.meta.name)));
public void initialize() {
final Database database = plugin.getDatabase();
plugin.runAsync(() -> {
database.getPublicHomes().forEach(home -> {
this.getPublicHomes().putIfAbsent(home.getOwner().username, new ArrayList<>());
this.getPublicHomes().get(home.getOwner().username).add(home.getMeta().getName());
});
database.getWarps().forEach(warp -> this.getWarps().add(warp.getMeta().getName()));
});
}
@@ -105,8 +60,8 @@ public class Cache {
* @param plugin the implementing plugin
*/
public CompletableFuture<Set<String>> updatePlayerListCache(@NotNull HuskHomes plugin, @NotNull OnlineUser requester) {
players.clear();
players.addAll(plugin.getOnlinePlayers()
getPlayers().clear();
getPlayers().addAll(plugin.getOnlinePlayers()
.stream()
.filter(player -> !player.isVanished())
.map(onlineUser -> onlineUser.username)
@@ -116,11 +71,11 @@ public class Cache {
return plugin.getMessenger()
.getOnlinePlayerNames(requester)
.thenApply(networkedPlayers -> {
players.addAll(Set.of(networkedPlayers));
return players;
getPlayers().addAll(Set.of(networkedPlayers));
return getPlayers();
});
}
return CompletableFuture.completedFuture(players);
return CompletableFuture.completedFuture(getPlayers());
}
/**
@@ -131,7 +86,7 @@ public class Cache {
* @since 3.1
*/
public boolean isWarmingUp(@NotNull UUID userUuid) {
return this.currentlyOnWarmup.contains(userUuid);
return this.getCurrentlyOnWarmup().contains(userUuid);
}
@NotNull
@@ -161,61 +116,61 @@ public class Cache {
@NotNull
public Optional<MineDown> getHomeList(@NotNull OnlineUser onlineUser, @NotNull User homeOwner, @NotNull Locales locales,
@NotNull List<Home> homes, final int itemsPerPage, final int page) {
if (eventDispatcher.dispatchViewHomeListEvent(homes, onlineUser, false).join().isCancelled()) {
if (plugin.getEventDispatcher().dispatchViewHomeListEvent(homes, onlineUser, false).join().isCancelled()) {
return Optional.empty();
}
final String homeListArguments = !onlineUser.equals(homeOwner) ? " " + homeOwner.username : "";
final PaginatedList homeList = PaginatedList.of(homes.stream().map(home ->
locales.getRawLocale("home_list_item",
Locales.escapeMineDown(home.meta.name),
Locales.escapeMineDown(home.owner.username + "." + home.meta.name),
Locales.escapeMineDown(locales.formatDescription(home.meta.description)))
.orElse(home.meta.name)).sorted().collect(Collectors.toList()), getBaseList(locales, itemsPerPage)
Locales.escapeMineDown(home.getMeta().getName()),
Locales.escapeMineDown(home.getOwner().username + "." + home.getMeta().getName()),
Locales.escapeMineDown(locales.formatDescription(home.getMeta().getDescription())))
.orElse(home.getMeta().getName())).sorted().collect(Collectors.toList()), getBaseList(locales, itemsPerPage)
.setHeaderFormat(locales.getRawLocale("home_list_page_title",
homeOwner.username, "%first_item_on_page_index%",
"%last_item_on_page_index%", "%total_items%").orElse(""))
.setCommand("/huskhomes:homelist" + homeListArguments).build());
this.privateHomeLists.put(homeOwner.username, homeList);
this.getPrivateHomeLists().put(homeOwner.username, homeList);
return Optional.of(homeList.getNearestValidPage(page));
}
@NotNull
public Optional<MineDown> getPublicHomeList(@NotNull OnlineUser onlineUser, @NotNull Locales locales,
@NotNull List<Home> publicHomes, final int itemsPerPage, final int page) {
if (eventDispatcher.dispatchViewHomeListEvent(publicHomes, onlineUser, true).join().isCancelled()) {
if (plugin.getEventDispatcher().dispatchViewHomeListEvent(publicHomes, onlineUser, true).join().isCancelled()) {
return Optional.empty();
}
final PaginatedList publicHomeList = PaginatedList.of(publicHomes.stream().map(home ->
locales.getRawLocale("public_home_list_item",
Locales.escapeMineDown(home.meta.name),
Locales.escapeMineDown(home.owner.username + "." + home.meta.name),
Locales.escapeMineDown(home.owner.username),
Locales.escapeMineDown(locales.formatDescription(home.meta.description)))
.orElse(home.meta.name)).sorted().collect(Collectors.toList()), getBaseList(locales, itemsPerPage)
Locales.escapeMineDown(home.getMeta().getName()),
Locales.escapeMineDown(home.getOwner().username + "." + home.getMeta().getName()),
Locales.escapeMineDown(home.getOwner().username),
Locales.escapeMineDown(locales.formatDescription(home.getMeta().getDescription())))
.orElse(home.getMeta().getName())).sorted().collect(Collectors.toList()), getBaseList(locales, itemsPerPage)
.setHeaderFormat(locales.getRawLocale("public_home_list_page_title",
"%first_item_on_page_index%", "%last_item_on_page_index%",
"%total_items%").orElse(""))
.setCommand("/huskhomes:publichomelist").build());
publicHomeLists.put(onlineUser.uuid, publicHomeList);
getPublicHomeLists().put(onlineUser.uuid, publicHomeList);
return Optional.of(publicHomeList.getNearestValidPage(page));
}
@NotNull
public Optional<MineDown> getWarpList(@NotNull OnlineUser onlineUser, @NotNull Locales locales,
@NotNull List<Warp> warps, final int itemsPerPage, final int page) {
if (eventDispatcher.dispatchViewWarpListEvent(warps, onlineUser).join().isCancelled()) {
if (plugin.getEventDispatcher().dispatchViewWarpListEvent(warps, onlineUser).join().isCancelled()) {
return Optional.empty();
}
final PaginatedList warpList = PaginatedList.of(warps.stream()
.map(warp -> locales.getRawLocale("warp_list_item",
Locales.escapeMineDown(warp.meta.name),
Locales.escapeMineDown(locales.formatDescription(warp.meta.description)))
.orElse(warp.meta.name)).sorted().collect(Collectors.toList()), getBaseList(locales, itemsPerPage)
Locales.escapeMineDown(warp.getMeta().getName()),
Locales.escapeMineDown(locales.formatDescription(warp.getMeta().getDescription())))
.orElse(warp.getMeta().getName())).sorted().collect(Collectors.toList()), getBaseList(locales, itemsPerPage)
.setHeaderFormat(locales.getRawLocale("warp_list_page_title",
"%first_item_on_page_index%", "%last_item_on_page_index%",
"%total_items%").orElse(""))
.setCommand("/huskhomes:warplist").build());
warpLists.put(onlineUser.uuid, warpList);
getWarpLists().put(onlineUser.uuid, warpList);
return Optional.of(warpList.getNearestValidPage(page));
}
@@ -238,4 +193,59 @@ public class Cache {
.getNearestValidPage(page);
}
/**
* Cached home names - maps a {@link UUID} to a list of their homes
*/
public Map<UUID, List<String>> getHomes() {
return homes;
}
/**
* Cached home names - maps a username to a list of their public homes
*/
public Map<String, List<String>> getPublicHomes() {
return publicHomes;
}
/**
* Cached warp names
*/
public List<String> getWarps() {
return warps;
}
/**
* Cached player list
*/
public Set<String> getPlayers() {
return players;
}
/**
* Cached lists of private homes for pagination, mapped to the username of the home owner
*/
public Map<String, PaginatedList> getPrivateHomeLists() {
return privateHomeLists;
}
/**
* Cached lists of public homes for pagination
*/
public Map<UUID, PaginatedList> getPublicHomeLists() {
return publicHomeLists;
}
/**
* Cached lists of warps for pagination
*/
public Map<UUID, PaginatedList> getWarpLists() {
return warpLists;
}
/**
* Cached user UUIDs currently on warmup countdowns for {@link TimedTeleport}s
*/
public Set<UUID> getCurrentlyOnWarmup() {
return currentlyOnWarmup;
}
}
@@ -5,7 +5,7 @@ import org.jetbrains.annotations.NotNull;
public class ValidationException extends IllegalArgumentException {
public ValidationException(@NotNull ValidationError error) {
super("Error validating position: " + error.toString());
super("Error validating position: " + error.name());
}
public enum ValidationError {
@@ -143,7 +143,7 @@ public abstract class BaseHuskHomesAPI {
*/
public final CompletableFuture<List<Home>> getUserPublicHomes(@NotNull User user) {
return getUserHomes(user).thenApply(homes -> homes.stream()
.filter(home -> home.isPublic)
.filter(home -> home.isPublic())
.collect(Collectors.toList()));
}
@@ -320,7 +320,7 @@ public abstract class BaseHuskHomesAPI {
final boolean timedTeleport,
@NotNull String... rtpArgs) {
return plugin.supplyAsync(() -> plugin.getRandomTeleportEngine()
.getRandomPosition(user.getPosition().world, rtpArgs)
.getRandomPosition(user.getPosition().getWorld(), rtpArgs)
.map(position -> {
final TeleportBuilder builder = Teleport.builder(plugin, user)
.setTarget(position);
@@ -125,7 +125,7 @@ public class DelHomeCommand extends CommandBase implements TabCompletable {
if (user == null) {
return Collections.emptyList();
}
return args.length > 1 ? Collections.emptyList() : plugin.getCache().homes
return args.length > 1 ? Collections.emptyList() : plugin.getCache().getHomes()
.getOrDefault(user.uuid, new ArrayList<>())
.stream()
.filter(s -> s.startsWith(args.length == 1 ? args[0] : ""))
@@ -73,7 +73,7 @@ public class DelWarpCommand extends CommandBase implements TabCompletable {
@Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
return args.length > 1 ? Collections.emptyList() : plugin.getCache().warps
return args.length > 1 ? Collections.emptyList() : plugin.getCache().getWarps()
.stream()
.filter(s -> s.startsWith(args.length == 1 ? args[0] : ""))
.sorted()
@@ -85,7 +85,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
private void editHome(@NotNull Home home, @NotNull OnlineUser editor,
@Nullable String editOperation, @Nullable String editArgs) {
final AtomicBoolean showMenuFlag = new AtomicBoolean(false);
final boolean otherOwner = !editor.equals(home.owner);
final boolean otherOwner = !editor.equals(home.getOwner());
if (editOperation == null) {
getHomeEditorWindow(home, true, otherOwner,
@@ -114,17 +114,17 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
return;
}
final String oldHomeName = home.meta.name;
final String oldHomeName = home.getMeta().getName();
final String newHomeName = editArgs;
plugin.getManager().updateHomeMeta(home, new PositionMeta(newHomeName, home.meta.description))
plugin.getManager().updateHomeMeta(home, new PositionMeta(newHomeName, home.getMeta().getDescription()))
.thenAccept(renameResult -> (switch (renameResult.resultType()) {
case SUCCESS -> {
if (home.owner.equals(editor)) {
if (home.getOwner().equals(editor)) {
yield plugin.getLocales().getLocale("edit_home_update_name",
oldHomeName, newHomeName);
} else {
yield plugin.getLocales().getLocale("edit_home_update_name_other",
home.owner.username, oldHomeName, newHomeName);
home.getOwner().username, oldHomeName, newHomeName);
}
}
case FAILED_DUPLICATE -> plugin.getLocales().getLocale("error_home_name_taken");
@@ -134,23 +134,23 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
}).ifPresent(editor::sendMessage));
}
case "description" -> {
final String oldHomeDescription = home.meta.description;
final String oldHomeDescription = home.getMeta().getDescription();
final String newDescription = editArgs != null ? editArgs : "";
plugin.getManager().updateHomeMeta(home, new PositionMeta(home.meta.name, newDescription))
plugin.getManager().updateHomeMeta(home, new PositionMeta(home.getMeta().getName(), newDescription))
.thenAccept(descriptionUpdateResult -> (switch (descriptionUpdateResult.resultType()) {
case SUCCESS -> {
if (home.owner.equals(editor)) {
if (home.getOwner().equals(editor)) {
yield plugin.getLocales().getLocale("edit_home_update_description",
home.meta.name,
home.getMeta().getName(),
oldHomeDescription.isBlank() ? plugin.getLocales()
.getRawLocale("item_no_description").orElse("N/A") : oldHomeDescription,
newDescription.isBlank() ? plugin.getLocales()
.getRawLocale("item_no_description").orElse("N/A") : newDescription);
} else {
yield plugin.getLocales().getLocale("edit_home_update_description_other",
home.owner.username,
home.meta.name,
home.getOwner().username,
home.getMeta().getName(),
oldHomeDescription.isBlank() ? plugin.getLocales()
.getRawLocale("item_no_description").orElse("N/A") : oldHomeDescription,
newDescription.isBlank() ? plugin.getLocales()
@@ -166,12 +166,12 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
}
case "relocate" ->
plugin.getManager().updateHomePosition(home, editor.getPosition()).thenRun(() -> {
if (home.owner.equals(editor)) {
if (home.getOwner().equals(editor)) {
editor.sendMessage(plugin.getLocales().getLocale("edit_home_update_location",
home.meta.name).orElse(new MineDown("")));
home.getMeta().getName()).orElse(new MineDown("")));
} else {
editor.sendMessage(plugin.getLocales().getLocale("edit_home_update_location_other",
home.owner.username, home.meta.name).orElse(new MineDown("")));
home.getOwner().username, home.getMeta().getName()).orElse(new MineDown("")));
}
// Show the menu if the menu flag is set
@@ -188,7 +188,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
.ifPresent(editor::sendMessage);
return;
}
final AtomicBoolean newIsPublic = new AtomicBoolean(!home.isPublic);
final AtomicBoolean newIsPublic = new AtomicBoolean(!home.isPublic());
if (editArgs != null && !editArgs.isBlank()) {
if (editArgs.equalsIgnoreCase("private")) {
newIsPublic.set(false);
@@ -202,7 +202,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
}
}
final String privacyKeyedString = newIsPublic.get() ? "public" : "private";
if (newIsPublic.get() == home.isPublic) {
if (newIsPublic.get() == home.isPublic()) {
plugin.getLocales().getLocale(
"error_edit_home_privacy_already_" + privacyKeyedString)
.ifPresent(editor::sendMessage);
@@ -233,14 +233,14 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
// Execute the update
plugin.getManager().updateHomePrivacy(home, newIsPublic.get()).thenRun(() -> {
if (home.owner.equals(editor)) {
if (home.getOwner().equals(editor)) {
editor.sendMessage(plugin.getLocales().getLocale(
"edit_home_privacy_" + privacyKeyedString + "_success",
home.meta.name).orElse(new MineDown("")));
home.getMeta().getName()).orElse(new MineDown("")));
} else {
editor.sendMessage(plugin.getLocales().getLocale(
"edit_home_privacy_" + privacyKeyedString + "_success_other",
home.owner.username, home.meta.name).orElse(new MineDown("")));
home.getOwner().username, home.getMeta().getName()).orElse(new MineDown("")));
}
// Perform necessary economy transaction
@@ -290,43 +290,43 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
return new ArrayList<>() {{
if (showTitle) {
if (!otherViewer) {
plugin.getLocales().getLocale("edit_home_menu_title", home.meta.name)
plugin.getLocales().getLocale("edit_home_menu_title", home.getMeta().getName())
.ifPresent(this::add);
} else {
plugin.getLocales().getLocale("edit_home_menu_title_other", home.owner.username, home.meta.name)
plugin.getLocales().getLocale("edit_home_menu_title_other", home.getOwner().username, home.getMeta().getName())
.ifPresent(this::add);
}
}
plugin.getLocales().getLocale("edit_home_menu_metadata_" + (!home.isPublic ? "private" : "public"),
plugin.getLocales().getLocale("edit_home_menu_metadata_" + (!home.isPublic() ? "private" : "public"),
DateTimeFormatter.ofPattern("MMM dd yyyy, HH:mm")
.format(home.meta.creationTime.atZone(ZoneId.systemDefault())),
home.uuid.toString().split(Pattern.quote("-"))[0],
home.uuid.toString())
.format(home.getMeta().getCreationTime().atZone(ZoneId.systemDefault())),
home.getUuid().toString().split(Pattern.quote("-"))[0],
home.getUuid().toString())
.ifPresent(this::add);
if (home.meta.description.length() > 0) {
if (home.getMeta().getDescription().length() > 0) {
plugin.getLocales().getLocale("edit_home_menu_description",
home.meta.description.length() > 50
? home.meta.description.substring(0, 49).trim() + "…" : home.meta.description,
plugin.getLocales().formatDescription(home.meta.description))
home.getMeta().getDescription().length() > 50
? home.getMeta().getDescription().substring(0, 49).trim() + "…" : home.getMeta().getDescription(),
plugin.getLocales().formatDescription(home.getMeta().getDescription()))
.ifPresent(this::add);
}
if (!plugin.getSettings().isCrossServer()) {
plugin.getLocales().getLocale("edit_home_menu_world", home.world.name)
plugin.getLocales().getLocale("edit_home_menu_world", home.getWorld().getName())
.ifPresent(this::add);
} else {
plugin.getLocales().getLocale("edit_home_menu_world_server", home.world.name, home.server.name)
plugin.getLocales().getLocale("edit_home_menu_world_server", home.getWorld().getName(), home.getServer().getName())
.ifPresent(this::add);
}
plugin.getLocales().getLocale("edit_home_menu_coordinates",
String.format("%.1f", home.x), String.format("%.1f", home.y), String.format("%.1f", home.z),
String.format("%.2f", home.yaw), String.format("%.2f", home.pitch))
String.format("%.1f", home.getX()), String.format("%.1f", home.getY()), String.format("%.1f", home.getZ()),
String.format("%.2f", home.getYaw()), String.format("%.2f", home.getPitch()))
.ifPresent(this::add);
final String formattedName = home.owner.username + "." + home.meta.name;
final String formattedName = home.getOwner().username + "." + home.getMeta().getName();
if (showTeleportButton) {
plugin.getLocales().getLocale("edit_home_menu_use_buttons",
formattedName)
@@ -336,7 +336,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
plugin.getLocales().getRawLocale("edit_home_menu_manage_buttons", escapedName,
showPrivacyToggleButton ? plugin.getLocales()
.getRawLocale("edit_home_menu_privacy_button_"
+ (home.isPublic ? "private" : "public"), escapedName)
+ (home.isPublic() ? "private" : "public"), escapedName)
.orElse("") : "")
.map(MineDown::new).ifPresent(this::add);
plugin.getLocales().getLocale("edit_home_menu_meta_edit_buttons",
@@ -351,7 +351,7 @@ public class EditHomeCommand extends CommandBase implements TabCompletable {
return Collections.emptyList();
}
return switch (args.length) {
case 0, 1 -> plugin.getCache().homes.getOrDefault(user.uuid, new ArrayList<>())
case 0, 1 -> plugin.getCache().getHomes().getOrDefault(user.uuid, new ArrayList<>())
.stream()
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
.sorted()
@@ -83,9 +83,9 @@ public class EditWarpCommand extends CommandBase implements TabCompletable {
return;
}
final String oldWarpName = warp.meta.name;
final String oldWarpName = warp.getMeta().getName();
final String newWarpName = editArgs;
plugin.getManager().updateWarpMeta(warp, new PositionMeta(newWarpName, warp.meta.description))
plugin.getManager().updateWarpMeta(warp, new PositionMeta(newWarpName, warp.getMeta().getDescription()))
.thenAccept(renameResult -> (switch (renameResult.resultType()) {
case SUCCESS ->
plugin.getLocales().getLocale("edit_warp_update_name", oldWarpName, newWarpName);
@@ -96,13 +96,13 @@ public class EditWarpCommand extends CommandBase implements TabCompletable {
}).ifPresent(editor::sendMessage));
}
case "description" -> {
final String oldWarpDescription = warp.meta.description;
final String oldWarpDescription = warp.getMeta().getDescription();
final String newDescription = editArgs != null ? editArgs : "";
plugin.getManager().updateWarpMeta(warp, new PositionMeta(warp.meta.name, newDescription))
plugin.getManager().updateWarpMeta(warp, new PositionMeta(warp.getMeta().getName(), newDescription))
.thenAccept(descriptionUpdateResult -> (switch (descriptionUpdateResult.resultType()) {
case SUCCESS -> plugin.getLocales().getLocale("edit_warp_update_description",
warp.meta.name,
warp.getMeta().getName(),
oldWarpDescription.isBlank() ? plugin.getLocales()
.getRawLocale("item_no_description").orElse("N/A") : oldWarpDescription,
newDescription.isBlank() ? plugin.getLocales()
@@ -117,7 +117,7 @@ public class EditWarpCommand extends CommandBase implements TabCompletable {
case "relocate" ->
plugin.getManager().updateWarpPosition(warp, editor.getPosition()).thenRun(() -> {
editor.sendMessage(plugin.getLocales().getLocale("edit_warp_update_location",
warp.meta.name).orElse(new MineDown("")));
warp.getMeta().getName()).orElse(new MineDown("")));
// Show the menu if the menu flag is set
if (showMenuFlag.get()) {
@@ -156,43 +156,43 @@ public class EditWarpCommand extends CommandBase implements TabCompletable {
final boolean showTeleportButton) {
return new ArrayList<>() {{
if (showTitle) {
plugin.getLocales().getLocale("edit_warp_menu_title", warp.meta.name)
plugin.getLocales().getLocale("edit_warp_menu_title", warp.getMeta().getName())
.ifPresent(this::add);
}
plugin.getLocales().getLocale("edit_warp_menu_metadata",
DateTimeFormatter.ofPattern("MMM dd yyyy, HH:mm")
.format(warp.meta.creationTime.atZone(ZoneId.systemDefault())),
warp.uuid.toString().split(Pattern.quote("-"))[0],
warp.uuid.toString())
.format(warp.getMeta().getCreationTime().atZone(ZoneId.systemDefault())),
warp.getUuid().toString().split(Pattern.quote("-"))[0],
warp.getUuid().toString())
.ifPresent(this::add);
if (warp.meta.description.length() > 0) {
if (warp.getMeta().getDescription().length() > 0) {
plugin.getLocales().getLocale("edit_warp_menu_description",
warp.meta.description.length() > 50
? warp.meta.description.substring(0, 49).trim() + "…" : warp.meta.description,
plugin.getLocales().formatDescription(warp.meta.description))
warp.getMeta().getDescription().length() > 50
? warp.getMeta().getDescription().substring(0, 49).trim() + "…" : warp.getMeta().getDescription(),
plugin.getLocales().formatDescription(warp.getMeta().getDescription()))
.ifPresent(this::add);
}
if (!plugin.getSettings().isCrossServer()) {
plugin.getLocales().getLocale("edit_warp_menu_world", warp.world.name).ifPresent(this::add);
plugin.getLocales().getLocale("edit_warp_menu_world", warp.getWorld().getName()).ifPresent(this::add);
} else {
plugin.getLocales().getLocale("edit_warp_menu_world_server", warp.world.name, warp.server.name).ifPresent(this::add);
plugin.getLocales().getLocale("edit_warp_menu_world_server", warp.getWorld().getName(), warp.getServer().getName()).ifPresent(this::add);
}
plugin.getLocales().getLocale("edit_warp_menu_coordinates",
String.format("%.1f", warp.x), String.format("%.1f", warp.y), String.format("%.1f", warp.z),
String.format("%.2f", warp.yaw), String.format("%.2f", warp.pitch))
String.format("%.1f", warp.getX()), String.format("%.1f", warp.getY()), String.format("%.1f", warp.getZ()),
String.format("%.2f", warp.getYaw()), String.format("%.2f", warp.getPitch()))
.ifPresent(this::add);
if (showTeleportButton) {
plugin.getLocales().getLocale("edit_warp_menu_use_buttons", warp.meta.name)
plugin.getLocales().getLocale("edit_warp_menu_use_buttons", warp.getMeta().getName())
.ifPresent(this::add);
}
plugin.getLocales().getLocale("edit_warp_menu_manage_buttons", warp.meta.name)
plugin.getLocales().getLocale("edit_warp_menu_manage_buttons", warp.getMeta().getName())
.ifPresent(this::add);
plugin.getLocales().getLocale("edit_warp_menu_meta_edit_buttons", warp.meta.name)
plugin.getLocales().getLocale("edit_warp_menu_meta_edit_buttons", warp.getMeta().getName())
.ifPresent(this::add);
}};
}
@@ -200,7 +200,7 @@ public class EditWarpCommand extends CommandBase implements TabCompletable {
@Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
return switch (args.length) {
case 0, 1 -> plugin.getCache().warps
case 0, 1 -> plugin.getCache().getWarps()
.stream()
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
.sorted()
@@ -111,7 +111,7 @@ public class HomeCommand extends CommandBase implements TabCompletable, ConsoleE
}
plugin.getLoggingAdapter().log(Level.INFO, "Teleporting " + playerToTeleport.username + " to "
+ home.owner.username + "." + home.meta.name);
+ home.getOwner().username + "." + home.getMeta().getName());
Teleport.builder(plugin, playerToTeleport)
.setTarget(home)
.toTeleport()
@@ -124,7 +124,7 @@ public class HomeCommand extends CommandBase implements TabCompletable, ConsoleE
if (user == null) {
return Collections.emptyList();
}
return args.length > 1 ? Collections.emptyList() : plugin.getCache().homes
return args.length > 1 ? Collections.emptyList() : plugin.getCache().getHomes()
.getOrDefault(user.uuid, new ArrayList<>())
.stream()
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
@@ -53,8 +53,8 @@ public class HomeListCommand extends CommandBase implements ConsoleExecutable {
* @param pageNumber page number to display
*/
private void showHomeList(@NotNull OnlineUser onlineUser, @NotNull String homeOwner, int pageNumber) {
if (plugin.getCache().privateHomeLists.containsKey(homeOwner)) {
onlineUser.sendMessage(plugin.getCache().privateHomeLists.get(homeOwner).getNearestValidPage(pageNumber));
if (plugin.getCache().getPrivateHomeLists().containsKey(homeOwner)) {
onlineUser.sendMessage(plugin.getCache().getPrivateHomeLists().get(homeOwner).getNearestValidPage(pageNumber));
return;
}
plugin.getDatabase().getUserDataByName(homeOwner).thenAccept(optionalUser -> optionalUser.ifPresentOrElse(userData -> {
@@ -101,7 +101,7 @@ public class HomeListCommand extends CommandBase implements ConsoleExecutable {
plugin.getLoggingAdapter().log(Level.INFO, "List of " + userData.get().user().username + "'s "
+ homes.size() + " homes:");
for (int i = 0; i < homes.size(); i++) {
final String home = homes.get(i).meta.name;
final String home = homes.get(i).getMeta().getName();
rowJoiner.add(home.length() < 16 ? home + " ".repeat(16 - home.length()) : home);
if ((i + 1) % 3 == 0) {
plugin.getLoggingAdapter().log(Level.INFO, rowJoiner.toString());
@@ -125,7 +125,7 @@ public class PublicHomeCommand extends CommandBase implements TabCompletable, Co
}
plugin.getLoggingAdapter().log(Level.INFO, "Teleporting " + playerToTeleport.username + " to "
+ home.owner.username + "." + home.meta.name);
+ home.getOwner().username + "." + home.getMeta().getName());
Teleport.builder(plugin, playerToTeleport)
.setTarget(home)
.toTeleport()
@@ -137,7 +137,7 @@ public class PublicHomeCommand extends CommandBase implements TabCompletable, Co
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
// Return every public home name as username.home_name from the cache
final List<String> publicHomes = new ArrayList<>();
plugin.getCache().publicHomes.forEach((ownerName, homeNames) ->
plugin.getCache().getPublicHomes().forEach((ownerName, homeNames) ->
homeNames.forEach(homeName -> publicHomes.add(ownerName + "." + homeName)));
return args.length > 1 ? Collections.emptyList() : publicHomes
.stream()
@@ -42,8 +42,8 @@ public class PublicHomeListCommand extends CommandBase implements ConsoleExecuta
* @param pageNumber page number to display
*/
private void showPublicHomeList(@NotNull OnlineUser onlineUser, int pageNumber) {
if (plugin.getCache().publicHomeLists.containsKey(onlineUser.uuid)) {
onlineUser.sendMessage(plugin.getCache().publicHomeLists.get(onlineUser.uuid).getNearestValidPage(pageNumber));
if (plugin.getCache().getPublicHomeLists().containsKey(onlineUser.uuid)) {
onlineUser.sendMessage(plugin.getCache().getPublicHomeLists().get(onlineUser.uuid).getNearestValidPage(pageNumber));
return;
}
@@ -68,8 +68,8 @@ public class PublicHomeListCommand extends CommandBase implements ConsoleExecuta
plugin.getLoggingAdapter().log(Level.INFO, "List of " + homes.size() + " public homes:");
for (int i = 0; i < homes.size(); i++) {
final String ownerUsername = homes.get(i).owner.username;
final String homeName = homes.get(i).meta.name;
final String ownerUsername = homes.get(i).getOwner().username;
final String homeName = homes.get(i).getMeta().getName();
final String home = ownerUsername + "." + homeName;
int spacingSize = (16 - ownerUsername.length()) + 17;
rowJoiner.add(home.length() < spacingSize ? home + " ".repeat(spacingSize - home.length()) : home);
@@ -42,7 +42,7 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable {
final Position userPosition = target.getPosition();
final String[] rtpArguments = args.length >= 1 ? ArrayUtils.subarray(args, 1, args.length) : args;
if (plugin.getSettings().getRtpRestrictedWorlds().stream()
.anyMatch(worldName -> worldName.equals(userPosition.world.name))) {
.anyMatch(worldName -> worldName.equals(userPosition.getWorld().getName()))) {
plugin.getLocales().getLocale("error_rtp_restricted_world")
.ifPresent(onlineUser::sendMessage);
return;
@@ -73,7 +73,7 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable {
plugin.getLocales().getLocale("teleporting_random_generation")
.ifPresent(onlineUser::sendMessage);
final Optional<Position> position = plugin.getRandomTeleportEngine().getRandomPosition(onlineUser.getPosition().world, rtpArguments);
final Optional<Position> position = plugin.getRandomTeleportEngine().getRandomPosition(onlineUser.getPosition().getWorld(), rtpArguments);
if (position.isEmpty()) {
plugin.getLocales().getLocale("error_rtp_randomization_timeout")
.ifPresent(onlineUser::sendMessage);
@@ -111,7 +111,7 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable {
}
plugin.getLoggingAdapter().log(Level.INFO, "Finding a random position for " + foundUser.get().username + "...");
plugin.getRandomTeleportEngine().getRandomPosition(foundUser.get().getPosition().world, ArrayUtils.subarray(args, 1, args.length)).thenAccept(position -> {
plugin.getRandomTeleportEngine().getRandomPosition(foundUser.get().getPosition().getWorld(), ArrayUtils.subarray(args, 1, args.length)).thenAccept(position -> {
if (position.isEmpty()) {
plugin.getLoggingAdapter().log(Level.WARNING, "Failed to teleport " + foundUser.get().username + " to a random position; randomization timed out!");
return;
@@ -40,14 +40,14 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
// Find the online user to teleport
plugin.getCache().updatePlayerListCache(plugin, onlineUser).thenRun(() -> {
// Get the list of potential teleports, filtered against vanished players, but ensuring the executor is in the list
final Set<String> players = plugin.getCache().players;
final Set<String> players = plugin.getCache().getPlayers();
players.add(onlineUser.username);
// Find the player to teleport
final String playerToTeleport = players.stream()
.filter(user -> user.equalsIgnoreCase(targetPlayerToTeleport)).findFirst()
.or(() -> Optional.ofNullable(targetPlayerToTeleport.equals("@s") ? onlineUser.username : null))
.or(() -> plugin.getCache().players.stream().filter(user -> user.toLowerCase().startsWith(targetPlayerToTeleport)).findFirst())
.or(() -> plugin.getCache().getPlayers().stream().filter(user -> user.toLowerCase().startsWith(targetPlayerToTeleport)).findFirst())
.orElse(null);
// Ensure the player to teleport exists
@@ -104,9 +104,9 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
result.getTeleporter()
.flatMap(teleporter -> plugin.getLocales()
.getLocale("teleporting_other_complete_position", teleporter.username,
Integer.toString((int) destination.x),
Integer.toString((int) destination.y),
Integer.toString((int) destination.z)))
Integer.toString((int) destination.getX()),
Integer.toString((int) destination.getY()),
Integer.toString((int) destination.getZ())))
.ifPresent(onlineUser::sendMessage);
}));
}
@@ -211,11 +211,11 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
final ArrayList<String> completions = new ArrayList<>();
completions.addAll(serveCoordinateCompletions
? List.of("~", "~ ~", "~ ~ ~",
Integer.toString((int) user.getPosition().x),
((int) user.getPosition().x + " " + (int) user.getPosition().y),
((int) user.getPosition().x + " " + (int) user.getPosition().y + " " + (int) user.getPosition().z))
Integer.toString((int) user.getPosition().getX()),
((int) user.getPosition().getX() + " " + (int) user.getPosition().getY()),
((int) user.getPosition().getX() + " " + (int) user.getPosition().getY() + " " + (int) user.getPosition().getZ()))
: Collections.emptyList());
completions.addAll(plugin.getCache().players);
completions.addAll(plugin.getCache().getPlayers());
return completions.stream()
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
.sorted().collect(Collectors.toList());
@@ -226,16 +226,16 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
if (user == null) {
return completions;
}
completions.addAll(List.of("~", Integer.toString((int) user.getPosition().y)));
completions.addAll(List.of("~ ~", (int) user.getPosition().y + " " + (int) user.getPosition().z));
completions.addAll(List.of("~", Integer.toString((int) user.getPosition().getY())));
completions.addAll(List.of("~ ~", (int) user.getPosition().getY() + " " + (int) user.getPosition().getZ()));
} else {
completions.addAll(serveCoordinateCompletions
? List.of("~", "~ ~", "~ ~ ~",
Integer.toString((int) user.getPosition().x),
((int) user.getPosition().x + " " + (int) user.getPosition().y),
((int) user.getPosition().x + " " + (int) user.getPosition().y + " " + (int) user.getPosition().z))
Integer.toString((int) user.getPosition().getX()),
((int) user.getPosition().getX() + " " + (int) user.getPosition().getY()),
((int) user.getPosition().getX() + " " + (int) user.getPosition().getY() + " " + (int) user.getPosition().getZ()))
: Collections.emptyList());
completions.addAll(plugin.getCache().players);
completions.addAll(plugin.getCache().getPlayers());
}
return completions.stream()
.filter(s -> s.toLowerCase().startsWith(args[1].toLowerCase()))
@@ -247,13 +247,13 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
if (!serveCoordinateCompletions) {
return completions;
}
completions.addAll(List.of("~", Integer.toString((int) user.getPosition().z)));
completions.addAll(List.of("~", Integer.toString((int) user.getPosition().getZ())));
} else if (isCoordinate(args[1])) {
if (!serveCoordinateCompletions) {
return completions;
}
completions.addAll(List.of("~", Integer.toString((int) user.getPosition().y)));
completions.addAll(List.of("~ ~", (int) user.getPosition().y + " " + (int) user.getPosition().z));
completions.addAll(List.of("~", Integer.toString((int) user.getPosition().getY())));
completions.addAll(List.of("~ ~", (int) user.getPosition().getY() + " " + (int) user.getPosition().getZ()));
}
return completions.stream()
.filter(s -> s.toLowerCase().startsWith(args[2].toLowerCase()))
@@ -265,7 +265,7 @@ public class TpCommand extends CommandBase implements TabCompletable, ConsoleExe
if (!serveCoordinateCompletions) {
return completions;
}
completions.addAll(List.of("~", Integer.toString((int) user.getPosition().z)));
completions.addAll(List.of("~", Integer.toString((int) user.getPosition().getZ())));
}
return completions.stream()
.filter(s -> s.toLowerCase().startsWith(args[3].toLowerCase()))
@@ -53,7 +53,7 @@ public class TpHereCommand extends CommandBase implements TabCompletable {
@Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
return args.length <= 1 ? plugin.getCache().players.stream()
return args.length <= 1 ? plugin.getCache().getPlayers().stream()
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
.sorted().collect(Collectors.toList()) : Collections.emptyList();
}
@@ -54,7 +54,7 @@ public class TpOfflineCommand extends CommandBase implements TabCompletable {
@Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
return args.length <= 1 ? plugin.getCache().players.stream()
return args.length <= 1 ? plugin.getCache().getPlayers().stream()
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
.sorted().collect(Collectors.toList()) : Collections.emptyList();
}
@@ -42,7 +42,7 @@ public class TpRespondCommand extends CommandBase implements TabCompletable {
@Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
return args.length <= 1 ? plugin.getCache().players.stream()
return args.length <= 1 ? plugin.getCache().getPlayers().stream()
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
.sorted().collect(Collectors.toList()) : Collections.emptyList();
}
@@ -33,7 +33,7 @@ public class TpaAllCommand extends CommandBase {
// Determine players to teleport and teleport them
plugin.getCache().updatePlayerListCache(plugin, onlineUser).thenAccept(playerList -> {
final List<String> players = plugin.getCache().players.stream()
final List<String> players = plugin.getCache().getPlayers().stream()
.filter(userName -> !userName.equalsIgnoreCase(onlineUser.username)).toList();
if (players.isEmpty()) {
plugin.getLocales().getLocale("error_no_players_online").ifPresent(onlineUser::sendMessage);
@@ -52,7 +52,7 @@ public class TpaCommand extends CommandBase implements TabCompletable {
@Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
return args.length <= 1 ? plugin.getCache().players.stream()
return args.length <= 1 ? plugin.getCache().getPlayers().stream()
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
.sorted().collect(Collectors.toList()) : Collections.emptyList();
}
@@ -52,7 +52,7 @@ public class TpaHereCommand extends CommandBase implements TabCompletable {
@Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
return args.length <= 1 ? plugin.getCache().players.stream()
return args.length <= 1 ? plugin.getCache().getPlayers().stream()
.filter(s -> s.toLowerCase().startsWith(args.length == 1 ? args[0].toLowerCase() : ""))
.sorted().collect(Collectors.toList()) : Collections.emptyList();
}
@@ -63,7 +63,7 @@ public class WarpCommand extends CommandBase implements TabCompletable, ConsoleE
@Override
public @NotNull List<String> onTabComplete(@NotNull String[] args, @Nullable OnlineUser user) {
return plugin.getCache().warps.stream()
return plugin.getCache().getWarps().stream()
.filter(s -> user == null || Warp.hasPermission(plugin.getSettings().isPermissionRestrictWarps(), user, s))
.filter(s -> s.toLowerCase().startsWith(args.length >= 1 ? args[0].toLowerCase() : ""))
.sorted()
@@ -89,7 +89,7 @@ public class WarpCommand extends CommandBase implements TabCompletable, ConsoleE
}
final Warp warp = optionalWarp.get();
plugin.getLoggingAdapter().log(Level.INFO, "Teleporting " + playerToTeleport.username + " to " + warp.meta.name);
plugin.getLoggingAdapter().log(Level.INFO, "Teleporting " + playerToTeleport.username + " to " + warp.getMeta().getName());
Teleport.builder(plugin, playerToTeleport)
.setTarget(warp)
.toTimedTeleport()
@@ -40,8 +40,8 @@ public class WarpListCommand extends CommandBase implements ConsoleExecutable {
* @param pageNumber page number to display
*/
private void showWarpList(@NotNull OnlineUser onlineUser, int pageNumber) {
if (plugin.getCache().warpLists.containsKey(onlineUser.uuid)) {
onlineUser.sendMessage(plugin.getCache().warpLists.get(onlineUser.uuid).getNearestValidPage(pageNumber));
if (plugin.getCache().getWarpLists().containsKey(onlineUser.uuid)) {
onlineUser.sendMessage(plugin.getCache().getWarpLists().get(onlineUser.uuid).getNearestValidPage(pageNumber));
return;
}
@@ -51,13 +51,13 @@ public class CachedSpawn {
* @param location The {@link Location} of the spawn
*/
public CachedSpawn(@NotNull Location location) {
this.x = location.x;
this.y = location.y;
this.z = location.z;
this.yaw = location.yaw;
this.pitch = location.pitch;
this.worldName = location.world.name;
this.worldUuid = location.world.uuid.toString();
this.x = location.getX();
this.y = location.getY();
this.z = location.getZ();
this.yaw = location.getYaw();
this.pitch = location.getPitch();
this.worldName = location.getWorld().getName();
this.worldUuid = location.getWorld().getUuid().toString();
}
@SuppressWarnings("unused")
@@ -268,11 +268,11 @@ public abstract class Database {
try {
final Server server = plugin.getServerName();
return getWarps().stream()
.filter(warp -> warp.server.equals(server))
.filter(warp -> warp.getServer().equals(server))
.collect(Collectors.toList());
} catch (IllegalStateException e) {
return getWarps().stream()
.filter(warp -> plugin.getWorlds().stream().anyMatch(world -> world.equals(warp.world)))
.filter(warp -> plugin.getWorlds().stream().anyMatch(world -> world.equals(warp.getWorld())))
.collect(Collectors.toList());
}
}
@@ -295,11 +295,11 @@ public abstract class Database {
try {
final Server server = plugin.getServerName();
return getPublicHomes().stream()
.filter(home -> home.server.equals(server))
.filter(home -> home.getServer().equals(server))
.collect(Collectors.toList());
} catch (IllegalStateException e) {
return plugin.getDatabase().getPublicHomes().stream()
.filter(home -> plugin.getWorlds().stream().anyMatch(world -> world.equals(home.world)))
.filter(home -> plugin.getWorlds().stream().anyMatch(world -> world.equals(home.getWorld())))
.collect(Collectors.toList());
}
}
@@ -145,14 +145,14 @@ public class MySqlDatabase extends Database {
VALUES (?,?,?,?,?,?,?,?);"""),
Statement.RETURN_GENERATED_KEYS)) {
statement.setDouble(1, position.x);
statement.setDouble(2, position.y);
statement.setDouble(3, position.z);
statement.setFloat(4, position.yaw);
statement.setFloat(5, position.pitch);
statement.setString(6, position.world.name);
statement.setString(7, position.world.uuid.toString());
statement.setString(8, position.server.name);
statement.setDouble(1, position.getX());
statement.setDouble(2, position.getY());
statement.setDouble(3, position.getZ());
statement.setFloat(4, position.getYaw());
statement.setFloat(5, position.getPitch());
statement.setString(6, position.getWorld().getName());
statement.setString(7, position.getWorld().getUuid().toString());
statement.setString(8, position.getServer().getName());
statement.executeUpdate();
final ResultSet resultSet = statement.getGeneratedKeys();
@@ -176,14 +176,14 @@ public class MySqlDatabase extends Database {
`world_name`=?,
`server_name`=?
WHERE `id`=?"""))) {
statement.setDouble(1, position.x);
statement.setDouble(2, position.y);
statement.setDouble(3, position.z);
statement.setFloat(4, position.yaw);
statement.setFloat(5, position.pitch);
statement.setString(6, position.world.uuid.toString());
statement.setString(7, position.world.name);
statement.setString(8, position.server.name);
statement.setDouble(1, position.getX());
statement.setDouble(2, position.getY());
statement.setDouble(3, position.getZ());
statement.setFloat(4, position.getYaw());
statement.setFloat(5, position.getPitch());
statement.setString(6, position.getWorld().getUuid().toString());
statement.setString(7, position.getWorld().getName());
statement.setString(8, position.getServer().getName());
statement.setDouble(9, positionId);
statement.executeUpdate();
}
@@ -197,10 +197,10 @@ public class MySqlDatabase extends Database {
Statement.RETURN_GENERATED_KEYS)) {
statement.setInt(1, setPosition(position, connection));
statement.setString(2, position.meta.name);
statement.setString(3, position.meta.description);
statement.setString(4, position.meta.getSerializedTags());
statement.setTimestamp(5, Timestamp.from(position.meta.creationTime));
statement.setString(2, position.getMeta().getName());
statement.setString(3, position.getMeta().getDescription());
statement.setString(4, position.getMeta().getSerializedTags());
statement.setTimestamp(5, Timestamp.from(position.getMeta().getCreationTime()));
statement.executeUpdate();
final ResultSet resultSet = statement.getGeneratedKeys();
@@ -230,9 +230,9 @@ public class MySqlDatabase extends Database {
`description`=?,
`tags`=?
WHERE `id`=?;"""))) {
updateStatement.setString(1, position.meta.name);
updateStatement.setString(2, position.meta.description);
updateStatement.setString(3, position.meta.getSerializedTags());
updateStatement.setString(1, position.getMeta().getName());
updateStatement.setString(2, position.getMeta().getDescription());
updateStatement.setString(3, position.getMeta().getSerializedTags());
updateStatement.setInt(4, savedPositionId);
updateStatement.executeUpdate();
}
@@ -866,13 +866,13 @@ public class MySqlDatabase extends Database {
@Override
public void saveHome(@NotNull Home home) {
getHome(home.uuid).ifPresentOrElse(presentHome -> {
getHome(home.getUuid()).ifPresentOrElse(presentHome -> {
try (Connection connection = getConnection()) {
// Update the home's saved position, including metadata
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `saved_position_id` FROM `%homes_table%`
WHERE `uuid`=?;"""))) {
statement.setString(1, home.uuid.toString());
statement.setString(1, home.getUuid().toString());
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
@@ -885,41 +885,41 @@ public class MySqlDatabase extends Database {
UPDATE `%homes_table%`
SET `public`=?
WHERE `uuid`=?;"""))) {
statement.setBoolean(1, home.isPublic);
statement.setString(2, home.uuid.toString());
statement.setBoolean(1, home.isPublic());
statement.setString(2, home.getUuid().toString());
statement.executeUpdate();
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE,
"Failed to update a home in the database for " + home.owner.username, e);
"Failed to update a home in the database for " + home.getOwner().username, e);
}
}, () -> {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
INSERT INTO `%homes_table%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`)
VALUES (?,?,?,?);"""))) {
statement.setString(1, home.uuid.toString());
statement.setString(1, home.getUuid().toString());
statement.setInt(2, setSavedPosition(home, connection));
statement.setString(3, home.owner.uuid.toString());
statement.setBoolean(4, home.isPublic);
statement.setString(3, home.getOwner().uuid.toString());
statement.setBoolean(4, home.isPublic());
statement.executeUpdate();
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE,
"Failed to set a home to the database for " + home.owner.username, e);
"Failed to set a home to the database for " + home.getOwner().username, e);
}
});
}
@Override
public void saveWarp(@NotNull Warp warp) {
getWarp(warp.uuid).ifPresentOrElse(presentWarp -> {
getWarp(warp.getUuid()).ifPresentOrElse(presentWarp -> {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `saved_position_id` FROM `%warps_table%`
WHERE `uuid`=?;"""))) {
statement.setString(1, warp.uuid.toString());
statement.setString(1, warp.getUuid().toString());
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
@@ -934,7 +934,7 @@ public class MySqlDatabase extends Database {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
INSERT INTO `%warps_table%` (`uuid`, `saved_position_id`)
VALUES (?,?);"""))) {
statement.setString(1, warp.uuid.toString());
statement.setString(1, warp.getUuid().toString());
statement.setInt(2, setSavedPosition(warp, connection));
statement.executeUpdate();
@@ -137,14 +137,14 @@ public class SqLiteDatabase extends Database {
VALUES (?,?,?,?,?,?,?,?);"""),
Statement.RETURN_GENERATED_KEYS)) {
statement.setDouble(1, position.x);
statement.setDouble(2, position.y);
statement.setDouble(3, position.z);
statement.setFloat(4, position.yaw);
statement.setFloat(5, position.pitch);
statement.setString(6, position.world.name);
statement.setString(7, position.world.uuid.toString());
statement.setString(8, position.server.name);
statement.setDouble(1, position.getX());
statement.setDouble(2, position.getY());
statement.setDouble(3, position.getZ());
statement.setFloat(4, position.getYaw());
statement.setFloat(5, position.getPitch());
statement.setString(6, position.getWorld().getName());
statement.setString(7, position.getWorld().getUuid().toString());
statement.setString(8, position.getServer().getName());
statement.executeUpdate();
// Return the ID of the newly inserted row
@@ -170,14 +170,14 @@ public class SqLiteDatabase extends Database {
`world_name`=?,
`server_name`=?
WHERE `id`=?"""))) {
statement.setDouble(1, position.x);
statement.setDouble(2, position.y);
statement.setDouble(3, position.z);
statement.setFloat(4, position.yaw);
statement.setFloat(5, position.pitch);
statement.setString(6, position.world.uuid.toString());
statement.setString(7, position.world.name);
statement.setString(8, position.server.name);
statement.setDouble(1, position.getX());
statement.setDouble(2, position.getY());
statement.setDouble(3, position.getZ());
statement.setFloat(4, position.getYaw());
statement.setFloat(5, position.getPitch());
statement.setString(6, position.getWorld().getUuid().toString());
statement.setString(7, position.getWorld().getName());
statement.setString(8, position.getServer().getName());
statement.setDouble(9, positionId);
statement.executeUpdate();
}
@@ -191,10 +191,10 @@ public class SqLiteDatabase extends Database {
Statement.RETURN_GENERATED_KEYS)) {
statement.setInt(1, setPosition(position, connection));
statement.setString(2, position.meta.name);
statement.setString(3, position.meta.description);
statement.setString(4, position.meta.getSerializedTags());
statement.setTimestamp(5, Timestamp.from(position.meta.creationTime));
statement.setString(2, position.getMeta().getName());
statement.setString(3, position.getMeta().getDescription());
statement.setString(4, position.getMeta().getSerializedTags());
statement.setTimestamp(5, Timestamp.from(position.getMeta().getCreationTime()));
statement.executeUpdate();
// Return the ID of the newly inserted row
@@ -226,9 +226,9 @@ public class SqLiteDatabase extends Database {
`description`=?,
`tags`=?
WHERE `id`=?;"""))) {
updateStatement.setString(1, position.meta.name);
updateStatement.setString(2, position.meta.description);
updateStatement.setString(3, position.meta.getSerializedTags());
updateStatement.setString(1, position.getMeta().getName());
updateStatement.setString(2, position.getMeta().getDescription());
updateStatement.setString(3, position.getMeta().getSerializedTags());
updateStatement.setInt(4, savedPositionId);
updateStatement.executeUpdate();
}
@@ -855,13 +855,13 @@ public class SqLiteDatabase extends Database {
@Override
public void saveHome(@NotNull Home home) {
getHome(home.uuid).ifPresentOrElse(presentHome -> {
getHome(home.getUuid()).ifPresentOrElse(presentHome -> {
try {
// Update the home's saved position, including metadata
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `saved_position_id` FROM `%homes_table%`
WHERE `uuid`=?;"""))) {
statement.setString(1, home.uuid.toString());
statement.setString(1, home.getUuid().toString());
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
@@ -874,41 +874,41 @@ public class SqLiteDatabase extends Database {
UPDATE `%homes_table%`
SET `public`=?
WHERE `uuid`=?;"""))) {
statement.setBoolean(1, home.isPublic);
statement.setString(2, home.uuid.toString());
statement.setBoolean(1, home.isPublic());
statement.setString(2, home.getUuid().toString());
statement.executeUpdate();
}
} catch (SQLException e) {
getLogger().log(Level.SEVERE,
"Failed to update a home in the database for " + home.owner.username, e);
"Failed to update a home in the database for " + home.getOwner().username, e);
}
}, () -> {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
INSERT INTO `%homes_table%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`)
VALUES (?,?,?,?);"""))) {
statement.setString(1, home.uuid.toString());
statement.setString(1, home.getUuid().toString());
statement.setInt(2, setSavedPosition(home, connection));
statement.setString(3, home.owner.uuid.toString());
statement.setBoolean(4, home.isPublic);
statement.setString(3, home.getOwner().uuid.toString());
statement.setBoolean(4, home.isPublic());
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
getLogger().log(Level.SEVERE,
"Failed to set a home to the database for " + home.owner.username, e);
"Failed to set a home to the database for " + home.getOwner().username, e);
}
});
}
@Override
public void saveWarp(@NotNull Warp warp) {
getWarp(warp.uuid)
getWarp(warp.getUuid())
.ifPresentOrElse(presentWarp -> {
try {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `saved_position_id` FROM `%warps_table%`
WHERE `uuid`=?;"""))) {
statement.setString(1, warp.uuid.toString());
statement.setString(1, warp.getUuid().toString());
final ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
@@ -922,7 +922,7 @@ public class SqLiteDatabase extends Database {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
INSERT INTO `%warps_table%` (`uuid`, `saved_position_id`)
VALUES (?,?);"""))) {
statement.setString(1, warp.uuid.toString());
statement.setString(1, warp.getUuid().toString());
statement.setInt(2, setSavedPosition(warp, connection));
statement.executeUpdate();
@@ -35,9 +35,9 @@ public class BlueMapHook extends MapHook {
@Override
protected CompletableFuture<Void> initializeMap() {
final CompletableFuture<Void> initializedFuture = new CompletableFuture<>();
CompletableFuture.runAsync(() -> BlueMapAPI.onEnable(blueMapAPI -> {
plugin.runAsync(() -> BlueMapAPI.onEnable(blueMapAPI -> {
// Create marker sets
plugin.getWorlds().forEach(world -> blueMapAPI.getWorld(world.uuid)
plugin.getWorlds().forEach(world -> blueMapAPI.getWorld(world.getUuid())
.ifPresent(blueMapWorld -> blueMapWorld.getMaps().forEach(map -> {
if (plugin.getSettings().isPublicHomesOnMap()) {
map.getMarkerSets().put(blueMapWorld.getId() + ":" + PUBLIC_HOMES_MARKER_SET_ID,
@@ -71,13 +71,13 @@ public class BlueMapHook extends MapHook {
if (!isValidPosition(home)) return CompletableFuture.completedFuture(null);
return removeHome(home).thenRun(() -> BlueMapAPI.getInstance().flatMap(
blueMapAPI -> getBlueMapWorld(blueMapAPI, home.world)).ifPresent(blueMapWorld -> blueMapWorld.getMaps()
blueMapAPI -> getBlueMapWorld(blueMapAPI, home.getWorld())).ifPresent(blueMapWorld -> blueMapWorld.getMaps()
.forEach(blueMapMap -> blueMapMap.getMarkerSets()
.computeIfPresent(blueMapWorld.getId() + ":" + PUBLIC_HOMES_MARKER_SET_ID, (s, markerSet) -> {
markerSet.getMarkers().put(home.owner.uuid + ":" + home.uuid,
markerSet.getMarkers().put(home.getOwner().uuid + ":" + home.getUuid(),
POIMarker.toBuilder()
.label("/phome" + home.owner.username + "." + home.meta.name)
.position((int) home.x, (int) home.y, (int) home.z)
.label("/phome" + home.getOwner().username + "." + home.getMeta().getName())
.position((int) home.getX(), (int) home.getY(), (int) home.getZ())
.icon(publicHomeMarkerIconPath, Vector2i.from(25, 25))
.maxDistance(5000)
.build());
@@ -89,10 +89,10 @@ public class BlueMapHook extends MapHook {
public CompletableFuture<Void> removeHome(@NotNull Home home) {
if (!isValidPosition(home)) return CompletableFuture.completedFuture(null);
BlueMapAPI.getInstance().flatMap(blueMapAPI -> getBlueMapWorld(blueMapAPI, home.world))
BlueMapAPI.getInstance().flatMap(blueMapAPI -> getBlueMapWorld(blueMapAPI, home.getWorld()))
.ifPresent(blueMapWorld -> blueMapWorld.getMaps().forEach(blueMapMap -> blueMapMap.getMarkerSets()
.computeIfPresent(blueMapWorld.getId() + ":" + PUBLIC_HOMES_MARKER_SET_ID, (s, markerSet) -> {
markerSet.getMarkers().remove(home.owner.uuid + ":" + home.uuid);
markerSet.getMarkers().remove(home.getOwner().uuid + ":" + home.getUuid());
return markerSet;
})));
return CompletableFuture.completedFuture(null);
@@ -115,13 +115,13 @@ public class BlueMapHook extends MapHook {
public CompletableFuture<Void> updateWarp(@NotNull Warp warp) {
if (!isValidPosition(warp)) return CompletableFuture.completedFuture(null);
return removeWarp(warp).thenRun(() -> BlueMapAPI.getInstance().flatMap(blueMapAPI -> getBlueMapWorld(blueMapAPI, warp.world))
return removeWarp(warp).thenRun(() -> BlueMapAPI.getInstance().flatMap(blueMapAPI -> getBlueMapWorld(blueMapAPI, warp.getWorld()))
.ifPresent(blueMapWorld -> blueMapWorld.getMaps().forEach(blueMapMap -> blueMapMap.getMarkerSets()
.computeIfPresent(blueMapWorld.getId() + ":" + WARPS_MARKER_SET_ID, (s, markerSet) -> {
markerSet.getMarkers().put(warp.uuid.toString(),
markerSet.getMarkers().put(warp.getUuid().toString(),
POIMarker.toBuilder()
.label("/warp " + warp.meta.name)
.position((int) warp.x, (int) warp.y, (int) warp.z)
.label("/warp " + warp.getMeta().getName())
.position((int) warp.getX(), (int) warp.getY(), (int) warp.getZ())
.icon(warpMarkerIconPath, Vector2i.from(25, 25))
.maxDistance(10000)
.build());
@@ -133,10 +133,10 @@ public class BlueMapHook extends MapHook {
public CompletableFuture<Void> removeWarp(@NotNull Warp warp) {
if (!isValidPosition(warp)) return CompletableFuture.completedFuture(null);
BlueMapAPI.getInstance().flatMap(blueMapAPI -> getBlueMapWorld(blueMapAPI, warp.world))
BlueMapAPI.getInstance().flatMap(blueMapAPI -> getBlueMapWorld(blueMapAPI, warp.getWorld()))
.ifPresent(blueMapWorld -> blueMapWorld.getMaps().forEach(blueMapMap -> blueMapMap.getMarkerSets()
.computeIfPresent(blueMapWorld.getId() + ":" + WARPS_MARKER_SET_ID, (s, markerSet) -> {
markerSet.getMarkers().remove(warp.uuid.toString());
markerSet.getMarkers().remove(warp.getUuid().toString());
return markerSet;
})));
return CompletableFuture.completedFuture(null);
@@ -163,10 +163,10 @@ public class BlueMapHook extends MapHook {
*/
@NotNull
private Optional<BlueMapWorld> getBlueMapWorld(@NotNull BlueMapAPI blueMapAPI, @NotNull World world) {
if (world.uuid.equals(new UUID(0, 0))) {
return blueMapAPI.getWorld(world.name);
if (world.getUuid().equals(new UUID(0, 0))) {
return blueMapAPI.getWorld(world.getName());
} else {
return blueMapAPI.getWorld(world.uuid);
return blueMapAPI.getWorld(world.getUuid());
}
}
}
@@ -5,6 +5,7 @@ import net.william278.huskhomes.player.User;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.SavedPosition;
import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.position.World;
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.CompletableFuture;
@@ -104,11 +105,11 @@ public abstract class MapHook extends PluginHook {
if (position instanceof Home && !plugin.getSettings().isPublicHomesOnMap()) return false;
try {
return position.server.equals(plugin.getServerName());
return position.getServer().equals(plugin.getServerName());
} catch (IllegalStateException e) {
return plugin.getWorlds().stream()
.map(world -> world.uuid)
.anyMatch(uuid -> uuid.equals(position.world.uuid));
.map(World::getUuid)
.anyMatch(uuid -> uuid.equals(position.getWorld().getUuid()));
}
}
@@ -78,7 +78,7 @@ public class PlanDataExtension implements DataExtension {
public long getPublicHomeCount(@NotNull UUID uuid) {
return database.getUserData(uuid)
.map(userData -> database.getHomes(userData.user())
.stream().filter(home -> home.isPublic).count())
.stream().filter(home -> home.isPublic()).count())
.orElse(0L);
}
@@ -121,9 +121,9 @@ public class PlanDataExtension implements DataExtension {
public String getOfflinePosition(@NotNull UUID uuid) {
return database.getUserData(uuid)
.map(userData -> database.getOfflinePosition(userData.user())
.map(position -> "x: " + (int) position.x + ", y: " + (int) position.y + ", z: " + (int) position.z
+ " (" + position.world.name +
((crossServer) ? "/" + position.server.name + ")" : ")"))
.map(position -> "x: " + (int) position.getX() + ", y: " + (int) position.getY() + ", z: " + (int) position.getZ()
+ " (" + position.getWorld().getName() +
((crossServer) ? "/" + position.getServer().getName() + ")" : ")"))
.orElse(UNKNOWN_STRING))
.orElse(UNKNOWN_STRING);
}
@@ -3,6 +3,7 @@ package net.william278.huskhomes.listener;
import de.themoep.minedown.adventure.MineDown;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.player.OnlineUser;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportType;
@@ -10,9 +11,7 @@ import net.william278.huskhomes.util.Permission;
import org.jetbrains.annotations.NotNull;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
import java.util.stream.Collectors;
/**
* A handler for when events take place
@@ -32,77 +31,66 @@ public class EventListener {
* @param onlineUser the joining {@link OnlineUser}
*/
protected final void handlePlayerJoin(@NotNull OnlineUser onlineUser) {
// Handle the first player joining the server
plugin.getDatabase().ensureUser(onlineUser)
// Handle cross-server checks
.thenRun(() -> handleInboundTeleport(onlineUser).thenRun(() -> {
// Update the cached player list
plugin.getCache().updatePlayerListCache(plugin, onlineUser);
}).thenRun(() -> {
// Get this user's tp-ignore state and set locally
plugin.getDatabase().getUserData(onlineUser.uuid).thenAccept(userData -> {
if (userData.isPresent()) {
final boolean ignoringRequests = userData.get().ignoringTeleports();
plugin.getRequestManager().setIgnoringRequests(onlineUser, ignoringRequests);
plugin.runAsync(() -> {
// Ensure the user is in the database
plugin.getDatabase().ensureUser(onlineUser);
// Send a reminder message if they are still ignoring requests
if (ignoringRequests) {
plugin.getLocales().getRawLocale("tpignore_on_notification",
plugin.getLocales().getRawLocale("tpignore_toggle_button").orElse(""))
.ifPresent(locale -> onlineUser.sendMessage(new MineDown(locale)));
}
}
}).thenRun(() -> {
// Cache this user's homes
plugin.getDatabase()
.getHomes(onlineUser)
.thenAccept(homes -> plugin.getCache().homes.put(onlineUser.uuid, homes.stream()
.map(home -> home.meta.name)
.collect(Collectors.toList())));
});
}));
// Handle any inbound teleports
if (plugin.getSettings().isCrossServer()) {
this.handleInboundTeleport(onlineUser);
}
// Set their ignoring requests state
plugin.getDatabase().getUserData(onlineUser.uuid).ifPresent(userData -> {
final boolean ignoringRequests = userData.ignoringTeleports();
plugin.getRequestManager().setIgnoringRequests(onlineUser, ignoringRequests);
// Send a reminder message if they are still ignoring requests
if (ignoringRequests) {
plugin.getLocales().getRawLocale("tpignore_on_notification", plugin.getLocales()
.getRawLocale("tpignore_toggle_button")
.orElse("")).ifPresent(locale -> onlineUser.sendMessage(new MineDown(locale)));
}
});
// Cache this user's homes
plugin.getCache().getHomes().put(onlineUser.uuid, plugin.getDatabase()
.getHomes(onlineUser).stream()
.map(Home::getName)
.toList());
});
}
/**
* Handle inbound cross-server teleports
*
* @param onlineUser user to handle the checks for
* @return a future returning void when done
*/
private CompletableFuture<Void> handleInboundTeleport(@NotNull OnlineUser onlineUser) {
// If the server is in proxy mode, check if the player is teleporting cross-server and handle
if (plugin.getSettings().isCrossServer()) {
return plugin.getDatabase().getCurrentTeleport(onlineUser).thenAccept(teleport -> {
if (teleport.isEmpty()) {
return;
private void handleInboundTeleport(@NotNull OnlineUser onlineUser) {
plugin.getDatabase().getCurrentTeleport(onlineUser).ifPresent(teleport -> {
if (teleport.type == TeleportType.RESPAWN) {
final Optional<Position> bedPosition = onlineUser.getBedSpawnPosition();
if (bedPosition.isEmpty()) {
plugin.getLocalCachedSpawn()
.flatMap(spawn -> spawn.getPosition(plugin.getServerName()))
.ifPresent(position -> onlineUser.teleportLocally(position,
plugin.getSettings().isAsynchronousTeleports()));
onlineUser.sendTranslatableMessage("block.minecraft.spawn.not_valid");
} else {
onlineUser.teleportLocally(bedPosition.get(), plugin.getSettings().isAsynchronousTeleports());
}
// Handle cross-server respawn
if (teleport.get().type == TeleportType.RESPAWN) {
final Optional<Position> bedPosition = onlineUser.getBedSpawnPosition();
if (bedPosition.isEmpty()) {
plugin.getLocalCachedSpawn().flatMap(spawn -> spawn.getPosition(plugin.getServerName()))
.ifPresent(position -> onlineUser.teleportLocally(position, plugin.getSettings().isAsynchronousTeleports()));
onlineUser.sendTranslatableMessage("block.minecraft.spawn.not_valid");
} else {
onlineUser.teleportLocally(bedPosition.get(), plugin.getSettings().isAsynchronousTeleports());
}
plugin.getDatabase().setCurrentTeleport(onlineUser, null).thenRunAsync(() ->
plugin.getDatabase().setRespawnPosition(onlineUser, bedPosition.orElse(null)));
return;
}
// Teleport the player locally
teleport.get().execute()
.thenRun(() -> plugin.getDatabase().setCurrentTeleport(onlineUser, null))
.exceptionally(throwable -> {
plugin.getLoggingAdapter().log(Level.SEVERE,
"An error occurred while teleporting an inbound player", throwable);
return null;
});
});
}
return CompletableFuture.completedFuture(null);
plugin.getDatabase().setCurrentTeleport(onlineUser, null);
plugin.getDatabase().setRespawnPosition(onlineUser, bedPosition.orElse(null));
return;
}
teleport.execute()
.thenRun(() -> plugin.getDatabase().setCurrentTeleport(onlineUser, null))
.exceptionally(throwable -> {
plugin.getLoggingAdapter().log(Level.SEVERE,
"An error occurred while teleporting an inbound player", throwable);
return null;
});
});
}
/**
@@ -112,7 +100,7 @@ public class EventListener {
*/
protected final void handlePlayerLeave(@NotNull OnlineUser onlineUser) {
// Remove this user's home cache
plugin.getCache().homes.remove(onlineUser.uuid);
plugin.getCache().getHomes().remove(onlineUser.uuid);
// Update the cached player list using another online player if possible
plugin.getOnlinePlayers()
@@ -134,7 +122,7 @@ public class EventListener {
protected final void handlePlayerDeath(@NotNull OnlineUser onlineUser) {
// Set the player's last position to where they died
if (plugin.getSettings().isBackCommandReturnByDeath()
&& onlineUser.hasPermission(Permission.COMMAND_BACK_RETURN_BY_DEATH.node)) {
&& onlineUser.hasPermission(Permission.COMMAND_BACK_RETURN_BY_DEATH.node)) {
plugin.getDatabase().setLastPosition(onlineUser, onlineUser.getPosition());
}
}
@@ -145,26 +133,28 @@ public class EventListener {
* @param onlineUser the respawning {@link OnlineUser}
*/
protected final void handlePlayerRespawn(@NotNull OnlineUser onlineUser) {
// Display the return by death via /back notification
if (plugin.getSettings().isBackCommandReturnByDeath()
&& onlineUser.hasPermission(Permission.COMMAND_BACK.node)
&& onlineUser.hasPermission(Permission.COMMAND_BACK_RETURN_BY_DEATH.node)) {
plugin.getLocales().getLocale("return_by_death_notification")
.ifPresent(onlineUser::sendMessage);
}
plugin.runAsync(() -> {
// Display the return by death via /back notification
if (plugin.getSettings().isBackCommandReturnByDeath()
&& onlineUser.hasPermission(Permission.COMMAND_BACK.node)
&& onlineUser.hasPermission(Permission.COMMAND_BACK_RETURN_BY_DEATH.node)) {
plugin.getLocales().getLocale("return_by_death_notification")
.ifPresent(onlineUser::sendMessage);
}
// Respawn the player cross-server if needed
if (plugin.getSettings().isCrossServer() && plugin.getSettings().isGlobalRespawning()) {
plugin.getDatabase().getRespawnPosition(onlineUser).thenAccept(position -> position.ifPresent(respawnPosition -> {
if (!respawnPosition.server.equals(plugin.getServerName())) {
Teleport.builder(plugin, onlineUser)
.setType(TeleportType.RESPAWN)
.setTarget(respawnPosition)
.toTeleport()
.thenAccept(Teleport::execute);
}
}));
}
// Respawn the player cross-server if needed
if (plugin.getSettings().isCrossServer() && plugin.getSettings().isGlobalRespawning()) {
plugin.getDatabase().getRespawnPosition(onlineUser).ifPresent(respawnPosition -> {
if (!respawnPosition.getServer().equals(plugin.getServerName())) {
Teleport.builder(plugin, onlineUser)
.setType(TeleportType.RESPAWN)
.setTarget(respawnPosition)
.toTeleport()
.thenAccept(Teleport::execute);
}
});
}
});
}
/**
@@ -174,11 +164,12 @@ public class EventListener {
* @param sourcePosition the source {@link Position} they came from
*/
protected final void handlePlayerTeleport(@NotNull OnlineUser onlineUser, @NotNull Position sourcePosition) {
if (!plugin.getSettings().isBackCommandSaveOnTeleportEvent()) return;
if (!plugin.getSettings().isBackCommandSaveOnTeleportEvent()) {
return;
}
plugin.getDatabase().getUserData(onlineUser.uuid)
.thenAccept(userData -> userData.ifPresent(data -> plugin.getDatabase()
.setLastPosition(data.user(), sourcePosition)));
plugin.runAsync(() -> plugin.getDatabase().getUserData(onlineUser.uuid)
.ifPresent(data -> plugin.getDatabase().setLastPosition(data.user(), sourcePosition)));
}
/**
@@ -29,13 +29,13 @@ public class HomesManager {
final Home home = existingHome
.map(existing -> {
existing.x = position.x;
existing.y = position.y;
existing.z = position.z;
existing.world = position.world;
existing.server = position.server;
existing.yaw = position.yaw;
existing.pitch = position.pitch;
existing.setX(position.getX());
existing.setY(position.getY());
existing.setZ(position.getZ());
existing.setWorld(position.getWorld());
existing.setServer(position.getServer());
existing.setYaw(position.getYaw());
existing.setPitch(position.getPitch());
return existing;
})
.orElse(new Home(position, new PositionMeta(name, ""), owner));
@@ -47,7 +47,7 @@ public class HomesManager {
if (home.isEmpty()) {
throw new ValidationException(ValidationException.ValidationError.NOT_FOUND);
}
plugin.getDatabase().deleteHome(home.get().uuid);
plugin.getDatabase().deleteHome(home.get().getUuid());
}
public void relocateHome(@NotNull User owner, @NotNull String name, @NotNull Position position) throws ValidationException {
@@ -65,7 +65,7 @@ public class HomesManager {
}
final Home home = optionalHome.get();
home.meta.name = newName;
home.getMeta().setName(newName);
plugin.getDatabase().saveHome(home);
}
@@ -80,7 +80,7 @@ public class HomesManager {
}
final Home home = optionalHome.get();
home.meta.description = description;
home.getMeta().setDescription(description);
plugin.getDatabase().saveHome(home);
}
@@ -91,7 +91,7 @@ public class HomesManager {
}
final Home home = optionalHome.get();
home.isPublic = isPublic;
home.setPublic(isPublic);
plugin.getDatabase().saveHome(home);
}
@@ -2,8 +2,6 @@ package net.william278.huskhomes.manager;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.ValidationException;
import net.william278.huskhomes.player.User;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.PositionMeta;
import net.william278.huskhomes.position.Warp;
@@ -29,13 +27,13 @@ public class WarpsManager {
final Warp warp = existingWarp
.map(existing -> {
existing.x = position.x;
existing.y = position.y;
existing.z = position.z;
existing.world = position.world;
existing.server = position.server;
existing.yaw = position.yaw;
existing.pitch = position.pitch;
existing.setX(position.getX());
existing.setY(position.getY());
existing.setZ(position.getZ());
existing.setWorld(position.getWorld());
existing.setServer(position.getServer());
existing.setYaw(position.getYaw());
existing.setPitch(position.getPitch());
return existing;
})
.orElse(new Warp(position, new PositionMeta(name, "")));
@@ -47,7 +45,7 @@ public class WarpsManager {
if (warp.isEmpty()) {
throw new ValidationException(ValidationException.ValidationError.NOT_FOUND);
}
plugin.getDatabase().deleteWarp(warp.get().uuid);
plugin.getDatabase().deleteWarp(warp.get().getUuid());
}
public void relocateWarp(@NotNull String name, @NotNull Position position) {
@@ -65,7 +63,7 @@ public class WarpsManager {
}
final Warp warp = optionalWarp.get();
warp.meta.name = newName;
warp.getMeta().setName(newName);
plugin.getDatabase().saveWarp(warp);
}
@@ -76,7 +74,7 @@ public class WarpsManager {
}
final Warp warp = optionalWarp.get();
warp.meta.description = description;
warp.getMeta().setDescription(description);
plugin.getDatabase().saveWarp(warp);
}
@@ -57,7 +57,7 @@ public abstract class OnlineUser extends User {
* @param node The permission node string
* @return {@code true} if the player has the node; {@code false} otherwise
*/
public abstract boolean hasPermission(@NotNull @Pattern(Permission.PERMISSION_PATTERN) String node);
public abstract boolean hasPermission(@NotNull String node);
/**
* Returns a {@link Map} of a player's permission nodes
@@ -10,16 +10,8 @@ import java.util.UUID;
*/
public class Home extends SavedPosition {
/**
* The {@link User} who owns this home
*/
@NotNull
public final User owner;
/**
* {@code true} if this home is public
*/
public boolean isPublic;
private final User owner;
private boolean isPublic;
public Home(double x, double y, double z, float yaw, float pitch,
@NotNull World world, @NotNull Server server,
@@ -27,13 +19,31 @@ public class Home extends SavedPosition {
@NotNull User owner, boolean isPublic) {
super(x, y, z, yaw, pitch, world, server, positionMeta, uuid);
this.owner = owner;
this.isPublic = isPublic;
this.setPublic(isPublic);
}
public Home(@NotNull Position position, @NotNull PositionMeta meta, @NotNull User owner) {
super(position, meta);
this.owner = owner;
this.isPublic = false;
this.setPublic(false);
}
/**
* The {@link User} who owns this home
*/
@NotNull
public User getOwner() {
return owner;
}
/**
* {@code true} if this home is public
*/
public boolean isPublic() {
return isPublic;
}
public void setPublic(boolean aPublic) {
isPublic = aPublic;
}
}
@@ -7,56 +7,98 @@ import org.jetbrains.annotations.NotNull;
*/
public class Location {
/**
* The double-precision defined x coordinate of the location
*/
public double x;
/**
* The double-precision defined y coordinate of the location
*/
public double y;
/**
* The double-precision defined z coordinate of the location
*/
public double z;
/**
* The float-precision defined yaw facing of the location
*/
public float yaw;
/**
* The float-precision defined pitch facing of the location
*/
public float pitch;
/**
* The {@link World} the location is on
*/
public World world;
private double x;
private double y;
private double z;
private float yaw;
private float pitch;
private World world;
public Location(double x, double y, double z, @NotNull World world) {
this.x = x;
this.y = y;
this.z = z;
this.yaw = 0;
this.pitch = 0;
this.world = world;
this.setX(x);
this.setY(y);
this.setZ(z);
this.setYaw(0);
this.setPitch(0);
this.setWorld(world);
}
public Location(double x, double y, double z, float yaw, float pitch,
@NotNull World world) {
this.x = x;
this.y = y;
this.z = z;
this.yaw = yaw;
this.pitch = pitch;
this.world = world;
this.setX(x);
this.setY(y);
this.setZ(z);
this.setYaw(yaw);
this.setPitch(pitch);
this.setWorld(world);
}
public Location() {
}
/**
* The double-precision defined x coordinate of the location
*/
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
/**
* The double-precision defined y coordinate of the location
*/
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
/**
* The double-precision defined z coordinate of the location
*/
public double getZ() {
return z;
}
public void setZ(double z) {
this.z = z;
}
/**
* The float-precision defined yaw facing of the location
*/
public float getYaw() {
return yaw;
}
public void setYaw(float yaw) {
this.yaw = yaw;
}
/**
* The float-precision defined pitch facing of the location
*/
public float getPitch() {
return pitch;
}
public void setPitch(float pitch) {
this.pitch = pitch;
}
/**
* The {@link World} the location is on
*/
public World getWorld() {
return world;
}
public void setWorld(World world) {
this.world = world;
}
}
@@ -10,24 +10,21 @@ import java.util.UUID;
*/
public class Position extends Location {
/**
* The {@link Server} the position is on
*/
public Server server;
private Server server;
public Position(double x, double y, double z, float yaw, float pitch,
@NotNull World world, @NotNull Server server) {
super(x, y, z, yaw, pitch, world);
this.server = server;
this.setServer(server);
}
public Position(@NotNull Location location, @NotNull Server server) {
super(location.x, location.y, location.z, location.yaw, location.pitch, location.world);
this.server = server;
super(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch(), location.getWorld());
this.setServer(server);
}
@SuppressWarnings("unused")
public Position() {
private Position() {
}
/**
@@ -36,13 +33,13 @@ public class Position extends Location {
* @param newPosition The position to update to
*/
public void update(@NotNull Position newPosition) {
this.x = newPosition.x;
this.y = newPosition.y;
this.z = newPosition.z;
this.yaw = newPosition.yaw;
this.pitch = newPosition.pitch;
this.world = newPosition.world;
this.server = newPosition.server;
this.setX(newPosition.getX());
this.setY(newPosition.getY());
this.setZ(newPosition.getZ());
this.setYaw(newPosition.getYaw());
this.setPitch(newPosition.getPitch());
this.setWorld(newPosition.getWorld());
this.setServer(newPosition.getServer());
}
/**
@@ -60,12 +57,12 @@ public class Position extends Location {
// Parse, handle relatives, and return, catching NumberFormatExceptions and returning an empty optional
try {
final double x = parseCoordinate(args[0], relativeTo.x);
final double y = parseCoordinate(args[1], relativeTo.y);
final double z = parseCoordinate(args[2], relativeTo.z);
final World world = args.length > 3 ? new World(args[3], UUID.randomUUID()) : relativeTo.world;
final Server server = args.length > 4 ? new Server(args[4]) : relativeTo.server;
return Optional.of(new Position(x, y, z, relativeTo.yaw, relativeTo.pitch, world, server));
final double x = parseCoordinate(args[0], relativeTo.getX());
final double y = parseCoordinate(args[1], relativeTo.getY());
final double z = parseCoordinate(args[2], relativeTo.getZ());
final World world = args.length > 3 ? new World(args[3], UUID.randomUUID()) : relativeTo.getWorld();
final Server server = args.length > 4 ? new Server(args[4]) : relativeTo.getServer();
return Optional.of(new Position(x, y, z, relativeTo.getYaw(), relativeTo.getPitch(), world, server));
} catch (NumberFormatException ignored) {
return Optional.empty();
}
@@ -91,4 +88,15 @@ public class Position extends Location {
return Double.parseDouble(value);
}
}
/**
* The {@link Server} the position is on
*/
public Server getServer() {
return server;
}
public void setServer(Server server) {
this.server = server;
}
}
@@ -8,49 +8,32 @@ import org.jetbrains.annotations.Nullable;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/**
* Represents metadata about a {@link Position}, used in {@link SavedPosition} implementations
*/
public class PositionMeta {
/**
* The name of a position
*/
@NotNull
public String name;
/**
* A description of a position
*/
@NotNull
public String description;
/**
* Map of metadata tags for a position
*/
@NotNull
public Map<String, String> tags;
/**
* The time the position was created
*/
@NotNull
public Instant creationTime;
private String name;
@Nullable
private String description;
private Map<String, String> tags;
private Instant creationTime;
public PositionMeta(@NotNull String name, @NotNull String description, @NotNull Instant creationTime,
@Nullable String serializedTags) {
this.name = name;
this.description = description;
this.creationTime = creationTime;
this.tags = deserializeTags(serializedTags);
this.setName(name);
this.setDescription(description);
this.setCreationTime(creationTime);
this.setTags(deserializeTags(serializedTags));
}
public PositionMeta(@NotNull String name, @NotNull String description) {
this.name = name;
this.description = description;
this.creationTime = Instant.now();
this.tags = new HashMap<>();
this.setName(name);
this.setDescription(description);
this.setCreationTime(Instant.now());
this.setTags(new HashMap<>());
}
/**
@@ -80,14 +63,59 @@ public class PositionMeta {
@Nullable
public String getSerializedTags() {
try {
if (tags.isEmpty()) {
if (getTags().isEmpty()) {
return null;
}
return new Gson().toJson(tags);
return new Gson().toJson(getTags());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* The name of a position
*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* A description of a position
*/
@NotNull
public String getDescription() {
return Optional.ofNullable(description).orElse("");
}
public void setDescription(@Nullable String description) {
this.description = description;
}
/**
* Map of metadata tags for a position
*/
public Map<String, String> getTags() {
return tags;
}
public void setTags(Map<String, String> tags) {
this.tags = tags;
}
/**
* The time the position was created
*/
@NotNull
public Instant getCreationTime() {
return creationTime;
}
public void setCreationTime(Instant creationTime) {
this.creationTime = creationTime;
}
}
@@ -9,23 +9,14 @@ import java.util.UUID;
*/
public abstract class SavedPosition extends Position implements Comparable<SavedPosition> {
/**
* Metadata about this position (name, description)
*/
@NotNull
public PositionMeta meta;
/**
* A unique ID representing this position
*/
@NotNull
public final UUID uuid;
private PositionMeta meta;
private final UUID uuid;
protected SavedPosition(double x, double y, double z, float yaw, float pitch,
@NotNull World world, @NotNull Server server,
@NotNull PositionMeta meta, @NotNull UUID uuid) {
super(x, y, z, yaw, pitch, world, server);
this.meta = meta;
this.setMeta(meta);
this.uuid = uuid;
}
@@ -36,15 +27,43 @@ public abstract class SavedPosition extends Position implements Comparable<Saved
* @param meta {@link PositionMeta} information about this position
*/
protected SavedPosition(@NotNull Position position, @NotNull PositionMeta meta) {
super(position.x, position.y, position.z, position.yaw, position.pitch,
position.world, position.server);
this.meta = meta;
super(position.getX(), position.getY(), position.getZ(), position.getYaw(), position.getPitch(),
position.getWorld(), position.getServer());
this.setMeta(meta);
this.uuid = UUID.randomUUID();
}
// Compare based on names for alphabetical sorting
@Override
public int compareTo(@NotNull SavedPosition o) {
return this.meta.name.compareTo(o.meta.name);
return this.getMeta().getName().compareTo(o.getMeta().getName());
}
/**
* Metadata about this position (name, description)
*/
@NotNull
public PositionMeta getMeta() {
return meta;
}
public void setMeta(@NotNull PositionMeta meta) {
this.meta = meta;
}
/**
* The name of this position. Shortcut for {@link #getMeta()}.{@link PositionMeta#getName()}
*/
@NotNull
public String getName() {
return getMeta().getName();
}
/**
* A unique ID representing this position
*/
@NotNull
public UUID getUuid() {
return uuid;
}
}
@@ -17,27 +17,25 @@ import java.nio.file.Path;
public class Server {
/**
* Default (unknown) server identifier
* Default server identifier
*/
@NotNull
public static Server getDefault() {
final Server server = new Server();
try {
final Path serverDirectory = Path.of(System.getProperty("user.dir"));
server.name = serverDirectory.getFileName().toString().trim();
server.setName(serverDirectory.getFileName().toString().trim());
} catch (Exception e) {
server.name = "server";
server.setName("server");
}
return server;
}
/**
* Proxy-defined name of this server
*/
@YamlKey("server_name")
public String name = getDefault().name;
private String name = getDefault().getName();
public Server(@NotNull String name) {
this.name = name;
this.setName(name);
}
private Server() {
@@ -47,9 +45,20 @@ public class Server {
public boolean equals(@NotNull Object other) {
// If the name of this server matches another, the servers are the same.
if (other instanceof Server server) {
return server.name.equalsIgnoreCase(this.name);
return server.getName().equalsIgnoreCase(this.getName());
}
return super.equals(other);
}
/**
* Proxy-defined name of this server
*/
@NotNull
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -48,7 +48,7 @@ public class Warp extends SavedPosition {
* @return true if the user has permission to teleport to this warp
*/
public boolean hasPermission(boolean restrictWarps, @NotNull OnlineUser user) {
return hasPermission(restrictWarps, user, meta.name);
return hasPermission(restrictWarps, user, getMeta().getName());
}
/**
@@ -3,6 +3,7 @@ package net.william278.huskhomes.position;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Optional;
import java.util.UUID;
/**
@@ -10,38 +11,62 @@ import java.util.UUID;
*/
public class World {
private String name;
private UUID uuid;
@Nullable
private Environment environment;
public World(@NotNull String name, @NotNull UUID uuid) {
this.setName(name);
this.setUuid(uuid);
}
public World(@NotNull String name, @NotNull UUID uuid, @Nullable Environment environment) {
this.setName(name);
this.setUuid(uuid);
this.setEnvironment(environment);
}
@SuppressWarnings("unused")
public World() {
}
/**
* The name of this world, as defined by the world directory name
*/
public String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* UUID of this world, as defined by the {@code uid.dat} file in the world directory
*/
public UUID uuid;
@NotNull
public UUID getUuid() {
return uuid;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
/**
* Environment of the world ({@link Environment#OVERWORLD}, {@link Environment#NETHER}, {@link Environment#THE_END},
* or {@link Environment#CUSTOM})
*/
@Nullable
public Environment environment;
public World(@NotNull String name, @NotNull UUID uuid) {
this.name = name;
this.uuid = uuid;
@NotNull
public Environment getEnvironment() {
return Optional.ofNullable(environment).orElse(Environment.OVERWORLD);
}
public World(@NotNull String name, @NotNull UUID uuid, @Nullable Environment environment) {
this.name = name;
this.uuid = uuid;
public void setEnvironment(@Nullable Environment environment) {
this.environment = environment;
}
@SuppressWarnings("unused")
public World() {
}
/**
* Identifies the environment of the world
*/
@@ -55,7 +80,7 @@ public class World {
@Override
public boolean equals(@NotNull Object obj) {
if (obj instanceof World world) {
return world.uuid.equals(uuid);
return world.getUuid().equals(getUuid());
}
return super.equals(obj);
}
@@ -46,7 +46,7 @@ public class NormalDistributionEngine extends RandomTeleportEngine {
final float z = (float) (radius * Math.cos(angle));
final float x = (float) (radius * Math.sin(angle));
return new Location(Math.round(origin.x) + x, 128d, Math.round(origin.z) + z, origin.world);
return new Location(Math.round(origin.getX()) + x, 128d, Math.round(origin.getZ()) + z, origin.getWorld());
}
/**
@@ -85,7 +85,7 @@ public class NormalDistributionEngine extends RandomTeleportEngine {
}
@Override
protected Optional<Position> getRandomPosition(@NotNull World world, @NotNull String[] args) {
public Optional<Position> getRandomPosition(@NotNull World world, @NotNull String[] args) {
Optional<Location> location = generateSafeLocation(world).join();
int attempts = 0;
while (location.isEmpty()) {
@@ -6,7 +6,6 @@ import net.william278.huskhomes.position.World;
import org.jetbrains.annotations.NotNull;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
/**
* Represents an engine for generating random position targets
@@ -46,7 +45,7 @@ public abstract class RandomTeleportEngine {
protected final Position getOrigin(@NotNull World world) {
return plugin.getLocalCachedSpawn()
.flatMap(spawn -> {
if (!spawn.worldUuid.equals(world.uuid.toString())) {
if (!spawn.worldUuid.equals(world.getUuid().toString())) {
return Optional.empty();
}
return spawn.getPosition(plugin.getServerName());
@@ -178,27 +178,24 @@ public class Teleport {
}
// If the target position is local, finalize economy transactions and teleport the player
if (!plugin.getSettings().isCrossServer() || target.server.equals(plugin.getServerName())) {
if (!plugin.getSettings().isCrossServer() || target.getServer().equals(plugin.getServerName())) {
return teleporter.teleportLocally(target, plugin.getSettings().isAsynchronousTeleports());
}
// If the target position is on another server, execute a cross-server teleport
final CompletableFuture<TeleportResult> teleportFuture = new CompletableFuture<>();
plugin.getDatabase()
.setCurrentTeleport(teleporter, this)
.thenApply(ignored -> plugin
.getMessenger()
.sendPlayer(teleporter, target.server)
.thenApply(completed -> completed
? TeleportResult.COMPLETED_CROSS_SERVER
: TeleportResult.FAILED_INVALID_SERVER))
plugin.getDatabase().setCurrentTeleport(teleporter, this);
plugin.getMessenger()
.sendPlayer(teleporter, target.getServer())
.thenApply(completed -> completed
? TeleportResult.COMPLETED_CROSS_SERVER
: TeleportResult.FAILED_INVALID_SERVER)
.orTimeout(10, TimeUnit.SECONDS)
.exceptionally(throwable -> {
plugin.getLoggingAdapter().log(Level.WARNING, "Cross-server teleport timed out for " + teleporter.username);
plugin.getDatabase().setCurrentTeleport(teleporter, null);
return CompletableFuture.completedFuture(TeleportResult.FAILED_INVALID_SERVER);
})
.thenAccept(result -> result.thenAcceptAsync(teleportFuture::complete));
return TeleportResult.FAILED_INVALID_SERVER;
});
return teleportFuture;
}
@@ -53,7 +53,7 @@ public class TimedTeleport extends Teleport {
}
// Check if the teleporter is already warming up to teleport
if (plugin.getCache().currentlyOnWarmup.contains(teleporter.uuid)) {
if (plugin.getCache().getCurrentlyOnWarmup().contains(teleporter.uuid)) {
return CompletableFuture.completedFuture(TeleportResult.FAILED_ALREADY_TELEPORTING)
.thenApply(resultState -> CompletedTeleport.from(resultState, this));
}
@@ -98,7 +98,7 @@ public class TimedTeleport extends Teleport {
}
// Mark the player as warming up and display the message
plugin.getCache().currentlyOnWarmup.add(teleporter.uuid);
plugin.getCache().getCurrentlyOnWarmup().add(teleporter.uuid);
plugin.getLocales().getLocale("teleporting_warmup_start", Integer.toString(timeLeft))
.ifPresent(teleporter::sendMessage);
@@ -118,7 +118,7 @@ public class TimedTeleport extends Teleport {
// Tick (decrement) the timed teleport timer and end it if done
if (tickWarmup()) {
plugin.getCache().currentlyOnWarmup.remove(teleporter.uuid);
plugin.getCache().getCurrentlyOnWarmup().remove(teleporter.uuid);
timedTeleportFuture.complete(null);
executor.shutdown();
}
@@ -195,9 +195,9 @@ public class TimedTeleport extends Teleport {
*/
private boolean hasTeleporterMoved() {
final double maxMovementDistance = 0.1d;
double movementDistance = Math.abs(startLocation.x - teleporter.getPosition().x) +
Math.abs(startLocation.y - teleporter.getPosition().y) +
Math.abs(startLocation.z - teleporter.getPosition().z);
double movementDistance = Math.abs(startLocation.getX() - teleporter.getPosition().getX()) +
Math.abs(startLocation.getY() - teleporter.getPosition().getY()) +
Math.abs(startLocation.getZ() - teleporter.getPosition().getZ());
return movementDistance > maxMovementDistance;
}
@@ -43,8 +43,8 @@ public class RequestTests {
Assertions.assertNotNull(readRequest.getPayload().position);
assert readRequest.getPayload().position != null && DUMMY_PAYLOAD.getPayload().position != null;
Assertions.assertEquals(DUMMY_PAYLOAD.getPayload().position.x, readRequest.getPayload().position.x);
Assertions.assertEquals(DUMMY_PAYLOAD.getPayload().position.y, readRequest.getPayload().position.y);
Assertions.assertEquals(DUMMY_PAYLOAD.getPayload().position.z, readRequest.getPayload().position.z);
Assertions.assertEquals(DUMMY_PAYLOAD.getPayload().position.getX(), readRequest.getPayload().position.getX());
Assertions.assertEquals(DUMMY_PAYLOAD.getPayload().position.getY(), readRequest.getPayload().position.getY());
Assertions.assertEquals(DUMMY_PAYLOAD.getPayload().position.getZ(), readRequest.getPayload().position.getZ());
}
}
@@ -25,8 +25,8 @@ public class NormalDistributionTests {
final double[] xValues = new double[locations.size()];
final double[] zValues = new double[locations.size()];
for (int i = 0; i < locations.size(); i++) {
xValues[i] = locations.get(i).x;
zValues[i] = locations.get(i).z;
xValues[i] = locations.get(i).getX();
zValues[i] = locations.get(i).getZ();
}
final Plot plot = Plot.plot(Plot.plotOpts()
.title("RTP Normal Distribution demo")