Add fabric builds for older MC versions & add checkstyle (#449)

* Remove instance getters, improve command logic, register APi

* Publish multiple fabric builds, enforce checkstyle

* Bump guava

* Bump to 4.4.2
This commit is contained in:
William authored and GitHub committed 2023-07-02 13:26:12 +01:00
1 parent 51baf196b3
commit c9f5262292
219 files changed
+8032 -1392

No files matched your search

@@ -61,17 +61,25 @@ import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Represents a cross-platform instance of the plugin
* Represents a cross-platform instance of the plugin.
*/
public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolver, TransactionResolver {
/**
* The spigot resource ID, used for update checking.
*/
int SPIGOT_RESOURCE_ID = 83767;
/**
* Get the user representing the server console.
*
* @return the {@link ConsoleUser}
*/
@NotNull
ConsoleUser getConsole();
/**
* The {@link Set} of online {@link OnlineUser}s on this server
* The {@link Set} of online {@link OnlineUser}s on this server.
*
* @return a {@link Set} of currently online {@link OnlineUser}s
*/
@@ -121,7 +129,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
}
/**
* Initialize a faucet of the plugin
* Initialize a faucet of the plugin.
*
* @param name the name of the faucet
* @param runner a runnable for initializing the faucet
@@ -137,7 +145,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
}
/**
* The plugin {@link Settings} loaded from file
* The plugin {@link Settings} loaded from file.
*
* @return the plugin {@link Settings}
*/
@@ -147,7 +155,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
void setSettings(@NotNull Settings settings);
/**
* The plugin messages loaded from file
* The plugin messages loaded from file.
*
* @return The plugin {@link Locales}
*/
@@ -157,17 +165,29 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
void setLocales(@NotNull Locales locales);
/**
* The local {@link Spawn} location of this server, as cached to disk
* The local {@link Spawn} location of this server, as cached to disk.
*
* @return the {@link Spawn} location data
* @see #getSpawn() for the canonical spawn point to use
*/
Optional<Spawn> getServerSpawn();
/**
* Update the local {@link Spawn} config file.
*
* @param spawn the new {@link Spawn} data
*/
void setServerSpawn(@NotNull Spawn spawn);
/**
* The canonical spawn {@link Position} of this server, if it has been set
* Update the {@link Spawn} position to a location on the server.
*
* @param location the new {@link Spawn} location
*/
void setServerSpawn(@NotNull Location location);
/**
* The canonical spawn {@link Position} of this server, if it has been set.
*
* @return the {@link Position} of the spawn, or an empty {@link Optional} if it has not been set
*/
@@ -178,7 +198,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
}
/**
* Returns the {@link Server} the plugin is on
* Returns the {@link Server} the plugin is on.
*
* @return The {@link Server} object
*/
@@ -193,7 +213,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
UnsafeBlocks getUnsafeBlocks();
/**
* The {@link Database} that store persistent plugin data
* The {@link Database} that store persistent plugin data.
*
* @return the {@link Database} implementation for accessing data
*/
@@ -201,7 +221,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
Database getDatabase();
/**
* The {@link Validator} for validating home names and descriptions
* The {@link Validator} for validating home names and descriptions.
*
* @return the {@link Validator} instance
*/
@@ -209,7 +229,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
Validator getValidator();
/**
* The {@link Manager} that manages home, warp and user data
* The {@link Manager} that manages home, warp and user data.
*
* @return the {@link Manager} implementation
*/
@@ -217,7 +237,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
Manager getManager();
/**
* The {@link Broker} that sends cross-network messages
* The {@link Broker} that sends cross-network messages.
*
* @return the {@link Broker} implementation
*/
@@ -225,7 +245,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
Broker getMessenger();
/**
* The {@link RandomTeleportEngine} that manages random teleports
* The {@link RandomTeleportEngine} that manages random teleports.
*
* @return the {@link RandomTeleportEngine} implementation
*/
@@ -233,22 +253,14 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
RandomTeleportEngine getRandomTeleportEngine();
/**
* Sets the {@link RandomTeleportEngine} to be used for processing random teleports
* Sets the {@link RandomTeleportEngine} to be used for processing random teleports.
*
* @param randomTeleportEngine the {@link RandomTeleportEngine} to use
*/
void setRandomTeleportEngine(@NotNull RandomTeleportEngine randomTeleportEngine);
/**
* Update the {@link Spawn} position to a location on the server
*
* @param location the new {@link Spawn} location
*/
void setServerSpawn(@NotNull Location location);
/**
* Set of active {@link Hook}s running on the server
* Set of active {@link Hook}s running on the server.
*
* @return the {@link Set} of active {@link Hook}s
*/
@@ -277,7 +289,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
}
/**
* Returns a resource read from the plugin resources folder
* Returns a resource read from the plugin resources folder.
*
* @param name the name of the resource
* @return the resource read as an {@link InputStream}
@@ -286,7 +298,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
InputStream getResource(@NotNull String name);
/**
* Returns the plugin data folder containing the plugin config, etc
* Returns the plugin data folder containing the plugin config, etc.
*
* @return the plugin data folder
*/
@@ -294,7 +306,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
File getDataFolder();
/**
* Returns a list of worlds on the server
* Returns a list of worlds on the server.
*
* @return a list of worlds on the server
*/
@@ -302,7 +314,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
List<World> getWorlds();
/**
* Returns the plugin version
* Returns the plugin version.
*
* @return the plugin {@link Version}
*/
@@ -310,7 +322,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
Version getVersion();
/**
* Returns a list of enabled commands
* Returns a list of enabled commands.
*
* @return A list of registered and enabled {@link Command}s
*/
@@ -396,7 +408,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
}
/**
* Reloads the {@link Settings} and {@link Locales} from their respective config files
* Reloads the {@link Settings} and {@link Locales} from their respective config files.
*
* @return {@code true} if the reload was successful, {@code false} otherwise
*/
@@ -407,8 +419,14 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
setSettings(Annotaml.create(new File(getDataFolder(), "config.yml"), Settings.class).get());
// Load locales from language preset default
final Locales languagePresets = Annotaml.create(Locales.class, Objects.requireNonNull(getResource("locales/" + getSettings().getLanguage() + ".yml"))).get();
setLocales(Annotaml.create(new File(getDataFolder(), "messages_" + getSettings().getLanguage() + ".yml"), languagePresets).get());
final Locales languagePresets = Annotaml.create(
Locales.class,
Objects.requireNonNull(getResource("locales/" + getSettings().getLanguage() + ".yml"))
).get();
setLocales(Annotaml.create(new File(
getDataFolder(),
"messages_" + getSettings().getLanguage() + ".yml"
), languagePresets).get());
// Load server from file
if (getSettings().doCrossServer()) {
@@ -448,26 +466,26 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
getUpdateChecker().check().thenAccept(checked -> {
if (!checked.isUpToDate()) {
log(Level.WARNING, "A new version of HuskHomes is available: v"
+ checked.getLatestVersion() + " (running v" + getVersion() + ")");
+ checked.getLatestVersion() + " (running v" + getVersion() + ")");
}
});
}
}
/**
* Registers the plugin with bStats metrics
* Registers the plugin with bStats metrics.
*
* @param metricsId the bStats id for the plugin
*/
void registerMetrics(int metricsId);
/**
* Initialize plugin messaging channels
* Initialize plugin messaging channels.
*/
void initializePluginChannels();
/**
* Log a message to the console
* Log a message to the console.
*
* @param level the level to log at
* @param message the message to log
@@ -476,7 +494,7 @@ public interface HuskHomes extends Task.Supplier, EventDispatcher, SafetyResolve
void log(@NotNull Level level, @NotNull String message, Throwable... exceptions);
/**
* Create a resource key namespaced with the plugin id
* Create a resource key namespaced with the plugin id.
*
* @param data the string ID elements to join
* @return the key
@@ -33,6 +33,7 @@ import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.util.TransactionResolver;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import java.time.Duration;
@@ -59,8 +60,9 @@ public abstract class BaseHuskHomesAPI {
protected final HuskHomes plugin;
/**
* <b>(Internal use only)</b> - Constructor, instantiating the base API class
* <b>(Internal use only)</b> - Constructor, instantiating the base API class.
*/
@ApiStatus.Internal
protected BaseHuskHomesAPI(@NotNull HuskHomes plugin) {
this.plugin = plugin;
}
@@ -88,19 +90,20 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Get the timestamp of when a user's cooldown for performing an {@link TransactionResolver.Action action} expires
* Get the timestamp of when a user's cooldown for performing an {@link TransactionResolver.Action action} expires.
*
* @param user The {@link User} to get data for.
* @param action The {@link TransactionResolver.Action} to get the cooldown for
* @return An {@link Optional} containing the {@link Instant} the cooldown expires, if there is one
* @since 4.4
*/
public final CompletableFuture<Optional<Instant>> getCooldown(@NotNull User user, @NotNull TransactionResolver.Action action) {
public final CompletableFuture<Optional<Instant>> getCooldown(@NotNull User user,
@NotNull TransactionResolver.Action action) {
return plugin.supplyAsync(() -> plugin.getDatabase().getCooldown(action, user));
}
/**
* Set a cooldown for a user performing an {@link TransactionResolver.Action action}
* Set a cooldown for a user performing an {@link TransactionResolver.Action action}.
*
* @param user The {@link User} to set data for.
* @param action The {@link TransactionResolver.Action} to set the cooldown for
@@ -108,7 +111,8 @@ public abstract class BaseHuskHomesAPI {
* @throws IllegalArgumentException if the expiry is in the past
* @since 4.4
*/
public final void setCooldown(@NotNull User user, @NotNull TransactionResolver.Action action, @NotNull Instant expiry) throws IllegalArgumentException {
public final void setCooldown(@NotNull User user, @NotNull TransactionResolver.Action action,
@NotNull Instant expiry) throws IllegalArgumentException {
if (Instant.now().isAfter(expiry)) {
throw new IllegalArgumentException("Cooldown expiry time must be in the future");
}
@@ -116,7 +120,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Set a cooldown for a user performing an {@link TransactionResolver.Action action}
* Set a cooldown for a user performing an {@link TransactionResolver.Action action}.
*
* @param user The {@link User} to set data for.
* @param action The {@link TransactionResolver.Action} to set the cooldown for
@@ -124,12 +128,13 @@ public abstract class BaseHuskHomesAPI {
* @throws IllegalArgumentException if the duration is negative
* @since 4.4
*/
public final void setCooldown(@NotNull User user, @NotNull TransactionResolver.Action action, @NotNull Duration duration) throws IllegalArgumentException {
public final void setCooldown(@NotNull User user, @NotNull TransactionResolver.Action action,
@NotNull Duration duration) throws IllegalArgumentException {
this.setCooldown(user, action, Instant.now().plus(duration));
}
/**
* Remove a cooldown for a user performing an {@link TransactionResolver.Action action}
* Remove a cooldown for a user performing an {@link TransactionResolver.Action action}.
*
* @param user The {@link User} to remove the cooldown for
* @param action The {@link TransactionResolver.Action} to remove the cooldown for
@@ -140,7 +145,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Returns the last position, as used in the {@code /back} command, for this user
* Returns the last position, as used in the {@code /back} command, for this user.
*
* @param user The {@link User} to get the last position for
* @return The user's last {@link Position}, if there is one
@@ -151,7 +156,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Set the last {@link Position}, as used in the {@code /back} command, for this user
* Set the last {@link Position}, as used in the {@code /back} command, for this user.
*
* @param user The {@link User} to set the last position for
* @param position The {@link Position} to set as the user's last position
@@ -162,7 +167,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Returns where the user last disconnected from a server
* Returns where the user last disconnected from a server.
*
* @param user The {@link User} to get the last disconnect position for
* @return The user's offline {@link Position}, if there is one
@@ -173,9 +178,9 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Returns where the user last set their spawn point by right-clicking a bed or respawn anchor
* <p>
* The optional returned by this method will be empty unless HuskHomes is running cross-server mode
* Returns where the user last set their spawn point by right-clicking a bed or respawn anchor.
*
* <p>The optional returned by this method will be empty unless HuskHomes is running cross-server mode
* and global respawning is enabled
*
* @param user The {@link User} to get the respawn position of
@@ -191,7 +196,7 @@ public abstract class BaseHuskHomesAPI {
/**
* Returns if a user is currently warming up for a timed teleport; that is, they are in the state where they
* must stand still and not take damage for the set amount of seconds before a teleport can be executed.
* must stand still and not take damage for the set number of seconds before a teleport can be executed.
*
* @param user The {@link User} to check
* @return {@code true} if the user is currently warming up, otherwise {@code false}
@@ -202,7 +207,8 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Save {@link SavedUser} to the database, updating it if data for the user already exists, or adding new user data if it doesn't.
* Save {@link SavedUser} to the database, updating it if data for the user already exists,
* or adding new user data if it doesn't.
*
* @param savedUser The {@link SavedUser} to save
* @since 3.0
@@ -254,11 +260,9 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Get a list of {@link Home}s set by the given user that they have made public
* Get a list of {@link Home}s set by the given user that they have made public.
*
* @param user The {@link User} to get the public homes of
* @return A {@link CompletableFuture} that will complete with a list of {@link Home}s set by the user that
* they have made public (where {@link Home#isPublic()})
* @return A {@link CompletableFuture} with the user's public homes (where {@link Home#isPublic()})
* @since 3.0
*/
public final CompletableFuture<List<Home>> getUserPublicHomes(@NotNull User user) {
@@ -268,7 +272,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Get a list of public homes local to this server
* Get a list of public homes local to this server.
*
* @param user The {@link User} to get the local public homes of
* @return A {@link CompletableFuture} that will complete with a list of public {@link Home}s local to the server
@@ -279,7 +283,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Get a list of homes that have been made public ("public homes")
* Get a list of homes that have been made public ("public homes").
*
* @return A {@link CompletableFuture} that will complete with a list of public {@link Home}s
* @since 3.0
@@ -289,11 +293,11 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Get a {@link Home} from the database owned by a given {@link User} with the specified name
* Get a {@link Home} from the database owned by a given {@link User} with the specified name.
*
* @param user The {@link User} to get the home of
* @param homeName The name of the home to get
* @return A {@link CompletableFuture} that will complete with the {@link Home} if it exists, otherwise an empty {@link Optional}
* @return A {@link CompletableFuture} with the {@link Home} if it exists, otherwise an empty {@link Optional}
* @since 3.0
*/
public final CompletableFuture<Optional<Home>> getHome(@NotNull User user, @NotNull String homeName) {
@@ -302,17 +306,17 @@ public abstract class BaseHuskHomesAPI {
/**
* Get a {@link Home} from the database by its' unique id
* Get a {@link Home} from the database by its {@link UUID unique ID}.
*
* @param homeUuid The {@link UUID} of the home to get
* @return A {@link CompletableFuture} that will complete with the {@link Home} if it exists, otherwise an empty {@link Optional}
* @return A {@link CompletableFuture} with the {@link Home} if it exists, otherwise an empty {@link Optional}
*/
public final CompletableFuture<Optional<Home>> getHome(@NotNull UUID homeUuid) {
return plugin.supplyAsync(() -> plugin.getDatabase().getHome(homeUuid));
}
/**
* Create a home for a given user with the specified name and position
* Create a home for a given user with the specified name and position.
*
* @param owner The {@link User} to create the home for
* @param name The name of the home
@@ -324,7 +328,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Delete a home for a given user with the specified name
* Delete a home for a given user with the specified name.
*
* @param owner The {@link User} to delete the home for
* @param name The name of the home
@@ -335,7 +339,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Delete a home
* Delete a home.
*
* @param home The {@link Home} to delete
* @since 4.0
@@ -345,7 +349,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Rename a home for a given user
* Rename a home for a given user.
*
* @param owner The {@link User} to rename the home for
* @param oldName The name of the home to rename
@@ -357,7 +361,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Rename a home
* Rename a home.
*
* @param home The {@link Home} to rename
* @param newName The new name of the home
@@ -368,7 +372,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Set the privacy of a home
* Set the privacy of a home.
*
* @param owner The {@link User} to set the privacy of the home for
* @param name The name of the home
@@ -380,7 +384,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Set the privacy of a home
* Set the privacy of a home.
*
* @param home The {@link Home} to set the privacy of
* @param isPublic Whether the home should be public or not
@@ -391,7 +395,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Set the description of a home
* Set the description of a home.
*
* @param owner The {@link User} to set the description of the home for
* @param name The name of the home
@@ -403,7 +407,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Set the description of a home
* Set the description of a home.
*
* @param home The {@link Home} to set the description of
* @param description The description of the home
@@ -414,7 +418,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Relocate a home for a given user
* Relocate a home for a given user.
*
* @param owner The {@link User} to relocate the home for
* @param name The name of the home
@@ -426,7 +430,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Relocate a home
* Relocate a home.
*
* @param home The {@link Home} to relocate
* @param position The new {@link Position} of the home
@@ -438,7 +442,7 @@ public abstract class BaseHuskHomesAPI {
/**
* Set the meta tags of a home
* Set the meta tags of a home.
*
* @param owner The {@link User} to set the meta tags of the home for
* @param name The name of the home
@@ -450,7 +454,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Set the meta tags of a home
* Set the meta tags of a home.
*
* @param home The {@link Home} to set the meta tags of
* @param tags The meta tags to set
@@ -461,14 +465,15 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Edit the meta tags of a home
* Edit the meta tags of a home.
*
* @param owner The {@link User} to edit the meta tags of the home for
* @param name The name of the home
* @param tagEditor The {@link Consumer} to edit the meta tags with
* @since 4.0
*/
public final void editHomeMetaTags(@NotNull User owner, @NotNull String name, @NotNull Consumer<Map<String, String>> tagEditor) {
public final void editHomeMetaTags(@NotNull User owner, @NotNull String name,
@NotNull Consumer<Map<String, String>> tagEditor) {
plugin.runAsync(() -> plugin.getDatabase().getHome(owner, name).ifPresent(home -> {
final Map<String, String> tags = home.getMeta().getTags();
tagEditor.accept(tags);
@@ -477,7 +482,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Get a list of {@link Warp}s local to this server
* Get a list of {@link Warp}s local to this server.
*
* @return A {@link CompletableFuture} that will complete with a list of {@link Warp}s local to the server
* @since 4.0
@@ -487,7 +492,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Get a list of {@link Warp}s
* Get a list of {@link Warp}s.
*
* @return A {@link CompletableFuture} that will complete with a list of {@link Warp}s
* @since 3.0
@@ -497,10 +502,10 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Get a {@link Warp} from the database with the specified name
* Get a {@link Warp} from the database with the specified name.
*
* @param warpName The name of the warp to get
* @return A {@link CompletableFuture} that will complete with the {@link Warp} if it exists, otherwise an empty {@link Optional}
* @return A {@link CompletableFuture} with the {@link Warp} if it exists, otherwise an empty {@link Optional}
* @since 3.0
*/
public final CompletableFuture<Optional<Warp>> getWarp(@NotNull String warpName) {
@@ -508,17 +513,17 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Get a {@link Warp} from the database by its' unique id
* Get a {@link Warp} from the database by its {@link UUID unique ID}.
*
* @param warpUuid The {@link UUID} of the warp to get
* @return A {@link CompletableFuture} that will complete with the {@link Warp} if it exists, otherwise an empty {@link Optional}
* @return A {@link CompletableFuture} with the {@link Warp} if it exists, otherwise an empty {@link Optional}
*/
public final CompletableFuture<Optional<Warp>> getWarp(@NotNull UUID warpUuid) {
return plugin.supplyAsync(() -> plugin.getDatabase().getWarp(warpUuid));
}
/**
* Create a new {@link Warp} with the given name and {@link Position}
* Create a new {@link Warp} with the given name and {@link Position}.
*
* @param name The name of the warp
* @param position The {@link Position} of the warp
@@ -529,7 +534,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Delete a {@link Warp} with the given name
* Delete a {@link Warp} with the given name.
*
* @param name The name of the warp to delete
*/
@@ -538,7 +543,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Delete a {@link Warp}
* Delete a {@link Warp}.
*
* @param warp The {@link Warp} to delete
*/
@@ -547,7 +552,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Rename a {@link Warp} by name
* Rename a {@link Warp} by name.
*
* @param oldName The name of the warp to rename
* @param newName The new name of the warp
@@ -557,7 +562,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Rename a {@link Warp}
* Rename a {@link Warp}.
*
* @param warp The {@link Warp} to rename
* @param newName The new name of the warp
@@ -567,7 +572,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Set the description of a {@link Warp} by name
* Set the description of a {@link Warp} by name.
*
* @param name The name of the warp to set the description of
* @param description The new description of the warp
@@ -577,7 +582,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Set the description of a {@link Warp}
* Set the description of a {@link Warp}.
*
* @param warp The {@link Warp} to set the description of
* @param description The new description of the warp
@@ -587,7 +592,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Set the {@link Position} of a {@link Warp} by name
* Set the {@link Position} of a {@link Warp} by name.
*
* @param name The name of the warp to set the {@link Position} of
* @param position The new {@link Position} of the warp
@@ -597,7 +602,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Set the {@link Position} of a {@link Warp}
* Set the {@link Position} of a {@link Warp}.
*
* @param warp The {@link Warp} to set the {@link Position} of
* @param position The new {@link Position} of the warp
@@ -607,7 +612,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Set the meta tags of a {@link Warp} by name
* Set the meta tags of a {@link Warp} by name.
*
* @param name The name of the warp to set the meta tags of
* @param tags The new meta tags of the warp
@@ -618,7 +623,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Set the meta tags of a {@link Warp}
* Set the meta tags of a {@link Warp}.
*
* @param warp The {@link Warp} to set the meta tags of
* @param tags The new meta tags of the warp
@@ -629,7 +634,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Edit the meta tags of a {@link Warp} by name
* Edit the meta tags of a {@link Warp} by name.
*
* @param name The name of the warp to edit the meta tags of
* @param tagEditor A {@link Consumer} that will be passed the current meta tags of the warp
@@ -646,8 +651,10 @@ public abstract class BaseHuskHomesAPI {
/**
* Get the canonical {@link Position} of the spawn point. Note that if cross-server and global spawn
* are enabled in the config, this may not return a position on this server.
* Get the canonical {@link Position} of the spawn point.
*
* <p>Note that if cross-server and global spawn are enabled in the config,
* this may not return a position on this server.
*
* @return A {@link CompletableFuture} that will complete with the {@link Position} of the spawn point
*/
@@ -656,7 +663,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Get the maximum number of set homes a given {@link OnlineUser} can make
* Get the maximum number of set homes a given {@link OnlineUser} can make.
*
* @param user The {@link OnlineUser} to get the maximum number of homes for
* @return The maximum number of homes the user can set
@@ -667,9 +674,9 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Get the number of homes an {@link OnlineUser} can set for free
* <p>
* This is irrelevant unless the server is using economy features with HuskHomes
* Get the number of homes an {@link OnlineUser} can set for free.
*
* <p>This is irrelevant unless the server is using economy features with HuskHomes.
*
* @param user The {@link OnlineUser} to get the number of free home slots for
* @return The number of homes the user can set for free
@@ -680,7 +687,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Get the number of homes an {@link OnlineUser} can make public
* Get the number of homes an {@link OnlineUser} can make public.
*
* @param user The {@link OnlineUser} to get the number of public home slots for
* @return The number of homes the user can make public
@@ -691,7 +698,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Get a {@link TeleportBuilder} to construct and execute a (timed) teleport
* Get a {@link TeleportBuilder} to construct and execute a (timed) teleport.
*
* @param teleporter The {@link OnlineUser} to teleport
* @return A {@link TeleportBuilder} to construct and execute a (timed) teleport
@@ -703,7 +710,7 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Get a {@link TeleportBuilder} to construct and execute a (timed) teleport
* Get a {@link TeleportBuilder} to construct and execute a (timed) teleport.
*
* @return A {@link TeleportBuilder} to construct and execute a (timed) teleport
* @since 4.0
@@ -716,7 +723,7 @@ public abstract class BaseHuskHomesAPI {
/**
* Attempt to teleport an {@link OnlineUser} to a randomly generated {@link Position}. The {@link Position} will be
* generated by the current {@link RandomTeleportEngine}
* generated by the current {@link RandomTeleportEngine}.
*
* @param user The {@link OnlineUser} to teleport
* @param timedTeleport Whether the teleport should be timed or not (requiring a warmup where they must stand still
@@ -724,7 +731,8 @@ public abstract class BaseHuskHomesAPI {
* @param rtpArgs Arguments that will be passed to the implementing {@link RandomTeleportEngine}
* @since 3.0
*/
public final void randomlyTeleportPlayer(@NotNull OnlineUser user, boolean timedTeleport, @NotNull String... rtpArgs) {
public final void randomlyTeleportPlayer(@NotNull OnlineUser user, boolean timedTeleport,
@NotNull String... rtpArgs) {
plugin.getRandomTeleportEngine()
.getRandomPosition(user.getPosition().getWorld(), rtpArgs)
.thenAccept(position -> {
@@ -751,7 +759,7 @@ public abstract class BaseHuskHomesAPI {
/**
* Attempt to teleport an {@link OnlineUser} to a randomly generated {@link Position}. The {@link Position} will be
* generated by the current {@link RandomTeleportEngine}
* generated by the current {@link RandomTeleportEngine}.
*
* @param user The {@link OnlineUser} to teleport
* @since 3.0
@@ -761,9 +769,10 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Set the {@link RandomTeleportEngine} to use for processing random teleports. The engine will be used to process all
* random teleports, including both {@code /rtp} command executions and API ({@link #randomlyTeleportPlayer(OnlineUser)})
* calls.
* Set the {@link RandomTeleportEngine} to use for processing random teleports.
*
* <p>The engine will be used to process all random {@link Teleport teleports},
* including both {@code /rtp} command executions and {@link #randomlyTeleportPlayer(OnlineUser) API calls}.
*
* @param randomTeleportEngine the {@link RandomTeleportEngine} to use to process random teleports
* @see RandomTeleportEngine
@@ -774,21 +783,20 @@ public abstract class BaseHuskHomesAPI {
}
/**
* Get a {@link MineDown}-formatted locale by key from the plugin {@link Locales} file
* Get a {@link MineDown}-formatted locale by key from the plugin {@link Locales} file.
*
* @param localeKey The key of the locale to get
* @param replacements Replacement strings to apply to the locale
* @return The {@link MineDown}-formatted locale
* @apiNote Since v3.0.4, this method returns a `adventure.MineDown` object, targeting
* <a href="https://docs.adventure.kyori.net/">Adventure</a> platforms, rather than a bungee components object.
* @since 3.0.4
* @apiNote Since v3.0.4, this returns MineDown-<a href="https://docs.adventure.kyori.net/">Adventure</a> components
* @since 3.0
*/
public final Optional<MineDown> getLocale(@NotNull String localeKey, @NotNull String... replacements) {
return plugin.getLocales().getLocale(localeKey, replacements);
}
/**
* Get a raw locale string by key from the plugin {@link Locales} file
* Get a raw locale string by key from the plugin {@link Locales} file.
*
* @param localeKey The key of the locale to get
* @param replacements Replacement strings to apply to the locale
@@ -799,4 +807,23 @@ public abstract class BaseHuskHomesAPI {
return plugin.getLocales().getRawLocale(localeKey, replacements);
}
/**
* An exception indicating the plugin has been accessed before it has been registered.
*/
static final class NotRegisteredException extends IllegalStateException {
private static final String MESSAGE = """
Could not access the HuskHomes API as it has not yet been registered. This could be because:
1) HuskHomes has failed to enable successfully
2) Your plugin isn't set to load after HuskHomes has
(Check if it set as a (soft)depend in plugin.yml or to load: BEFORE in paper-plugin.yml?)
3) You are attempting to access HuskHomes on plugin construction/before your plugin has enabled.""";
NotRegisteredException() {
super(MESSAGE);
}
}
}
@@ -36,8 +36,8 @@ public class BackCommand extends InGameCommand {
protected BackCommand(@NotNull HuskHomes plugin) {
super("back", List.of(), "", plugin);
addAdditionalPermissions(Map.of(
"death", false,
"previous", false
"death", false,
"previous", false
));
}
@@ -32,7 +32,8 @@ public abstract class Command extends Node {
private final String usage;
private final Map<String, Boolean> additionalPermissions;
protected Command(@NotNull String name, @NotNull List<String> aliases, @NotNull String usage, @NotNull HuskHomes plugin) {
protected Command(@NotNull String name, @NotNull List<String> aliases, @NotNull String usage,
@NotNull HuskHomes plugin) {
super(name, aliases, plugin);
this.usage = usage;
this.additionalPermissions = new HashMap<>();
@@ -70,8 +71,8 @@ public abstract class Command extends Node {
return "/" + getName() + " " + getRawUsage();
}
public final void addAdditionalPermissions(@NotNull Map<String, Boolean> additionalPermissions) {
additionalPermissions.forEach((permission, value) -> this.additionalPermissions.put(getPermission(permission), value));
public final void addAdditionalPermissions(@NotNull Map<String, Boolean> permissions) {
permissions.forEach((permission, value) -> this.additionalPermissions.put(getPermission(permission), value));
}
@NotNull
@@ -44,7 +44,8 @@ public class DelHomeCommand extends SavedPositionCommand<Home> {
@Override
public void execute(@NotNull CommandUser executor, @NotNull Home home, @NotNull String[] args) {
if (executor instanceof OnlineUser user && !home.getOwner().equals(user) && !user.hasPermission(getOtherPermission())) {
if (executor instanceof OnlineUser user && !home.getOwner().equals(user)
&& !user.hasPermission(getOtherPermission())) {
plugin.getLocales().getLocale("error_no_permission")
.ifPresent(user::sendMessage);
return;
@@ -72,10 +72,12 @@ public class EditHomeCommand extends SavedPositionCommand<Home> {
case "description" -> setHomeDescription(executor, home, ownerEditing, args);
case "relocate" -> setHomePosition(executor, home, ownerEditing);
case "privacy" -> setHomePrivacy(executor, home, ownerEditing, args);
default -> throw new IllegalStateException("Unexpected value: " + operation.get().toLowerCase());
}
}
private void setHomeName(@NotNull CommandUser executor, @NotNull Home home, boolean ownerEditing, @NotNull String[] args) {
private void setHomeName(@NotNull CommandUser executor, @NotNull Home home, boolean ownerEditing,
@NotNull String[] args) {
final String oldName = home.getName();
final Optional<String> optionalName = parseStringArg(args, 1);
if (optionalName.isEmpty()) {
@@ -106,7 +108,8 @@ public class EditHomeCommand extends SavedPositionCommand<Home> {
});
}
private void setHomeDescription(@NotNull CommandUser executor, @NotNull Home home, boolean ownerEditing, @NotNull String[] args) {
private void setHomeDescription(@NotNull CommandUser executor, @NotNull Home home, boolean ownerEditing,
@NotNull String[] args) {
final String oldDescription = home.getMeta().getDescription();
final Optional<String> optionalDescription = parseGreedyArguments(args);
if (optionalDescription.isEmpty()) {
@@ -127,7 +130,8 @@ public class EditHomeCommand extends SavedPositionCommand<Home> {
}
if (ownerEditing) {
plugin.getLocales().getLocale("edit_home_update_description", home.getName(), oldDescription, newDescription)
plugin.getLocales().getLocale("edit_home_update_description",
home.getName(), oldDescription, newDescription)
.ifPresent(executor::sendMessage);
} else {
plugin.getLocales().getLocale("edit_home_update_description_other", home.getOwner().getUsername(),
@@ -157,21 +161,24 @@ public class EditHomeCommand extends SavedPositionCommand<Home> {
plugin.getLocales().getLocale("edit_home_update_location", home.getName())
.ifPresent(executor::sendMessage);
} else {
plugin.getLocales().getLocale("edit_home_update_location_other", home.getOwner().getUsername(), home.getName())
plugin.getLocales().getLocale("edit_home_update_location_other",
home.getOwner().getUsername(), home.getName())
.ifPresent(executor::sendMessage);
}
});
}
private void setHomePrivacy(@NotNull CommandUser executor, @NotNull Home home, boolean ownerEditing, @NotNull String[] args) {
private void setHomePrivacy(@NotNull CommandUser executor, @NotNull Home home, boolean ownerEditing,
@NotNull String[] args) {
if (!executor.hasPermission(getPermission("privacy"))) {
plugin.getLocales().getLocale("error_no_permission")
.ifPresent(executor::sendMessage);
return;
}
// Check against economy
if (executor instanceof OnlineUser user && !plugin.validateTransaction(user, TransactionResolver.Action.MAKE_HOME_PUBLIC)) {
// Check against the economy hook
if (executor instanceof OnlineUser user
&& !plugin.validateTransaction(user, TransactionResolver.Action.MAKE_HOME_PUBLIC)) {
return;
}
@@ -184,7 +191,8 @@ public class EditHomeCommand extends SavedPositionCommand<Home> {
try {
plugin.getManager().homes().setHomePrivacy(event.getHome(), home.isPublic());
} catch (ValidationException e) {
int maxHomes = plugin.getManager().homes().getMaxPublicHomes(executor instanceof OnlineUser user ? user : null);
int maxHomes = plugin.getManager().homes()
.getMaxPublicHomes(executor instanceof OnlineUser user ? user : null);
e.dispatchHomeError(executor, false, plugin, Integer.toString(maxHomes));
return;
}
@@ -208,7 +216,7 @@ public class EditHomeCommand extends SavedPositionCommand<Home> {
}
/**
* Get a formatted home editor chat window for a supplied {@link Home}
* Get a formatted home editor chat window for a supplied {@link Home}.
*
* @param home The home to display
* @param otherViewer If the viewer of the editor is not the homeowner
@@ -219,55 +227,61 @@ public class EditHomeCommand extends SavedPositionCommand<Home> {
@NotNull
private List<MineDown> getHomeEditorWindow(@NotNull Home home, boolean otherViewer,
boolean showTeleportButton, boolean showPrivacyToggleButton) {
return new ArrayList<>() {{
if (!otherViewer) {
plugin.getLocales().getLocale("edit_home_menu_title", home.getName())
.ifPresent(this::add);
} else {
plugin.getLocales().getLocale("edit_home_menu_title_other", home.getOwner().getUsername(), home.getName())
.ifPresent(this::add);
}
final List<MineDown> messages = new ArrayList<>();
if (!otherViewer) {
plugin.getLocales().getLocale("edit_home_menu_title", home.getName())
.ifPresent(messages::add);
} else {
plugin.getLocales().getLocale("edit_home_menu_title_other",
home.getOwner().getUsername(), home.getName())
.ifPresent(messages::add);
}
plugin.getLocales().getLocale("edit_home_menu_metadata_" + (!home.isPublic() ? "private" : "public"),
DateTimeFormatter.ofPattern("MMM dd yyyy, HH:mm")
.format(home.getMeta().getCreationTime().atZone(ZoneId.systemDefault())),
home.getUuid().toString().split(Pattern.quote("-"))[0],
home.getUuid().toString())
.ifPresent(this::add);
plugin.getLocales().getLocale("edit_home_menu_metadata_" + (!home.isPublic() ? "private" : "public"),
DateTimeFormatter.ofPattern("MMM dd yyyy, HH:mm")
.format(home.getMeta().getCreationTime().atZone(ZoneId.systemDefault())),
home.getUuid().toString().split(Pattern.quote("-"))[0],
home.getUuid().toString())
.ifPresent(messages::add);
if (home.getMeta().getDescription().length() > 0) {
plugin.getLocales().getLocale("edit_home_menu_description",
plugin.getLocales().truncateText(home.getMeta().getDescription(), 50),
plugin.getLocales().wrapText(home.getMeta().getDescription(), 40))
.ifPresent(this::add);
}
if (home.getMeta().getDescription().length() > 0) {
plugin.getLocales().getLocale("edit_home_menu_description",
plugin.getLocales().truncateText(home.getMeta().getDescription(), 50),
plugin.getLocales().wrapText(home.getMeta().getDescription(), 40))
.ifPresent(messages::add);
}
if (!plugin.getSettings().doCrossServer()) {
plugin.getLocales().getLocale("edit_home_menu_world", home.getWorld().getName())
.ifPresent(this::add);
} else {
plugin.getLocales().getLocale("edit_home_menu_world_server", home.getWorld().getName(), home.getServer())
.ifPresent(this::add);
}
if (!plugin.getSettings().doCrossServer()) {
plugin.getLocales().getLocale("edit_home_menu_world", home.getWorld().getName())
.ifPresent(messages::add);
} else {
plugin.getLocales().getLocale("edit_home_menu_world_server",
home.getWorld().getName(), home.getServer())
.ifPresent(messages::add);
}
plugin.getLocales().getLocale("edit_home_menu_coordinates",
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);
plugin.getLocales().getLocale("edit_home_menu_coordinates",
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(messages::add);
if (showTeleportButton) {
plugin.getLocales().getLocale("edit_home_menu_use_buttons", home.getSafeIdentifier())
.ifPresent(this::add);
}
plugin.getLocales().getRawLocale("edit_home_menu_manage_buttons", home.getSafeIdentifier(),
showPrivacyToggleButton ? plugin.getLocales()
.getRawLocale("edit_home_menu_privacy_button_"
+ (home.isPublic() ? "private" : "public"), home.getSafeIdentifier())
.orElse("") : "")
.map(MineDown::new).ifPresent(this::add);
plugin.getLocales().getLocale("edit_home_menu_meta_edit_buttons", home.getSafeIdentifier())
.ifPresent(this::add);
}};
if (showTeleportButton) {
plugin.getLocales().getLocale("edit_home_menu_use_buttons", home.getSafeIdentifier())
.ifPresent(messages::add);
}
plugin.getLocales().getRawLocale("edit_home_menu_manage_buttons",
home.getSafeIdentifier(),
showPrivacyToggleButton ? plugin.getLocales()
.getRawLocale("edit_home_menu_privacy_button_"
+ (home.isPublic() ? "private" : "public"), home.getSafeIdentifier())
.orElse("") : "")
.map(MineDown::new).ifPresent(messages::add);
plugin.getLocales().getLocale("edit_home_menu_meta_edit_buttons", home.getSafeIdentifier())
.ifPresent(messages::add);
return messages;
}
}
@@ -61,6 +61,7 @@ public class EditWarpCommand extends SavedPositionCommand<Warp> {
case "rename" -> setWarpName(executor, warp, args);
case "description" -> setWarpDescription(executor, warp, args);
case "relocate" -> setWarpPosition(executor, warp);
default -> throw new IllegalStateException("Unexpected value: " + operation.get().toLowerCase());
}
}
@@ -106,7 +107,8 @@ public class EditWarpCommand extends SavedPositionCommand<Warp> {
return;
}
plugin.getLocales().getLocale("edit_warp_update_description", warp.getName(), warp.getMeta().getDescription())
plugin.getLocales().getLocale("edit_warp_update_description",
warp.getName(), warp.getMeta().getDescription())
.ifPresent(executor::sendMessage);
});
}
@@ -133,49 +135,54 @@ public class EditWarpCommand extends SavedPositionCommand<Warp> {
}
/**
* Get a formatted warp editor chat window for a supplied {@link Warp}
* Get a formatted warp editor chat window for a supplied {@link Warp}.
*
* @param warp The warp to display
* @return List of {@link MineDown} messages to send to the editor that form the menu
*/
@NotNull
private List<MineDown> getWarpEditorWindow(@NotNull Warp warp) {
return new ArrayList<>() {{
plugin.getLocales().getLocale("edit_warp_menu_title", warp.getName())
.ifPresent(this::add);
final List<MineDown> messages = new ArrayList<>();
plugin.getLocales().getLocale("edit_warp_menu_title", warp.getName())
.ifPresent(messages::add);
plugin.getLocales().getLocale("edit_warp_menu_metadata",
DateTimeFormatter.ofPattern("MMM dd yyyy, HH:mm")
.format(warp.getMeta().getCreationTime().atZone(ZoneId.systemDefault())),
warp.getUuid().toString().split(Pattern.quote("-"))[0],
warp.getUuid().toString())
.ifPresent(this::add);
plugin.getLocales().getLocale("edit_warp_menu_metadata",
DateTimeFormatter.ofPattern("MMM dd yyyy, HH:mm")
.format(warp.getMeta().getCreationTime().atZone(ZoneId.systemDefault())),
warp.getUuid().toString().split(Pattern.quote("-"))[0],
warp.getUuid().toString())
.ifPresent(messages::add);
if (warp.getMeta().getDescription().length() > 0) {
plugin.getLocales().getLocale("edit_warp_menu_description",
plugin.getLocales().truncateText(warp.getMeta().getDescription(), 50),
plugin.getLocales().wrapText(warp.getMeta().getDescription(), 40))
.ifPresent(this::add);
}
if (warp.getMeta().getDescription().length() > 0) {
plugin.getLocales().getLocale("edit_warp_menu_description",
plugin.getLocales().truncateText(warp.getMeta().getDescription(), 50),
plugin.getLocales().wrapText(warp.getMeta().getDescription(), 40))
.ifPresent(messages::add);
}
if (!plugin.getSettings().doCrossServer()) {
plugin.getLocales().getLocale("edit_warp_menu_world", warp.getWorld().getName()).ifPresent(this::add);
} else {
plugin.getLocales().getLocale("edit_warp_menu_world_server", warp.getWorld().getName(), warp.getServer()).ifPresent(this::add);
}
if (!plugin.getSettings().doCrossServer()) {
plugin.getLocales().getLocale("edit_warp_menu_world",
warp.getWorld().getName()).ifPresent(messages::add);
} else {
plugin.getLocales().getLocale("edit_warp_menu_world_server",
warp.getWorld().getName(), warp.getServer()).ifPresent(messages::add);
}
plugin.getLocales().getLocale("edit_warp_menu_coordinates",
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);
plugin.getLocales().getLocale("edit_warp_menu_coordinates",
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(messages::add);
plugin.getLocales().getLocale("edit_warp_menu_use_buttons", warp.getSafeIdentifier())
.ifPresent(this::add);
plugin.getLocales().getLocale("edit_warp_menu_manage_buttons", warp.getSafeIdentifier())
.ifPresent(this::add);
plugin.getLocales().getLocale("edit_warp_menu_meta_edit_buttons", warp.getSafeIdentifier())
.ifPresent(this::add);
}};
plugin.getLocales().getLocale("edit_warp_menu_use_buttons", warp.getSafeIdentifier())
.ifPresent(messages::add);
plugin.getLocales().getLocale("edit_warp_menu_manage_buttons", warp.getSafeIdentifier())
.ifPresent(messages::add);
plugin.getLocales().getLocale("edit_warp_menu_meta_edit_buttons", warp.getSafeIdentifier())
.ifPresent(messages::add);
return messages;
}
}
@@ -100,12 +100,15 @@ public class HuskHomesCommand extends Command implements TabProvider {
.getNearestValidPage(parseIntArg(args, 1).orElse(1)));
case "reload" -> {
if (!plugin.loadConfigs()) {
executor.sendMessage(new MineDown("[Error:](#ff3300) [Failed to reload the plugin. Check console for errors.](#ff7e5e)"));
executor.sendMessage(new MineDown(
"[Error:](#ff3300) [Failed to reload the plugin. Check console for errors.](#ff7e5e)"
));
return;
}
executor.sendMessage(new MineDown("""
[HuskHomes](#00fb9a bold) [| Reloaded config & message files.](#00fb9a)
[ℹ If you have modified the database or cross-server message broker settings, you need to restart your server for these changes to take effect.](gray)"""
executor.sendMessage(new MineDown(
"[HuskHomes](#00fb9a bold) [| Reloaded config & message files.](#00fb9a)\n"
+ "[ℹ If you have modified the database or cross-server message broker settings,"
+ " you need to restart your server for these changes to take effect.](gray)"
));
}
case "update" -> updateChecker.check().thenAccept(checked -> {
@@ -32,7 +32,8 @@ public abstract class ListCommand extends Command {
protected final Map<UUID, PaginatedList> cachedLists;
protected ListCommand(@NotNull String name, @NotNull List<String> aliases, @NotNull String usage, @NotNull HuskHomes plugin) {
protected ListCommand(@NotNull String name, @NotNull List<String> aliases, @NotNull String usage,
@NotNull HuskHomes plugin) {
super(name, aliases, usage, plugin);
this.cachedLists = new HashMap<>();
}
@@ -156,23 +156,23 @@ public abstract class Node implements Executable {
.orElse(Position.at(0, 0, 0, 0, 0, plugin.getWorlds().get(0), plugin.getServerName()));
}
protected Optional<Position> parsePositionArgs(@NotNull Position basePosition, @NotNull String[] args, int startIndex) {
protected Optional<Position> parsePositionArgs(@NotNull Position basePosition, @NotNull String[] args, int from) {
// Parse x, y, and z
final Optional<Double> x = parseCoordinateArg(args, startIndex, basePosition.getX());
final Optional<Double> y = parseCoordinateArg(args, startIndex + 1, basePosition.getY());
final Optional<Double> z = parseCoordinateArg(args, startIndex + 2, basePosition.getZ());
final Optional<Double> x = parseCoordinateArg(args, from, basePosition.getX());
final Optional<Double> y = parseCoordinateArg(args, from + 1, basePosition.getY());
final Optional<Double> z = parseCoordinateArg(args, from + 2, basePosition.getZ());
if (x.isEmpty() || y.isEmpty() || z.isEmpty()) {
return Optional.empty();
}
// Parse world and server name
final Optional<World> world = parseWorldArg(args, startIndex + 3);
final Optional<String> server = parseStringArg(args, startIndex + 4);
final Optional<World> world = parseWorldArg(args, from + 3);
final Optional<String> server = parseStringArg(args, from + 4);
// Parse yaw, pitch
int angleStartIndex = (world.isEmpty() ? 3 : server.isEmpty() ? 4 : 5);
final Optional<Float> yaw = parseFloatArg(args, startIndex + angleStartIndex);
final Optional<Float> pitch = parseFloatArg(args, startIndex + angleStartIndex + 1);
final Optional<Float> yaw = parseFloatArg(args, from + angleStartIndex);
final Optional<Float> pitch = parseFloatArg(args, from + angleStartIndex + 1);
return Optional.of(Position.at(x.get(), y.get(), z.get(),
yaw.orElse(basePosition.getYaw()), pitch.orElse(basePosition.getPitch()),
@@ -74,7 +74,7 @@ public class PrivateHomeListCommand extends ListCommand {
}
if (executor instanceof OnlineUser onlineUser && !user.getUuid().equals(onlineUser.getUuid())
&& !executor.hasPermission(getPermission("other"))) {
&& !executor.hasPermission(getPermission("other"))) {
plugin.getLocales().getLocale("error_no_permission")
.ifPresent(executor::sendMessage);
return;
@@ -93,7 +93,8 @@ public class PrivateHomeListCommand extends ListCommand {
}));
}
private Optional<PaginatedList> generateList(@NotNull CommandUser executor, @NotNull User user, @NotNull List<Home> homes) {
private Optional<PaginatedList> generateList(@NotNull CommandUser executor, @NotNull User user,
@NotNull List<Home> homes) {
if (homes.isEmpty()) {
if (!executor.equals(user)) {
plugin.getLocales().getLocale("error_no_homes_set_other", user.getUsername())
@@ -109,7 +110,10 @@ public class PrivateHomeListCommand extends ListCommand {
plugin.getLocales()
.getRawLocale("home_list_item",
Locales.escapeText(home.getName()), home.getSafeIdentifier(),
Locales.escapeText(plugin.getLocales().wrapText(home.getMeta().getDescription(), 40)))
Locales.escapeText(plugin.getLocales().wrapText(
home.getMeta().getDescription(),
40
)))
.orElse(home.getName())).sorted().collect(Collectors.toList()),
plugin.getLocales()
.getBaseList(plugin.getSettings().getListItemsPerPage())
@@ -46,7 +46,7 @@ public class PublicHomeCommand extends HomeCommand implements TabProvider {
@NotNull
public List<String> suggest(@NotNull CommandUser executor, @NotNull String[] args) {
if (args.length <= 2) {
return filter(plugin.getManager().homes().getPublicHomeNames(), args);
return filter(plugin.getManager().homes().getPublicHomeIdentifiers(), args);
}
return List.of();
}
@@ -71,7 +71,10 @@ public class PublicHomeListCommand extends ListCommand {
.getRawLocale("public_home_list_item",
Locales.escapeText(home.getName()), home.getSafeIdentifier(),
Locales.escapeText(home.getOwner().getUsername()),
Locales.escapeText(plugin.getLocales().wrapText(home.getMeta().getDescription(), 40)))
Locales.escapeText(plugin.getLocales().wrapText(
home.getMeta().getDescription(),
40
)))
.orElse(home.getName())).sorted().collect(Collectors.toList()),
plugin.getLocales()
.getBaseList(plugin.getSettings().getListItemsPerPage())
@@ -80,14 +80,15 @@ public class RtpCommand extends Command implements UserListTabProvider {
}
/**
* Validates the RTP command, returning the world to randomly teleport in if successful
* Validates the RTP command, returning the world to randomly teleport in if successful.
*
* @param teleporter The user to teleport
* @param executor The user executing the command
* @param args The command arguments
* @return The world to randomly teleport in, if successful
*/
private Optional<World> validateRtp(@NotNull OnlineUser teleporter, @NotNull CommandUser executor, @NotNull String[] args) {
private Optional<World> validateRtp(@NotNull OnlineUser teleporter, @NotNull CommandUser executor,
@NotNull String[] args) {
// Check permissions if the user is being teleported by another player
if (!executor.equals(teleporter) && !executor.hasPermission(getPermission("other"))) {
plugin.getLocales().getLocale("error_no_permission")
@@ -127,7 +128,7 @@ public class RtpCommand extends Command implements UserListTabProvider {
}
/**
* Executes the random teleport
* Executes the random teleport.
*
* @param teleporter The player to teleport
* @param executor The player executing the command
@@ -45,7 +45,7 @@ public abstract class SavedPositionCommand<T extends SavedPosition> extends Comm
protected SavedPositionCommand(@NotNull String name, @NotNull List<String> aliases, @NotNull Class<T> positionType,
@NotNull List<String> arguments, @NotNull HuskHomes plugin) {
super(name, aliases, "<name>" + ((arguments.size() > 0) ? " [" + String.join("|", arguments) + "]" : ""), plugin);
super(name, aliases, "<name>" + formatUsage(arguments), plugin);
this.positionType = positionType;
this.arguments = arguments;
@@ -78,18 +78,18 @@ public abstract class SavedPositionCommand<T extends SavedPosition> extends Comm
private Optional<Home> resolveHome(@NotNull CommandUser executor, @NotNull String homeName) {
if (homeName.contains(Home.IDENTIFIER_DELIMITER)) {
final String ownerUsername = homeName.substring(0, homeName.indexOf(Home.IDENTIFIER_DELIMITER));
final String ownerHomeName = homeName.substring(homeName.indexOf(Home.IDENTIFIER_DELIMITER) + 1);
if (ownerUsername.isBlank() || ownerHomeName.isBlank()) {
final String ownerHome = homeName.substring(homeName.indexOf(Home.IDENTIFIER_DELIMITER) + 1);
if (ownerUsername.isBlank() || ownerHome.isBlank()) {
plugin.getLocales().getLocale("error_invalid_syntax", getUsage())
.ifPresent(executor::sendMessage);
return Optional.empty();
}
final Optional<Home> optionalHome = plugin.getDatabase().getUserDataByName(ownerUsername)
.flatMap(owner -> resolveHomeByName(owner.getUser(), ownerHomeName));
.flatMap(owner -> resolveHomeByName(owner.getUser(), ownerHome));
if (optionalHome.isEmpty()) {
plugin.getLocales().getLocale(executor.hasPermission(getOtherPermission())
? "error_home_invalid_other" : "error_public_home_invalid", ownerUsername, ownerHomeName)
? "error_home_invalid_other" : "error_public_home_invalid", ownerUsername, ownerHome)
.ifPresent(executor::sendMessage);
return Optional.empty();
}
@@ -97,7 +97,7 @@ public abstract class SavedPositionCommand<T extends SavedPosition> extends Comm
final Home home = optionalHome.get();
if (executor instanceof OnlineUser user && !home.isPublic() && !user.equals(home.getOwner())
&& !user.hasPermission(getOtherPermission())) {
plugin.getLocales().getLocale("error_public_home_invalid", ownerUsername, ownerHomeName)
plugin.getLocales().getLocale("error_public_home_invalid", ownerUsername, ownerHome)
.ifPresent(executor::sendMessage);
return Optional.empty();
}
@@ -138,7 +138,8 @@ public abstract class SavedPositionCommand<T extends SavedPosition> extends Comm
return Optional.empty();
}
if (executor instanceof OnlineUser user && plugin.getSettings().doPermissionRestrictWarps()
&& !user.hasPermission(Warp.getWildcardPermission()) && !user.hasPermission(Warp.getPermission(warpName))) {
&& !user.hasPermission(Warp.getWildcardPermission())
&& !user.hasPermission(Warp.getPermission(warpName))) {
plugin.getLocales().getLocale("error_warp_invalid", warpName)
.ifPresent(executor::sendMessage);
return Optional.empty();
@@ -180,6 +181,11 @@ public abstract class SavedPositionCommand<T extends SavedPosition> extends Comm
}
}
@NotNull
private static String formatUsage(List<String> arguments) {
return ((arguments.size() > 0) ? " [" + String.join("|", arguments) + "]" : "");
}
@Override
@NotNull
public List<String> suggest(@NotNull CommandUser executor, @NotNull String[] args) {
@@ -188,14 +194,14 @@ public abstract class SavedPositionCommand<T extends SavedPosition> extends Comm
case 0, 1 -> {
if (args.length == 1 && args[0].contains(Home.IDENTIFIER_DELIMITER)) {
if (executor.hasPermission(getOtherPermission())) {
yield filter(plugin.getManager().homes().getUserHomeNames(), args);
yield filter(plugin.getManager().homes().getUserHomeIdentifiers(), args);
}
yield filter(plugin.getManager().homes().getUserHomeNames(), args);
yield filter(plugin.getManager().homes().getUserHomeIdentifiers(), args);
}
if (executor instanceof OnlineUser user) {
yield filter(plugin.getManager().homes().getUserHomes().get(user.getUsername()), args);
}
yield filter(plugin.getManager().homes().getUserHomeNames(), args);
yield filter(plugin.getManager().homes().getUserHomeIdentifiers(), args);
}
case 2 -> filter(arguments.stream().toList(), args);
default -> List.of();
@@ -41,8 +41,9 @@ public class SetSpawnCommand extends InGameCommand {
if (plugin.getSettings().doCrossServer() && plugin.getSettings().isGlobalSpawn()) {
final String warpName = plugin.getSettings().getGlobalSpawnName();
plugin.getManager().warps().createWarp(warpName, position, true);
plugin.getLocales().getRawLocale("spawn_warp_default_description")
.ifPresent(description -> plugin.getManager().warps().setWarpDescription(warpName, description));
plugin.getLocales().getRawLocale("spawn_warp_default_description").ifPresent(
description -> plugin.getManager().warps().setWarpDescription(warpName, description)
);
} else {
plugin.setServerSpawn(position);
}
@@ -59,8 +59,8 @@ public class SpawnCommand extends Command {
this.teleportToSpawn(optionalTeleporter.get(), executor, spawn.get(), args);
}
public void teleportToSpawn(@NotNull Teleportable teleporter, @NotNull CommandUser executor, @NotNull Position spawn,
@NotNull String[] args) {
public void teleportToSpawn(@NotNull Teleportable teleporter, @NotNull CommandUser executor,
@NotNull Position spawn, @NotNull String[] args) {
if (!executor.equals(teleporter) && !executor.hasPermission(getPermission("other"))) {
plugin.getLocales().getLocale("error_no_permission")
.ifPresent(executor::sendMessage);
@@ -115,16 +115,16 @@ public class TpCommand extends Command implements TabProvider {
@Override
@NotNull
public final List<String> suggest(@NotNull CommandUser user, @NotNull String[] args) {
final Position basePosition = getBasePosition(user);
final Position relative = getBasePosition(user);
final boolean serveCoordinateCompletions = user.hasPermission(getPermission("coordinates"));
switch (args.length) {
case 0, 1 -> {
final ArrayList<String> completions = new ArrayList<>();
completions.addAll(serveCoordinateCompletions
? List.of("~", "~ ~", "~ ~ ~",
Integer.toString((int) basePosition.getX()),
((int) basePosition.getX() + " " + (int) basePosition.getY()),
((int) basePosition.getX() + " " + (int) basePosition.getY() + " " + (int) basePosition.getZ()))
Integer.toString((int) relative.getX()),
((int) relative.getX() + " " + (int) relative.getY()),
((int) relative.getX() + " " + (int) relative.getY() + " " + (int) relative.getZ()))
: List.of());
completions.addAll(plugin.getPlayerList(false));
return completions.stream()
@@ -134,15 +134,17 @@ public class TpCommand extends Command implements TabProvider {
case 2 -> {
final ArrayList<String> completions = new ArrayList<>();
if (isCoordinate(args, 0)) {
completions.addAll(List.of("~", Integer.toString((int) basePosition.getY())));
completions.addAll(List.of("~ ~", (int) basePosition.getY() + " " + (int) basePosition.getZ()));
completions.addAll(List.of("~", Integer.toString((int) relative.getY())));
completions.addAll(List.of("~ ~", (int) relative.getY() + " " + (int) relative.getZ()));
} else {
completions.addAll(serveCoordinateCompletions
? List.of("~", "~ ~", "~ ~ ~",
Integer.toString((int) basePosition.getX()),
((int) basePosition.getX() + " " + (int) basePosition.getY()),
((int) basePosition.getX() + " " + (int) basePosition.getY() + " " + (int) basePosition.getZ()))
: List.of());
completions.addAll(
serveCoordinateCompletions
? List.of("~", "~ ~", "~ ~ ~",
Integer.toString((int) relative.getX()),
((int) relative.getX() + " " + (int) relative.getY()),
((int) relative.getX() + " " + (int) relative.getY() + " " + (int) relative.getZ()))
: List.of()
);
completions.addAll(plugin.getPlayerList(false));
}
return completions.stream()
@@ -155,13 +157,13 @@ public class TpCommand extends Command implements TabProvider {
if (!serveCoordinateCompletions) {
return completions;
}
completions.addAll(List.of("~", Integer.toString((int) basePosition.getZ())));
completions.addAll(List.of("~", Integer.toString((int) relative.getZ())));
} else if (isCoordinate(args, 1)) {
if (!serveCoordinateCompletions) {
return completions;
}
completions.addAll(List.of("~", Integer.toString((int) basePosition.getY())));
completions.addAll(List.of("~ ~", (int) basePosition.getY() + " " + (int) basePosition.getZ()));
completions.addAll(List.of("~", Integer.toString((int) relative.getY())));
completions.addAll(List.of("~ ~", (int) relative.getY() + " " + (int) relative.getZ()));
}
return completions.stream()
.filter(s -> s.toLowerCase().startsWith(args[2].toLowerCase()))
@@ -173,7 +175,7 @@ public class TpCommand extends Command implements TabProvider {
if (!serveCoordinateCompletions) {
return completions;
}
completions.addAll(List.of("~", Integer.toString((int) basePosition.getZ())));
completions.addAll(List.of("~", Integer.toString((int) relative.getZ())));
}
return completions.stream()
.filter(s -> s.toLowerCase().startsWith(args[3].toLowerCase()))
@@ -28,14 +28,19 @@ import java.util.Optional;
/**
* A command used for responding to tp requests - can either be a /tpaccept or /tpdecline command, controlled by the
* acceptRequestCommand flag
* acceptRequestCommand flag.
*/
public class TpRespondCommand extends InGameCommand implements UserListTabProvider {
private final boolean accept;
protected TpRespondCommand(@NotNull HuskHomes plugin, boolean accept) {
super(accept ? "tpaccept" : "tpdecline", accept ? List.of("tpyes") : List.of("tpno", "tpdeny"), "[player]", plugin);
super(
accept ? "tpaccept" : "tpdecline",
accept ? List.of("tpyes") : List.of("tpno", "tpdeny"),
"[player]",
plugin
);
this.accept = accept;
}
@@ -48,7 +48,8 @@ public class WarpCommand extends SavedPositionCommand<Warp> {
@Override
public void execute(@NotNull CommandUser executor, @NotNull Warp warp, @NotNull String[] args) {
if (plugin.getSettings().doPermissionRestrictWarps()) {
if (!executor.hasPermission(warp.getPermission()) && !executor.hasPermission(Warp.getWildcardPermission())) {
if (!executor.hasPermission(warp.getPermission())
&& !executor.hasPermission(Warp.getWildcardPermission())) {
plugin.getLocales().getLocale("error_no_permission")
.ifPresent(executor::sendMessage);
return;
@@ -70,7 +70,10 @@ public class WarpListCommand extends ListCommand {
plugin.getLocales()
.getRawLocale("warp_list_item",
Locales.escapeText(warp.getName()), warp.getSafeIdentifier(),
Locales.escapeText(plugin.getLocales().wrapText(warp.getMeta().getDescription(), 40)))
Locales.escapeText(plugin.getLocales().wrapText(
warp.getMeta().getDescription(),
40
)))
.orElse(warp.getName())).sorted().collect(Collectors.toList()),
plugin.getLocales()
.getBaseList(plugin.getSettings().getListItemsPerPage())
@@ -32,7 +32,7 @@ import java.util.Map;
import java.util.Optional;
/**
* Loaded locales used by the plugin to display styled messages
* Loaded locales used by the plugin to display styled messages.
*/
@YamlFile(rootedMap = true, header = """
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
@@ -45,7 +45,7 @@ import java.util.Optional;
public class Locales {
/**
* The raw set of locales loaded from yaml
* The raw set of locales loaded from yaml.
*/
public Map<String, String> rawLocales = new HashMap<>();
@@ -54,7 +54,7 @@ public class Locales {
}
/**
* Returns a raw, un-formatted locale loaded from the locales file
* Returns a raw, unformatted locale loaded from the locale file.
*
* @param localeId String identifier of the locale, corresponding to a key in the file
* @return An {@link Optional} containing the locale corresponding to the id, if it exists
@@ -64,12 +64,12 @@ public class Locales {
}
/**
* Returns a raw, un-formatted locale loaded from the locales file, with replacements applied
* <p>
* Note that replacements will not be MineDown-escaped; use {@link #escapeText(String)} to escape replacements
* Returns a raw, unformatted locale loaded from the locale file, with replacements applied.
*
* <p>Note that replacements will not be MineDown-escaped; use {@link #escapeText(String)} to escape replacements
*
* @param localeId String identifier of the locale, corresponding to a key in the file
* @param replacements Ordered array of replacement strings to fill in placeholders with
* @param replacements An ordered array of replacement strings to fill in placeholders with
* @return An {@link Optional} containing the replacement-applied locale corresponding to the id, if it exists
*/
public Optional<String> getRawLocale(@NotNull String localeId, @NotNull String... replacements) {
@@ -77,7 +77,7 @@ public class Locales {
}
/**
* Returns a MineDown-formatted locale from the locales file
* Returns a MineDown-formatted locale from the locale file.
*
* @param localeId String identifier of the locale, corresponding to a key in the file
* @return An {@link Optional} containing the formatted locale corresponding to the id, if it exists
@@ -87,13 +87,13 @@ public class Locales {
}
/**
* Returns a MineDown-formatted locale from the locales file, with replacements applied
* <p>
* Note that replacements will be MineDown-escaped before application
* Returns a MineDown-formatted locale from the locale file, with replacements applied.
*
* <p>Note that replacements will be MineDown-escaped before application
*
* @param localeId String identifier of the locale, corresponding to a key in the file
* @param replacements Ordered array of replacement strings to fill in placeholders with
* @return An {@link Optional} containing the replacement-applied, formatted locale corresponding to the id, if it exists
* @param replacements An ordered array of replacement strings to fill in placeholders with
* @return An {@link Optional} with the replacement-applied, formatted locale corresponding to the id, if it exists
*/
public Optional<MineDown> getLocale(@NotNull String localeId, @NotNull String... replacements) {
return getRawLocale(localeId, Arrays.stream(replacements).map(Locales::escapeText)
@@ -101,10 +101,10 @@ public class Locales {
}
/**
* Apply placeholder replacements to a raw locale
* Apply placeholder replacements to a raw locale.
*
* @param rawLocale The raw, unparsed locale
* @param replacements Ordered array of replacement strings to fill in placeholders with
* @param replacements An ordered array of replacement strings to fill in placeholders with
* @return the raw locale, with inserted placeholders
*/
@NotNull
@@ -119,7 +119,7 @@ public class Locales {
}
/**
* Escape a string from {@link MineDown} formatting for use in a MineDown-formatted locale
* Escape a string from {@link MineDown} formatting for use in a MineDown-formatted locale.
*
* @param string The string to escape
* @return The escaped string
@@ -150,7 +150,7 @@ public class Locales {
}
/**
* Formats a description string, wrapping text on whitespace after 40 characters
* Formats a description string, wrapping text on whitespace after 40 characters.
*
* @param string The string to format
* @return The line-break formatted string, or a String literal {@code "N/A"} if the input string is empty
@@ -189,7 +189,7 @@ public class Locales {
}
/**
* Represents where a locale should be displayed
* Represents where a locale should be displayed.
*/
public enum DisplaySlot {
CHAT,
@@ -26,7 +26,7 @@ import org.jetbrains.annotations.NotNull;
import java.nio.file.Path;
/**
* Represents a server on a proxied network
* Represents a server on a proxied network.
*/
@YamlFile(header = """
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
@@ -39,7 +39,7 @@ import java.nio.file.Path;
public class Server {
/**
* Default server identifier
* Default server identifier.
*/
@NotNull
public static String getDefaultServerName() {
@@ -72,7 +72,7 @@ public class Server {
}
/**
* Proxy-defined name of this server
* Proxy-defined name of this server.
*/
@NotNull
public String getName() {
@@ -55,7 +55,7 @@ public class Settings {
private boolean checkForUpdates = true;
// Database settings
@YamlComment("Type of database to use (MYSQL, SQLITE)")
@YamlComment("Type of database to use (SQLITE, MYSQL or MARIADB)")
@YamlKey("database.type")
private Database.Type databaseType = Database.Type.SQLITE;
@@ -76,9 +76,13 @@ public class Settings {
private String mySqlPassword = "pa55w0rd";
@YamlKey("database.mysql.credentials.parameters")
private String mySqlConnectionParameters = "?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8";
private String mySqlConnectionParameters = "?autoReconnect=true"
+ "&useSSL=false"
+ "&useUnicode=true"
+ "&characterEncoding=UTF-8";
@YamlComment("MYSQL database Hikari connection pool properties. Don't modify this unless you know what you're doing!")
@YamlComment("MYSQL database Hikari connection pool properties. "
+ "Don't modify this unless you know what you're doing!")
@YamlKey("database.mysql.connection_pool.size")
private int mySqlConnectionPoolSize = 12;
@@ -96,15 +100,7 @@ public class Settings {
@YamlComment("Names of tables to use on your database. Don't modify this unless you know what you're doing!")
@YamlKey("database.table_names")
private Map<String, String> tableNames = Map.of(
Database.Table.PLAYER_DATA.name().toLowerCase(), Database.Table.PLAYER_DATA.getDefaultName(),
Database.Table.PLAYER_COOLDOWNS_DATA.name().toLowerCase(), Database.Table.PLAYER_COOLDOWNS_DATA.getDefaultName(),
Database.Table.POSITION_DATA.name().toLowerCase(), Database.Table.POSITION_DATA.getDefaultName(),
Database.Table.SAVED_POSITION_DATA.name().toLowerCase(), Database.Table.SAVED_POSITION_DATA.getDefaultName(),
Database.Table.HOME_DATA.name().toLowerCase(), Database.Table.HOME_DATA.getDefaultName(),
Database.Table.WARP_DATA.name().toLowerCase(), Database.Table.WARP_DATA.getDefaultName(),
Database.Table.TELEPORT_DATA.name().toLowerCase(), Database.Table.TELEPORT_DATA.getDefaultName()
);
private Map<String, String> tableNames = Database.Table.getConfigMap();
// General settings
@@ -112,11 +108,13 @@ public class Settings {
@YamlKey("general.max_homes")
private int maxHomes = 10;
@YamlComment("The maximum public homes a user can create. Override with the huskhomes.max_public_homes.<number> permission.")
@YamlComment("The maximum public homes a user can create. "
+ "Override with the huskhomes.max_public_homes.<number> permission.")
@YamlKey("general.max_public_homes")
private int maxPublicHomes = 10;
@YamlComment("Whether permission limits (i.e. huskhomes.max_homes.<number>) should stack if the user inherits multiple nodes.")
@YamlComment("Whether permission limits (i.e. huskhomes.max_homes.<number>)"
+ "should stack if the user inherits multiple nodes.")
@YamlKey("general.stack_permission_limits")
private boolean stackPermissionLimits = false;
@@ -124,7 +122,7 @@ public class Settings {
@YamlKey("general.permission_restrict_warps")
private boolean permissionRestrictWarps = false;
@YamlComment("Whether running /sethome <name> or /setwarp <name> when a home/warp already exists should overwrite it.")
@YamlComment("Whether running /sethome <name> or /setwarp <name> when a home/warp already exists should overwrite.")
@YamlKey("general.overwrite_existing_homes_warps")
private boolean overwriteExistingHomesWarps = true;
@@ -160,7 +158,7 @@ public class Settings {
@YamlKey("general.back_command_return_by_death")
private boolean backCommandReturnByDeath = true;
@YamlComment("Whether /back should work with other plugins that use the PlayerTeleportEvent (this can cause conflicts)")
@YamlComment("Whether /back should work with other plugins that use the PlayerTeleportEvent (can cause conflicts)")
@YamlKey("general.back_command_save_teleport_event")
private boolean backCommandSaveOnTeleportEvent = false;
@@ -178,12 +176,7 @@ public class Settings {
@YamlComment("Which sound effects to play for various actions")
@YamlKey("general.sound_effects")
private Map<String, String> soundEffects = Map.of(
SoundEffectAction.TELEPORTATION_COMPLETE.name().toLowerCase(), SoundEffectAction.TELEPORTATION_COMPLETE.defaultSoundEffect,
SoundEffectAction.TELEPORTATION_WARMUP.name().toLowerCase(), SoundEffectAction.TELEPORTATION_WARMUP.defaultSoundEffect,
SoundEffectAction.TELEPORTATION_CANCELLED.name().toLowerCase(), SoundEffectAction.TELEPORTATION_CANCELLED.defaultSoundEffect,
SoundEffectAction.TELEPORT_REQUEST_RECEIVED.name().toLowerCase(), SoundEffectAction.TELEPORT_REQUEST_RECEIVED.defaultSoundEffect
);
private Map<String, String> soundEffects = SoundEffectAction.getConfigMap();
@YamlComment("Whether to provide modern, rich TAB suggestions for commands (if available)")
@YamlKey("general.brigadier_tab_completion")
@@ -199,7 +192,8 @@ public class Settings {
@YamlKey("cross_server.messenger_type")
private Broker.Type messageBrokerType = Broker.Type.PLUGIN_MESSAGE;
@YamlComment("Specify a common ID for grouping servers running HuskHomes on your proxy. Don't modify this unless you know what you're doing!")
@YamlComment("Specify a common ID for grouping servers running HuskHomes on your proxy. "
+ "Don't modify this unless you know what you're doing!")
@YamlKey("cross_server.cluster_id")
private String clusterId = "";
@@ -242,7 +236,7 @@ public class Settings {
@YamlKey("rtp.distribution_mean")
private float rtpDistributionMean = 0.75f;
@YamlComment("Standard deviation of the normal distribution used to calculate the distance from the center of the world")
@YamlComment("Standard deviation of the normal distribution for distributing players randomly")
@YamlKey("rtp.distribution_deviation")
private float rtpDistributionStandardDeviation = 2f;
@@ -370,7 +364,7 @@ public class Settings {
@NotNull
public String getTableName(@NotNull Database.Table table) {
return Optional.ofNullable(getTableNames().get(table.name().toLowerCase())).orElse(table.getDefaultName());
return Optional.ofNullable(getTableNames().get(table.name().toLowerCase())).orElse(table.getName());
}
public int getMaxHomes() {
@@ -563,7 +557,7 @@ public class Settings {
return disabledCommands.stream().anyMatch(disabled -> {
final String command = (disabled.startsWith("/") ? disabled.substring(1) : disabled);
return command.equalsIgnoreCase(type.getName())
|| type.getAliases().stream().anyMatch(alias -> alias.equalsIgnoreCase(command));
|| type.getAliases().stream().anyMatch(alias -> alias.equalsIgnoreCase(command));
});
}
@@ -572,18 +566,28 @@ public class Settings {
}
/**
* Represents actions that have a sound effect associated with performing them
* Represents actions that have a sound effect associated with performing them.
*/
public enum SoundEffectAction {
TELEPORTATION_COMPLETE("entity.enderman.teleport"),
TELEPORTATION_WARMUP("block.note_block.banjo"),
TELEPORTATION_CANCELLED("entity.item.break"),
TELEPORT_REQUEST_RECEIVED("entity.experience_orb.pickup");
private final String defaultSoundEffect;
private final String defaultEffect;
SoundEffectAction(@NotNull String defaultSoundEffect) {
this.defaultSoundEffect = defaultSoundEffect;
SoundEffectAction(@NotNull String defaultEffect) {
this.defaultEffect = defaultEffect;
}
@NotNull
public static Map<String, String> getConfigMap() {
return Arrays.stream(values())
.collect(Collectors.toMap(
SoundEffectAction::name,
action -> action.defaultEffect)
);
}
}
}
@@ -29,7 +29,7 @@ import org.jetbrains.annotations.NotNull;
import java.util.UUID;
/**
* Used to store the server spawn location
* Used to store the server spawn location.
*/
@YamlFile(header = """
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
@@ -49,7 +49,7 @@ public class Spawn {
public String worldUuid;
/**
* Returns the {@link Position} of the spawn
* Returns the {@link Position} of the spawn.
*
* @param server The server the spawn is on
* @return The {@link Position} of the spawn
@@ -60,7 +60,7 @@ public class Spawn {
}
/**
* Set the {@link Location} of the spawn
* Set the {@link Location} of the spawn.
*
* @param location The {@link Location} of the spawn
*/
@@ -30,6 +30,7 @@ import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.util.TransactionResolver;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -38,23 +39,20 @@ import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.SQLException;
import java.time.Instant;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.*;
import java.util.stream.Collectors;
/**
* An abstract representation of the plugin database, storing home, warp and player data.
* <p>
* Implemented by different database platforms - MySQL, SQLite, etc. - as configured by the administrator.
*
* <p>Implemented by different database platforms - MySQL, SQLite, etc. - as configured by the administrator.
*/
public abstract class Database {
protected final HuskHomes plugin;
/**
* Loads SQL table creation schema statements from a resource file as a string array
* Loads SQL table creation schema statements from a resource file as a string array.
*
* @param schemaFileName database script resource file to load from
* @return Array of string-formatted table creation schema statements
@@ -68,24 +66,31 @@ public abstract class Database {
}
/**
* Format all table name placeholder strings in a SQL statement
* Format all table name placeholder strings in an SQL statement.
*
* @param sql the SQL statement with unformatted table name placeholders
* @return the formatted statement, with table placeholders replaced with the correct names
*/
protected final String formatStatementTables(@NotNull String sql) {
return sql
.replaceAll("%positions_table%", plugin.getSettings().getTableName(Table.POSITION_DATA))
.replaceAll("%players_table%", plugin.getSettings().getTableName(Table.PLAYER_DATA))
.replaceAll("%cooldowns_table%", plugin.getSettings().getTableName(Table.PLAYER_COOLDOWNS_DATA))
.replaceAll("%teleports_table%", plugin.getSettings().getTableName(Table.TELEPORT_DATA))
.replaceAll("%saved_positions_table%", plugin.getSettings().getTableName(Table.SAVED_POSITION_DATA))
.replaceAll("%homes_table%", plugin.getSettings().getTableName(Table.HOME_DATA))
.replaceAll("%warps_table%", plugin.getSettings().getTableName(Table.WARP_DATA));
.replaceAll("%positions_table%", plugin.getSettings()
.getTableName(Table.POSITION_DATA))
.replaceAll("%players_table%", plugin.getSettings()
.getTableName(Table.PLAYER_DATA))
.replaceAll("%cooldowns_table%", plugin.getSettings()
.getTableName(Table.PLAYER_COOLDOWNS_DATA))
.replaceAll("%teleports_table%", plugin.getSettings()
.getTableName(Table.TELEPORT_DATA))
.replaceAll("%saved_positions_table%", plugin.getSettings()
.getTableName(Table.SAVED_POSITION_DATA))
.replaceAll("%homes_table%", plugin.getSettings()
.getTableName(Table.HOME_DATA))
.replaceAll("%warps_table%", plugin.getSettings()
.getTableName(Table.WARP_DATA));
}
/**
* Create a database instance, pulling table names from the plugin config
* Create a database instance, pulling table names from the plugin config.
*
* @param plugin the implementing plugin instance
*/
@@ -99,7 +104,7 @@ public abstract class Database {
public abstract void initialize() throws IllegalStateException;
/**
* <b>(Internal use only)</b> - Sets a position to the position table in the database
* <b>(Internal use only)</b> - Sets a position to the position table in the database.
*
* @param position The {@link Position} to set
* @param connection SQL connection
@@ -109,44 +114,50 @@ public abstract class Database {
protected abstract int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException;
/**
* <b>(Internal use only)</b> - Updates position data
* <b>(Internal use only)</b> - Updates position data.
*
* @param positionId ID of the position to update
* @param position the Position.at
* @param connection SQL connection
* @throws SQLException if an SQL exception occurs doing this
*/
protected abstract void updatePosition(int positionId, @NotNull Position position, @NotNull Connection connection) throws SQLException;
@ApiStatus.Internal
protected abstract void updatePosition(int positionId, @NotNull Position position,
@NotNull Connection connection) throws SQLException;
/**
* <b>(Internal use only)</b> - Sets a {@link SavedPosition} to the database
* <b>(Internal use only)</b> - Sets a {@link SavedPosition} to the database.
*
* @param position The {@link SavedPosition} to set
* @param connection SQL connection
* @return The newly inserted row ID
* @throws SQLException if an SQL exception occurs doing this
*/
protected abstract int setSavedPosition(@NotNull SavedPosition position, @NotNull Connection connection) throws SQLException;
@ApiStatus.Internal
protected abstract int setSavedPosition(@NotNull SavedPosition position,
@NotNull Connection connection) throws SQLException;
/**
* <b>(Internal use only)</b> - Updates a saved position metadata
* <b>(Internal use only)</b> - Updates a saved position metadata.
*
* @param savedPositionId ID of the metadata to update
* @param savedPosition the new saved position
* @param connection SQL connection
* @throws SQLException if an SQL exception occurs doing this
*/
protected abstract void updateSavedPosition(int savedPositionId, @NotNull SavedPosition savedPosition, @NotNull Connection connection) throws SQLException;
@ApiStatus.Internal
protected abstract void updateSavedPosition(int savedPositionId, @NotNull SavedPosition savedPosition,
@NotNull Connection connection) throws SQLException;
/**
* Ensure a {@link User} has a {@link SavedUser} entry in the database and that their username is up-to-date
* Ensure a {@link User} has a {@link SavedUser} entry in the database and that their username is up-to-date.
*
* @param user The {@link User} to ensure
*/
public abstract void ensureUser(@NotNull User user);
/**
* Get {@link SavedUser} for a user by their Minecraft username (<i>case-insensitive</i>)
* Get {@link SavedUser} for a user by their Minecraft username (<i>case-insensitive</i>).
*
* @param name Username of the {@link SavedUser} to get (<i>case-insensitive</i>)
* @return An optional with the {@link SavedUser} present if they exist
@@ -154,7 +165,7 @@ public abstract class Database {
public abstract Optional<SavedUser> getUserDataByName(@NotNull String name);
/**
* Get {@link SavedUser} for a user by their Minecraft account {@link UUID}
* Get {@link SavedUser} for a user by their Minecraft account {@link UUID}.
*
* @param uuid Minecraft account {@link UUID} of the {@link SavedUser} to get
* @return An optional with the {@link SavedUser} present if they exist
@@ -162,23 +173,24 @@ public abstract class Database {
public abstract Optional<SavedUser> getUserData(@NotNull UUID uuid);
/**
* Get the currently active cooldown of a {@link User} for a specific {@link TransactionResolver.Action}
* Get the currently active cooldown of a {@link User} for a specific {@link TransactionResolver.Action}.
*
* @return An optional containing the {@link Instant} the cooldown expires at, or empty if the {@link User} has no cooldown
* @return An optional with the {@link Instant} the cooldown expires, or empty if the {@link User} has no cooldown
*/
public abstract Optional<Instant> getCooldown(@NotNull TransactionResolver.Action action, @NotNull User user);
/**
* Set the cooldown of a {@link User} for a specific {@link TransactionResolver.Action}
* Set the cooldown of a {@link User} for a specific {@link TransactionResolver.Action}.
*
* @param action The {@link TransactionResolver.Action} to set the cooldown for
* @param user The {@link User} to set the cooldown for
* @param cooldownExpiry The {@link Instant} the cooldown expires at
*/
public abstract void setCooldown(@NotNull TransactionResolver.Action action, @NotNull User user, @NotNull Instant cooldownExpiry);
public abstract void setCooldown(@NotNull TransactionResolver.Action action, @NotNull User user,
@NotNull Instant cooldownExpiry);
/**
* Remove the cooldown of a {@link User} for a specific {@link TransactionResolver.Action}
* Remove the cooldown of a {@link User} for a specific {@link TransactionResolver.Action}.
*
* @param action The {@link TransactionResolver.Action} to remove the cooldown for
* @param user The {@link User} to remove the cooldown for
@@ -186,7 +198,7 @@ public abstract class Database {
public abstract void removeCooldown(@NotNull TransactionResolver.Action action, @NotNull User user);
/**
* Get a list of {@link Home}s set by a {@link User}
* Get a list of {@link Home}s set by a {@link User}.
*
* @param user {@link User} to get the homes of
* @return A future returning void when complete
@@ -194,14 +206,14 @@ public abstract class Database {
public abstract List<Home> getHomes(@NotNull User user);
/**
* Get a list of all {@link Warp}s that have been set
* Get a list of all {@link Warp}s that have been set.
*
* @return A list containing all {@link Warp}s
*/
public abstract List<Warp> getWarps();
/**
* Get a list of publicly-set {@link Warp}s on <i>this {@link Server}</i>
* Get a list of publicly-set {@link Warp}s on <i>this {@link Server server}</i>.
*
* @param plugin The plugin instance
* @return A list containing all {@link Warp}s set on this server
@@ -214,14 +226,14 @@ public abstract class Database {
}
/**
* Get a list of all publicly-set {@link Home}s
* Get a list of all publicly-set {@link Home}s.
*
* @return A list containing all publicly-set {@link Home}s
*/
public abstract List<Home> getPublicHomes();
/**
* Get a list of publicly-set {@link Home}s on <i>this {@link Server}</i>
* Get a list of publicly-set {@link Home}s on <i>this {@link Server server}</i>.
*
* @param plugin The plugin instance
* @return A list containing all publicly-set {@link Home}s on this server
@@ -234,19 +246,19 @@ public abstract class Database {
}
/**
* Get a {@link Home} with the given name, set by the given {@link User}
* Get a {@link Home} with the given name, set by the given {@link User}.
*
* @param user The {@link User} who set the home
* @param homeName The name of the home to get
* @return An optional with the {@link Home} present if it exists
* @apiNote Whether the name lookup query is case-insensitive is determined by the {@code general.case_insensitive_names} setting
* @apiNote Whether lookup is case-sensitive is determined by the {@code general.case_insensitive_names} setting
*/
public final Optional<Home> getHome(@NotNull User user, @NotNull String homeName) {
return this.getHome(user, homeName, plugin.getSettings().caseInsensitiveNames());
}
/**
* Get a {@link Home} with the given name, set by the given {@link User}
* Get a {@link Home} with the given name, set by the given {@link User}.
*
* @param user The {@link User} who set the home
* @param homeName The name of the home to get
@@ -256,7 +268,7 @@ public abstract class Database {
public abstract Optional<Home> getHome(@NotNull User user, @NotNull String homeName, boolean caseInsensitive);
/**
* Get a {@link Home} by its unique id
* Get a {@link Home} by its {@link UUID unique ID}.
*
* @param uuid the {@link UUID} of the home to get
* @return An optional with the {@link Home} present if it exists
@@ -264,18 +276,18 @@ public abstract class Database {
public abstract Optional<Home> getHome(@NotNull UUID uuid);
/**
* Get a {@link Warp} with the given name
* Get a {@link Warp} with the given name.
*
* @param warpName The name of the warp to get
* @return An optional with the {@link Warp} present if it exists
* @apiNote Whether the name lookup query is case-insensitive is determined by the {@code general.case_insensitive_names} setting
* @apiNote Whether lookup is case-insensitive is determined by the {@code general.case_insensitive_names} setting
*/
public final Optional<Warp> getWarp(@NotNull String warpName) {
return getWarp(warpName, plugin.getSettings().caseInsensitiveNames());
}
/**
* Get a {@link Warp} with the given name
* Get a {@link Warp} with the given name.
*
* @param warpName The name of the warp to get
* @param caseInsensitive Whether the search should be case-insensitive
@@ -284,7 +296,7 @@ public abstract class Database {
public abstract Optional<Warp> getWarp(@NotNull String warpName, boolean caseInsensitive);
/**
* Get a {@link Warp} by its unique id
* Get a {@link Warp} by its {@link UUID unique ID}.
*
* @param uuid the {@link UUID} of the warp to get
* @return An optional with the {@link Warp} present if it exists
@@ -292,7 +304,7 @@ public abstract class Database {
public abstract Optional<Warp> getWarp(@NotNull UUID uuid);
/**
* Get the current {@link Teleport} being executed by the specified {@link OnlineUser}
* Get the current {@link Teleport} being executed by the specified {@link OnlineUser}.
*
* @param onlineUser The {@link OnlineUser} to check
* @return An optional with the {@link Teleport} present if they are teleporting cross-server
@@ -300,23 +312,23 @@ public abstract class Database {
public abstract Optional<Teleport> getCurrentTeleport(@NotNull OnlineUser onlineUser);
/**
* Updates a user in the database with new {@link SavedUser}
* Updates a user in the database with new {@link SavedUser}.
*
* @param savedUser The {@link SavedUser} to update
*/
public abstract void updateUserData(@NotNull SavedUser savedUser);
/**
* Sets or clears the current {@link Teleport} being executed by a {@link User}
* Sets or clears the current {@link Teleport} being executed by a {@link User}.
*
* @param user The {@link User} to set the current teleport of.
* Pass as {@code null} to clear the player's current teleport.<p>
* Pass as {@code null} to clear the player's current teleport
* @param teleport The {@link Teleport} to set as their current cross-server teleport
*/
public abstract void setCurrentTeleport(@NotNull User user, @Nullable Teleport teleport);
/**
* Clears the current {@link Teleport} being executed by a {@link User}
* Clears the current {@link Teleport} being executed by a {@link User}.
*
* @param user The {@link User} to clear the current teleport of
*/
@@ -325,7 +337,7 @@ public abstract class Database {
}
/**
* Get the last teleport {@link Position} of a specified {@link User}
* Get the last teleport {@link Position} of a specified {@link User}.
*
* @param user The {@link User} to check
* @return An optional with the {@link Position} present if it has been set
@@ -333,7 +345,7 @@ public abstract class Database {
public abstract Optional<Position> getLastPosition(@NotNull User user);
/**
* Sets the last teleport {@link Position} of a {@link User}
* Sets the last teleport {@link Position} of a {@link User}.
*
* @param user The {@link User} to set the last position of
* @param position The {@link Position} to set as their last position
@@ -341,7 +353,7 @@ public abstract class Database {
public abstract void setLastPosition(@NotNull User user, @NotNull Position position);
/**
* Get the offline {@link Position} of a specified {@link User}
* Get the offline {@link Position} of a specified {@link User}.
*
* @param user The {@link User} to check
* @return An optional with the {@link Position} present if it has been set
@@ -349,7 +361,7 @@ public abstract class Database {
public abstract Optional<Position> getOfflinePosition(@NotNull User user);
/**
* Sets the offline {@link Position} of a {@link User}
* Sets the offline {@link Position} of a {@link User}.
*
* @param user The {@link User} to set the offline position of
* @param position The {@link Position} to set as their offline position
@@ -357,7 +369,7 @@ public abstract class Database {
public abstract void setOfflinePosition(@NotNull User user, @NotNull Position position);
/**
* Get the respawn {@link Position} of a specified {@link User}
* Get the respawn {@link Position} of a specified {@link User}.
*
* @param user The {@link User} to check
* @return An optional with the {@link Position} present if it has been set
@@ -365,11 +377,11 @@ public abstract class Database {
public abstract Optional<Position> getRespawnPosition(@NotNull User user);
/**
* Sets or clears the respawn {@link Position} of a {@link User}
* Sets or clears the respawn {@link Position} of a {@link User}.
*
* @param user The {@link User} to set the respawn position of
* @param position The {@link Position} to set as their respawn position
* Pass as {@code null} to clear the player's current respawn position.<p>
* Pass as {@code null} to clear the player's current respawn position.
*/
public abstract void setRespawnPosition(@NotNull User user, @Nullable Position position);
@@ -410,23 +422,24 @@ public abstract class Database {
public abstract void deleteWarp(@NotNull UUID uuid);
/**
* Deletes all {@link Warp}s set on the database table
* Deletes all {@link Warp}s set on the database table.
*
* @return An integer; the number of deleted warps
*/
public abstract int deleteAllWarps();
/**
* Close any remaining connection to the database source
* Close any remaining connection to the database source.
*/
public abstract void terminate();
/**
* Identifies types of databases
* Identifies types of databases.
*/
public enum Type {
MYSQL("MySQL"),
MARIADB("MariaDB"),
SQLITE("SQLite");
private final String displayName;
@@ -442,7 +455,7 @@ public abstract class Database {
}
/**
* Represents the names of tables in the database
* Represents the names of tables in the database.
*/
public enum Table {
PLAYER_DATA("huskhomes_users"),
@@ -460,8 +473,18 @@ public abstract class Database {
}
@NotNull
public String getDefaultName() {
public String getName() {
return defaultName;
}
@NotNull
public static Map<String, String> getConfigMap() {
return Arrays.stream(values())
.collect(Collectors.toMap(
Table::name,
action -> action.defaultName
));
}
}
}
@@ -38,7 +38,7 @@ import java.util.*;
import java.util.logging.Level;
/**
* A MySQL implementation of the plugin {@link Database}
* A MySQL implementation of the plugin {@link Database}.
*/
@SuppressWarnings("DuplicatedCode")
public class MySqlDatabase extends Database {
@@ -51,7 +51,7 @@ public class MySqlDatabase extends Database {
}
/**
* Fetch the auto-closeable connection from the hikariDataSource
* Fetch the auto-closeable connection from the hikariDataSource.
*
* @return The {@link Connection} to the MySQL database
* @throws SQLException if the connection fails for some reason
@@ -64,13 +64,15 @@ public class MySqlDatabase extends Database {
public void initialize() throws IllegalStateException {
// Initialize the Hikari pooled connection
dataSource = new HikariDataSource();
dataSource.setJdbcUrl("jdbc:mysql://" +
plugin.getSettings().getMySqlHost() +
":" +
plugin.getSettings().getMySqlPort() +
"/" +
plugin.getSettings().getMySqlDatabase() +
plugin.getSettings().getMySqlConnectionParameters());
dataSource.setJdbcUrl("jdbc:" + (plugin.getSettings().getDatabaseType() == Type.MARIADB ? "mariadb" : "mysql")
+ "://"
+ plugin.getSettings().getMySqlHost()
+ ":"
+ plugin.getSettings().getMySqlPort()
+ "/"
+ plugin.getSettings().getMySqlDatabase()
+ plugin.getSettings().getMySqlConnectionParameters()
);
// Authenticate with the database
dataSource.setUsername(plugin.getSettings().getMySqlUsername());
@@ -85,19 +87,24 @@ public class MySqlDatabase extends Database {
dataSource.setPoolName(DATA_POOL_NAME);
// Set additional connection pool properties
dataSource.setDataSourceProperties(new Properties() {{
put("cachePrepStmts", "true");
put("prepStmtCacheSize", "250");
put("prepStmtCacheSqlLimit", "2048");
put("useServerPrepStmts", "true");
put("useLocalSessionState", "true");
put("useLocalTransactionState", "true");
put("rewriteBatchedStatements", "true");
put("cacheResultSetMetadata", "true");
put("cacheServerConfiguration", "true");
put("elideSetAutoCommits", "true");
put("maintainTimeStats", "false");
}});
final Properties properties = new Properties();
properties.putAll(
Map.of("cachePrepStmts", "true",
"prepStmtCacheSize", "250",
"prepStmtCacheSqlLimit", "2048",
"useServerPrepStmts", "true",
"useLocalSessionState", "true",
"useLocalTransactionState", "true"
));
properties.putAll(
Map.of(
"rewriteBatchedStatements", "true",
"cacheResultSetMetadata", "true",
"cacheServerConfiguration", "true",
"elideSetAutoCommits", "true",
"maintainTimeStats", "false")
);
dataSource.setDataSourceProperties(properties);
// Prepare database schema; make tables if they don't exist
try (Connection connection = dataSource.getConnection()) {
@@ -107,20 +114,22 @@ public class MySqlDatabase extends Database {
statement.execute(tableCreationStatement);
}
} catch (SQLException e) {
throw new IllegalStateException("Failed to create database tables. Please ensure you are running MySQL v8.0+ " +
"and that your connecting user account has privileges to create tables.", e);
throw new IllegalStateException("Failed to create database tables. Make sure you're running MySQL v8.0+"
+ "and that your connecting user account has privileges to create tables.", e);
}
} catch (SQLException | IOException e) {
throw new IllegalStateException("Failed to establish a connection to the MySQL database. " +
"Please check the supplied database credentials in the config file", e);
throw new IllegalStateException("Failed to establish a connection to the MySQL database. "
+ "Please check the supplied database credentials in the config file", e);
}
}
@Override
protected int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
INSERT INTO `%positions_table%` (`x`,`y`,`z`,`yaw`,`pitch`,`world_name`,`world_uuid`,`server_name`)
VALUES (?,?,?,?,?,?,?,?);"""),
INSERT INTO `%positions_table%`
(`x`,`y`,`z`,`yaw`,`pitch`,`world_name`,`world_uuid`,`server_name`)
VALUES
(?,?,?,?,?,?,?,?);"""),
Statement.RETURN_GENERATED_KEYS)) {
statement.setDouble(1, position.getX());
@@ -142,7 +151,8 @@ public class MySqlDatabase extends Database {
}
@Override
protected void updatePosition(int positionId, @NotNull Position position, @NotNull Connection connection) throws SQLException {
protected void updatePosition(int positionId, @NotNull Position position,
@NotNull Connection connection) throws SQLException {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
UPDATE `%positions_table%`
SET `x`=?,
@@ -168,10 +178,13 @@ public class MySqlDatabase extends Database {
}
@Override
protected int setSavedPosition(@NotNull SavedPosition position, @NotNull Connection connection) throws SQLException {
protected int setSavedPosition(@NotNull SavedPosition position,
@NotNull Connection connection) throws SQLException {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
INSERT INTO `%saved_positions_table%` (`position_id`, `name`, `description`, `tags`, `timestamp`)
VALUES (?,?,?,?,?);"""),
INSERT INTO `%saved_positions_table%`
(`position_id`, `name`, `description`, `tags`, `timestamp`)
VALUES
(?,?,?,?,?);"""),
Statement.RETURN_GENERATED_KEYS)) {
statement.setInt(1, setPosition(position, connection));
@@ -190,7 +203,8 @@ public class MySqlDatabase extends Database {
}
@Override
protected void updateSavedPosition(int savedPositionId, @NotNull SavedPosition position, @NotNull Connection connection) throws SQLException {
protected void updateSavedPosition(int savedPositionId, @NotNull SavedPosition position,
@NotNull Connection connection) throws SQLException {
try (PreparedStatement selectStatement = connection.prepareStatement(formatStatementTables("""
SELECT `position_id`
FROM `%saved_positions_table%`
@@ -220,7 +234,8 @@ public class MySqlDatabase extends Database {
@Override
public void ensureUser(@NotNull User onlineUser) {
getUserData(onlineUser.getUuid()).ifPresentOrElse(existingUserData -> {
getUserData(onlineUser.getUuid()).ifPresentOrElse(
existingUserData -> {
if (!existingUserData.getUsername().equals(onlineUser.getUsername())) {
// Update a player's name if it has changed in the database
try (Connection connection = getConnection()) {
@@ -233,7 +248,9 @@ public class MySqlDatabase extends Database {
statement.setString(2, existingUserData.getUserUuid().toString());
statement.executeUpdate();
}
plugin.log(Level.INFO, "Updated " + onlineUser.getUsername() + "'s name in the database (" + existingUserData.getUsername() + " -> " + onlineUser.getUsername() + ")");
plugin.log(Level.INFO, "Updated " + onlineUser.getUsername()
+ "'s name in the database (" + existingUserData.getUsername()
+ " -> " + onlineUser.getUsername() + ")");
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to update a player's name on the database", e);
}
@@ -331,7 +348,8 @@ public class MySqlDatabase extends Database {
}
@Override
public void setCooldown(@NotNull TransactionResolver.Action action, @NotNull User user, @NotNull Instant cooldownExpiry) {
public void setCooldown(@NotNull TransactionResolver.Action action, @NotNull User user,
@NotNull Instant cooldownExpiry) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
INSERT INTO `%cooldowns_table%` (`player_uuid`, `type`, `start_timestamp`, `end_timestamp`)
@@ -368,11 +386,15 @@ public class MySqlDatabase extends Database {
final List<Home> userHomes = new ArrayList<>();
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public`
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `name`, `description`, `tags`,
`timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public`
FROM `%homes_table%`
INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
INNER JOIN `%saved_positions_table%`
ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%`
ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
WHERE `owner_uuid`=?
ORDER BY `name`;"""))) {
@@ -408,10 +430,13 @@ public class MySqlDatabase extends Database {
final List<Warp> warps = new ArrayList<>();
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`,
`x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
FROM `%warps_table%`
INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%saved_positions_table%`
ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
ORDER BY `name`;"""))) {
final ResultSet resultSet = statement.executeQuery();
@@ -442,14 +467,18 @@ public class MySqlDatabase extends Database {
final List<Home> userHomes = new ArrayList<>();
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public`
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`,
`description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`,
`server_name`, `public`
FROM `%homes_table%`
INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
INNER JOIN `%saved_positions_table%`
ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%`
ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
WHERE `public`=true
ORDER BY `name`;"""))) {
final ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
userHomes.add(Home.from(resultSet.getDouble("x"),
@@ -480,11 +509,16 @@ public class MySqlDatabase extends Database {
public Optional<Home> getHome(@NotNull User user, @NotNull String homeName, boolean caseInsensitive) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public`
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`,
`name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`,
`world_uuid`, `server_name`, `public`
FROM `%homes_table%`
INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
INNER JOIN `%saved_positions_table%`
ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%`
ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
WHERE `owner_uuid`=?
AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) {
statement.setString(1, user.getUuid().toString());
@@ -521,11 +555,16 @@ public class MySqlDatabase extends Database {
public Optional<Home> getHome(@NotNull UUID uuid) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public`
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`,
`name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`,
`world_uuid`, `server_name`, `public`
FROM `%homes_table%`
INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
INNER JOIN `%saved_positions_table%`
ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%`
ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
WHERE `%homes_table%`.`uuid`=?;"""))) {
statement.setString(1, uuid.toString());
@@ -559,10 +598,13 @@ public class MySqlDatabase extends Database {
public Optional<Warp> getWarp(@NotNull String warpName, boolean caseInsensitive) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`,
`x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
FROM `%warps_table%`
INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%saved_positions_table%`
ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) {
statement.setBoolean(1, caseInsensitive);
statement.setString(2, warpName);
@@ -595,10 +637,13 @@ public class MySqlDatabase extends Database {
public Optional<Warp> getWarp(@NotNull UUID uuid) {
try (Connection connection = getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`,
`x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
FROM `%warps_table%`
INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%saved_positions_table%`
ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
WHERE `%warps_table%`.uuid=?;"""))) {
statement.setString(1, uuid.toString());
@@ -675,7 +720,7 @@ public class MySqlDatabase extends Database {
statement.executeUpdate();
}
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to update user data for " + savedUser.getUsername() + " on the database", e);
plugin.log(Level.SEVERE, "Failed to update user data for " + savedUser.getUsername(), e);
}
}
@@ -39,23 +39,23 @@ import java.util.*;
import java.util.logging.Level;
/**
* An SQLite implementation of the plugin {@link Database}
* An SQLite implementation of the plugin {@link Database}.
*/
@SuppressWarnings("DuplicatedCode")
public class SqLiteDatabase extends Database {
/**
* Path to the SQLite HuskHomesData.db file
* Path to the SQLite HuskHomesData.db file.
*/
private final File databaseFile;
/**
* The name of the database file
* The name of the database file.
*/
private static final String DATABASE_FILE_NAME = "HuskHomesData.db";
/**
* The persistent SQLite database connection
* The persistent SQLite database connection.
*/
private Connection connection;
@@ -91,7 +91,9 @@ public class SqLiteDatabase extends Database {
config.setSynchronous(SQLiteConfig.SynchronousMode.FULL);
// Establish the connection
connection = DriverManager.getConnection("jdbc:sqlite:" + databaseFile.getAbsolutePath(), config.toProperties());
connection = DriverManager.getConnection(
"jdbc:sqlite:" + databaseFile.getAbsolutePath(), config.toProperties()
);
} catch (IOException e) {
plugin.log(Level.SEVERE, "An exception occurred creating the database file", e);
} catch (SQLException e) {
@@ -123,8 +125,10 @@ public class SqLiteDatabase extends Database {
@Override
protected int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
INSERT INTO `%positions_table%` (`x`,`y`,`z`,`yaw`,`pitch`,`world_name`,`world_uuid`,`server_name`)
VALUES (?,?,?,?,?,?,?,?);"""),
INSERT INTO `%positions_table%`
(`x`,`y`,`z`,`yaw`,`pitch`,`world_name`,`world_uuid`,`server_name`)
VALUES
(?,?,?,?,?,?,?,?);"""),
Statement.RETURN_GENERATED_KEYS)) {
statement.setDouble(1, position.getX());
@@ -148,7 +152,8 @@ public class SqLiteDatabase extends Database {
}
@Override
protected void updatePosition(int positionId, @NotNull Position position, @NotNull Connection connection) throws SQLException {
protected void updatePosition(int positionId, @NotNull Position position,
@NotNull Connection connection) throws SQLException {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
UPDATE `%positions_table%`
SET `x`=?,
@@ -174,10 +179,13 @@ public class SqLiteDatabase extends Database {
}
@Override
protected int setSavedPosition(@NotNull SavedPosition position, @NotNull Connection connection) throws SQLException {
protected int setSavedPosition(@NotNull SavedPosition position,
@NotNull Connection connection) throws SQLException {
try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
INSERT INTO `%saved_positions_table%` (`position_id`, `name`, `description`, `tags`, `timestamp`)
VALUES (?,?,?,?,?);"""),
INSERT INTO `%saved_positions_table%`
(`position_id`, `name`, `description`, `tags`, `timestamp`)
VALUES
(?,?,?,?,?);"""),
Statement.RETURN_GENERATED_KEYS)) {
statement.setInt(1, setPosition(position, connection));
@@ -198,7 +206,8 @@ public class SqLiteDatabase extends Database {
}
@Override
protected void updateSavedPosition(int savedPositionId, @NotNull SavedPosition position, @NotNull Connection connection) throws SQLException {
protected void updateSavedPosition(int savedPositionId, @NotNull SavedPosition position,
@NotNull Connection connection) throws SQLException {
try (PreparedStatement selectStatement = connection.prepareStatement(formatStatementTables("""
SELECT `position_id`
FROM `%saved_positions_table%`
@@ -228,7 +237,8 @@ public class SqLiteDatabase extends Database {
@Override
public void ensureUser(@NotNull User onlineUser) {
getUserData(onlineUser.getUuid()).ifPresentOrElse(existingUser -> {
getUserData(onlineUser.getUuid()).ifPresentOrElse(
existingUser -> {
if (!existingUser.getUsername().equals(onlineUser.getUsername())) {
// Update a player's name if it has changed in the database
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
@@ -239,7 +249,9 @@ public class SqLiteDatabase extends Database {
statement.setString(1, onlineUser.getUsername());
statement.setString(2, existingUser.getUserUuid().toString());
statement.executeUpdate();
plugin.log(Level.INFO, "Updated " + onlineUser.getUsername() + "'s name in the database (" + existingUser.getUsername() + " -> " + onlineUser.getUsername() + ")");
plugin.log(Level.INFO, "Updated " + onlineUser.getUsername()
+ "'s name in the database (" + existingUser.getUsername()
+ " -> " + onlineUser.getUsername() + ")");
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to update a player's name on the database", e);
}
@@ -343,7 +355,8 @@ public class SqLiteDatabase extends Database {
}
@Override
public void setCooldown(@NotNull TransactionResolver.Action action, @NotNull User user, @NotNull Instant cooldownExpiry) {
public void setCooldown(@NotNull TransactionResolver.Action action, @NotNull User user,
@NotNull Instant cooldownExpiry) {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
INSERT INTO `%cooldowns_table%` (`player_uuid`, `type`, `start_timestamp`, `end_timestamp`)
VALUES (?,?,?,?);"""))) {
@@ -361,11 +374,15 @@ public class SqLiteDatabase extends Database {
public List<Home> getHomes(@NotNull User user) {
final List<Home> userHomes = new ArrayList<>();
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public`
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `name`, `description`, `tags`, `timestamp`,
`x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public`
FROM `%homes_table%`
INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
INNER JOIN `%saved_positions_table%`
ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%`
ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
WHERE `owner_uuid`=?
ORDER BY `name`;"""))) {
statement.setString(1, user.getUuid().toString());
@@ -399,12 +416,14 @@ public class SqLiteDatabase extends Database {
public List<Warp> getWarps() {
final List<Warp> warps = new ArrayList<>();
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`,
`x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
FROM `%warps_table%`
INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%saved_positions_table%`
ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
ORDER BY `name`;"""))) {
final ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
warps.add(Warp.from(resultSet.getDouble("x"),
@@ -431,14 +450,18 @@ public class SqLiteDatabase extends Database {
public List<Home> getPublicHomes() {
final List<Home> userHomes = new ArrayList<>();
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public`
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`,
`name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`,
`world_uuid`, `server_name`, `public`
FROM `%homes_table%`
INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
INNER JOIN `%saved_positions_table%`
ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%`
ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
WHERE `public`=true
ORDER BY `name`;"""))) {
final ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
userHomes.add(Home.from(resultSet.getDouble("x"),
@@ -468,11 +491,16 @@ public class SqLiteDatabase extends Database {
@Override
public Optional<Home> getHome(@NotNull User user, @NotNull String homeName, boolean caseInsensitive) {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public`
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`,
`name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`,
`world_uuid`, `server_name`, `public`
FROM `%homes_table%`
INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
INNER JOIN `%saved_positions_table%`
ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%`
ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
WHERE `owner_uuid`=?
AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) {
statement.setString(1, user.getUuid().toString());
@@ -507,11 +535,16 @@ public class SqLiteDatabase extends Database {
@Override
public Optional<Home> getHome(@NotNull UUID uuid) {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public`
SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`,
`name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`,
`world_uuid`, `server_name`, `public`
FROM `%homes_table%`
INNER JOIN `%saved_positions_table%` ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%` ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
INNER JOIN `%saved_positions_table%`
ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%players_table%`
ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
WHERE `%homes_table%`.`uuid`=?;"""))) {
statement.setString(1, uuid.toString());
@@ -543,10 +576,13 @@ public class SqLiteDatabase extends Database {
@Override
public Optional<Warp> getWarp(@NotNull String warpName, boolean caseInsensitive) {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`,
`x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
FROM `%warps_table%`
INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%saved_positions_table%`
ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) {
statement.setBoolean(1, caseInsensitive);
statement.setString(2, warpName);
@@ -577,10 +613,13 @@ public class SqLiteDatabase extends Database {
@Override
public Optional<Warp> getWarp(@NotNull UUID uuid) {
try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`,
`x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`
FROM `%warps_table%`
INNER JOIN `%saved_positions_table%` ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%` ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
INNER JOIN `%saved_positions_table%`
ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id`
INNER JOIN `%positions_table%`
ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
WHERE `%warps_table%`.uuid=?;"""))) {
statement.setString(1, uuid.toString());
@@ -652,7 +691,7 @@ public class SqLiteDatabase extends Database {
statement.setString(3, savedUser.getUserUuid().toString());
statement.executeUpdate();
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to update user data for " + savedUser.getUsername() + " on the database", e);
plugin.log(Level.SEVERE, "Failed to update user data for " + savedUser.getUsername(), e);
}
}
@@ -20,21 +20,21 @@
package net.william278.huskhomes.event;
/**
* Base interface for a cancellable event
* Base interface for a cancellable event.
*/
public interface Cancellable extends Event {
/**
* Set whether the event should be canceled
* Set whether the event should be canceled.
*
* @param cancelled {@code true} if the event should be canceled
*/
void setCancelled(boolean cancelled);
/**
* Check whether the event is cancelled
* Check whether the event is canceled.
*
* @return {@code true} if the event is cancelled
* @return {@code true} if the event is canceled
*/
boolean isCancelled();
@@ -20,7 +20,7 @@
package net.william278.huskhomes.event;
/**
* Interface for an event fired by HuskHomes
* Interface for an event fired by HuskHomes.
*/
public interface Event {
}
@@ -36,12 +36,12 @@ import java.util.List;
import java.util.function.Consumer;
/**
* An abstract dispatcher of events
* An abstract dispatcher of events.
*/
public interface EventDispatcher {
/**
* Fire an event synchronously, then run a callback asynchronously
* Fire an event synchronously, then run a callback asynchronously.
*
* @param event The event to fire
* @param callback The callback to run after the event has been fired
@@ -56,42 +56,62 @@ public interface EventDispatcher {
}
/**
* Fire an event on this thread, and return whether the event was canceled
* Fire an event on this thread, and return whether the event was canceled.
*
* @param event The event to fire
* @param <T> The type of event to fire
* @return Whether the event was canceled
*/
<T extends Event> boolean fireIsCancelled(@NotNull T event);
@NotNull
ITeleportEvent getTeleportEvent(@NotNull Teleport teleport);
@NotNull
ITeleportWarmupEvent getTeleportWarmupEvent(@NotNull TimedTeleport teleport, int duration);
@NotNull
ISendTeleportRequestEvent getSendTeleportRequestEvent(@NotNull OnlineUser sender, @NotNull TeleportRequest request);
IReceiveTeleportRequestEvent getReceiveTeleportRequestEvent(@NotNull OnlineUser recipient, @NotNull TeleportRequest request);
@NotNull
IReceiveTeleportRequestEvent getReceiveTeleportRequestEvent(@NotNull OnlineUser recipient,
@NotNull TeleportRequest request);
IReplyTeleportRequestEvent getReplyTeleportRequestEvent(@NotNull OnlineUser recipient, @NotNull TeleportRequest request);
@NotNull
IReplyTeleportRequestEvent getReplyTeleportRequestEvent(@NotNull OnlineUser recipient,
@NotNull TeleportRequest request);
IHomeCreateEvent getHomeCreateEvent(@NotNull User owner, @NotNull String name, @NotNull Position position, @NotNull CommandUser creator);
@NotNull
IHomeCreateEvent getHomeCreateEvent(@NotNull User owner, @NotNull String name, @NotNull Position position,
@NotNull CommandUser creator);
@NotNull
IHomeEditEvent getHomeEditEvent(@NotNull Home home, @NotNull CommandUser editor);
@NotNull
IHomeDeleteEvent getHomeDeleteEvent(@NotNull Home home, @NotNull CommandUser deleter);
@NotNull
IWarpCreateEvent getWarpCreateEvent(@NotNull String name, @NotNull Position position, @NotNull CommandUser creator);
@NotNull
IWarpEditEvent getWarpEditEvent(@NotNull Warp warp, @NotNull CommandUser editor);
@NotNull
IWarpDeleteEvent getWarpDeleteEvent(@NotNull Warp warp, @NotNull CommandUser deleter);
IHomeListEvent getViewHomeListEvent(@NotNull List<Home> homes, @NotNull CommandUser listViewer, boolean publicHomeList);
@NotNull
IHomeListEvent getViewHomeListEvent(@NotNull List<Home> homes, @NotNull CommandUser listViewer,
boolean publicHomeList);
@NotNull
IWarpListEvent getViewWarpListEvent(@NotNull List<Warp> homes, @NotNull CommandUser listViewer);
@NotNull
IDeleteAllHomesEvent getDeleteAllHomesEvent(@NotNull User user, @NotNull CommandUser deleter);
@NotNull
IDeleteAllWarpsEvent getDeleteAllWarpsEvent(@NotNull CommandUser deleter);
@NotNull
@@ -24,18 +24,23 @@ import net.william278.huskhomes.user.User;
import org.jetbrains.annotations.NotNull;
/**
* Representation of an event that fires when all homes are deleted
* Representation of an event that fires when all homes are deleted.
*/
public interface IDeleteAllHomesEvent extends Cancellable {
/**
* Get the player whose homes are being deleted
* Get the player whose homes are being deleted.
*
* @return the {@link User} whose homes are being deleted
*/
@NotNull
User getHomeOwner();
/**
* Get the user who is deleting the homes.
*
* @return the {@link CommandUser} who is deleting the homes
*/
@NotNull
CommandUser getDeleter();
@@ -23,10 +23,15 @@ import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull;
/**
* Representation of an event that fires when all warps are deleted
* Representation of an event that fires when all warps are deleted.
*/
public interface IDeleteAllWarpsEvent extends Cancellable {
/**
* Get the user who is deleting the warps.
*
* @return the {@link CommandUser} who is deleting the warps
*/
@NotNull
CommandUser getDeleter();
@@ -24,18 +24,23 @@ import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull;
/**
* Representation of an event that fires when a single home is deleted
* Representation of an event that fires when a single home is deleted.
*/
public interface IHomeDeleteEvent extends Cancellable {
/**
* Get the home being deleted
* Get the home being deleted.
*
* @return the {@link Home} being deleted
*/
@NotNull
Home getHome();
/**
* Get the user who is deleting the home.
*
* @return the {@link CommandUser} who is deleting the home
*/
@NotNull
CommandUser getDeleter();
@@ -24,18 +24,23 @@ import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull;
/**
* Representation of an event that fires when a home is edited
* Representation of an event that fires when a home is edited.
*/
public interface IHomeEditEvent extends Cancellable {
/**
* Get the home about to be saved
* Get the home about to be saved.
*
* @return the {@link Home} being saved
*/
@NotNull
Home getHome();
/**
* Get the user who is editing the home.
*
* @return the {@link CommandUser} who is editing the home
*/
@NotNull
CommandUser getEditor();
@@ -26,22 +26,27 @@ import org.jetbrains.annotations.NotNull;
import java.util.List;
/**
* Represents an event that fires when a player requests to view a list of homes
* Represents an event that fires when a player requests to view a list of homes.
*/
public interface IHomeListEvent extends Cancellable {
/**
* Get the list of homes to be displayed
* Get the list of homes to be displayed.
*
* @return the list of homes
*/
@NotNull
List<Home> getHomes();
/**
* Set the list of homes to be displayed.
*
* @param homes the list of homes
*/
void setHomes(@NotNull List<Home> homes);
/**
* Get the player viewing the home list
* Get the player viewing the home list.
*
* @return the player viewing the home list
*/
@@ -49,7 +54,7 @@ public interface IHomeListEvent extends Cancellable {
CommandUser getListViewer();
/**
* Indicates if the player has requested to view a list of public homes
* Indicates if the player has requested to view a list of public homes.
*
* @return true if the player has requested to view a list of public homes
*/
@@ -23,12 +23,12 @@ import net.william278.huskhomes.teleport.Teleport;
import org.jetbrains.annotations.NotNull;
/**
* Representation of an event that fires when a teleport is about to occur
* Representation of an event that fires when a teleport is about to occur.
*/
public interface ITeleportEvent extends Cancellable {
/**
* Get the teleport being carried out
* Get the teleport being carried out.
*
* @return the {@link Teleport} being carried out
*/
@@ -23,19 +23,19 @@ import net.william278.huskhomes.teleport.TimedTeleport;
import org.jetbrains.annotations.NotNull;
/**
* Representation of an event that fires when a timed teleport warmup starts
* Representation of an event that fires when a timed teleport warmup starts.
*/
public interface ITeleportWarmupEvent extends Cancellable {
/**
* The duration of the timed teleport before the user is teleported
* The duration of the timed teleport before the user is teleported.
*
* @return the teleport warmup duration
*/
int getWarmupDuration();
/**
* The {@link TimedTeleport} being processed
* The {@link TimedTeleport} being processed.
*
* @return the timed teleport that has started
*/
@@ -24,18 +24,23 @@ import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull;
/**
* Representation of an event that fires when a single warp is deleted
* Representation of an event that fires when a single warp is deleted.
*/
public interface IWarpDeleteEvent extends Cancellable {
/**
* Get the warp being deleted
* Get the warp being deleted.
*
* @return the {@link Warp} being deleted
*/
@NotNull
Warp getWarp();
/**
* Get the user who is deleting the warp.
*
* @return the {@link CommandUser} who is deleting the warp
*/
@NotNull
CommandUser getDeleter();
@@ -24,18 +24,23 @@ import net.william278.huskhomes.user.CommandUser;
import org.jetbrains.annotations.NotNull;
/**
* Representation of an event that fires when a warp is created or updated
* Representation of an event that fires when a warp is created or updated.
*/
public interface IWarpEditEvent extends Cancellable {
/**
* Get the warp being created or updated
* Get the warp being created or updated.
*
* @return the {@link Warp} being saved
*/
@NotNull
Warp getWarp();
/**
* Get the user who is editing the warp.
*
* @return the {@link CommandUser} who is editing the warp
*/
@NotNull
CommandUser getEditor();
@@ -26,22 +26,27 @@ import org.jetbrains.annotations.NotNull;
import java.util.List;
/**
* Represents an event that fires when a player requests to view a list of warps
* Represents an event that fires when a player requests to view a list of warps.
*/
public interface IWarpListEvent extends Cancellable {
/**
* Get the list of warps to be displayed
* Get the list of warps to be displayed.
*
* @return the list of warps
*/
@NotNull
List<Warp> getWarps();
/**
* Set the list of warps to be displayed.
*
* @param warps the list of warps
*/
void setWarps(@NotNull List<Warp> warps);
/**
* Get the user viewing the warp list
* Get the user viewing the warp list.
*
* @return the user viewing the warp list
*/
@@ -44,7 +44,7 @@ import java.util.Map;
import java.util.logging.Level;
/**
* Hook to display warps and public homes on <a href="https://github.com/BlueMap-Minecraft/BlueMap">BlueMap</a> maps
* Hook to display warps and public homes on <a href="https://github.com/BlueMap-Minecraft/BlueMap">BlueMap</a> maps.
*/
public class BlueMapHook extends MapHook {
@@ -63,15 +63,15 @@ public class BlueMapHook extends MapHook {
for (World world : plugin.getWorlds()) {
this.editMapWorld(world, (mapWorld -> {
final MarkerSet publicHomeMarkers = MarkerSet.builder().label(getPublicHomesMarkerSetName()).build();
final MarkerSet homeMarkers = MarkerSet.builder().label(getPublicHomesMarkerSetName()).build();
final MarkerSet warpsMarkers = MarkerSet.builder().label(getWarpsMarkerSetName()).build();
for (BlueMapMap map : mapWorld.getMaps()) {
map.getMarkerSets().put(getPublicHomesKey(), publicHomeMarkers);
map.getMarkerSets().put(getPublicHomesKey(), homeMarkers);
map.getMarkerSets().put(getWarpsKey(), warpsMarkers);
}
publicHomesMarkerSets.put(world.getName(), publicHomeMarkers);
publicHomesMarkerSets.put(world.getName(), homeMarkers);
warpsMarkerSets.put(world.getName(), warpsMarkers);
}));
}
@@ -34,7 +34,7 @@ import org.jetbrains.annotations.Nullable;
import java.util.Optional;
/**
* Hook to display warps and public homes on Dynmap
* Hook to display warps and public homes on Dynmap.
*/
public class DynmapHook extends MapHook {
@@ -171,8 +171,12 @@ public class DynmapHook extends MapHook {
return getDynmap().map(api -> {
publicHomesMarkers = api.getMarkerAPI().getMarkerSet(getPublicHomesKey());
if (publicHomesMarkers == null) {
publicHomesMarkers = api.getMarkerAPI().createMarkerSet(getPublicHomesKey(), getPublicHomesMarkerSetName(),
api.getMarkerAPI().getMarkerIcons(), false);
publicHomesMarkers = api.getMarkerAPI().createMarkerSet(
getPublicHomesKey(),
getPublicHomesMarkerSetName(),
api.getMarkerAPI().getMarkerIcons(),
false
);
} else {
publicHomesMarkers.setMarkerSetLabel(getPublicHomesMarkerSetName());
}
@@ -28,7 +28,7 @@ import org.jetbrains.annotations.NotNull;
import java.util.Locale;
/**
* A hook that provides economy features
* A hook that provides economy features.
*/
public abstract class EconomyHook extends Hook {
@@ -37,7 +37,7 @@ public abstract class EconomyHook extends Hook {
}
/**
* Get the balance of a player
* Get the balance of a player.
*
* @param player the player to get the balance of
* @return the balance of the player
@@ -45,7 +45,7 @@ public abstract class EconomyHook extends Hook {
public abstract double getPlayerBalance(@NotNull OnlineUser player);
/**
* Set the balance of a player
* Set the balance of a player.
*
* @param player the player to set the balance of
* @param amount the amount to set the balance to
@@ -53,7 +53,7 @@ public abstract class EconomyHook extends Hook {
public abstract void changePlayerBalance(@NotNull OnlineUser player, final double amount);
/**
* Format a balance to a string
* Format a balance to a string.
*
* @param amount the amount to format
* @return the formatted string
@@ -61,14 +61,14 @@ public abstract class EconomyHook extends Hook {
public abstract String formatCurrency(final double amount);
/**
* Send the player a message notifying them that they have been charged
* for performing an action
* Send the player a message notifying them that they have been charged for performing an action.
*
* @param user the user to notify
* @param plugin the plugin instance
* @param action the action that was performed
*/
public final void notifyDeducted(@NotNull OnlineUser user, @NotNull HuskHomes plugin, @NotNull TransactionResolver.Action action) {
public final void notifyDeducted(@NotNull OnlineUser user, @NotNull HuskHomes plugin,
@NotNull TransactionResolver.Action action) {
plugin.getSettings().getEconomyCost(action)
.flatMap(cost -> plugin.getLocales().getLocale(
"economy_transaction_complete",
@@ -81,14 +81,12 @@ public abstract class EconomyHook extends Hook {
}
/**
* Send the player a message notifying them that they have been charged
* for performing an action
* Send the player a message notifying them that they have been charged for performing an action.
*
* @param user the user to notify
* @param plugin the plugin instance
* @param action the action that was performed
* @deprecated See {@link #notifyDeducted(OnlineUser, HuskHomes, TransactionResolver.Action)} instead,
* using the new {@link TransactionResolver.Action} enum
* @deprecated See {@link #notifyDeducted(OnlineUser, HuskHomes, TransactionResolver.Action)} instead
*/
@Deprecated(since = "4.4", forRemoval = true)
public final void notifyDeducted(@NotNull OnlineUser user, @NotNull HuskHomes plugin, @NotNull Action action) {
@@ -96,7 +94,7 @@ public abstract class EconomyHook extends Hook {
}
/**
* Economy actions for which a player can be charged
* Economy actions for which a player can be charged.
*
* @deprecated Use the new {@link TransactionResolver.Action} enum instead
*/
@@ -124,7 +122,7 @@ public abstract class EconomyHook extends Hook {
}
/**
* Create an action with a default cost
* Create an action with a default cost.
*
* @return the default cost
* @deprecated Use the new {@link TransactionResolver.Action#getDefaultCost()} instead
@@ -135,7 +133,7 @@ public abstract class EconomyHook extends Hook {
}
/**
* Translate this legacy Action to the new {@link TransactionResolver.Action}
* Translate this legacy Action to the new {@link TransactionResolver.Action}.
*
* @return the equivalent {@link TransactionResolver.Action}
*/
@@ -23,22 +23,22 @@ import net.william278.huskhomes.HuskHomes;
import org.jetbrains.annotations.NotNull;
/**
* A plugin hook, where HuskHomes hooks into another plugin
* A plugin hook, where HuskHomes hooks into another plugin.
*/
public abstract class Hook {
/**
* The plugin that this hook is for
* The plugin that this hook is for.
*/
protected final HuskHomes plugin;
/**
* The name of the hook
* The name of the hook.
*/
protected final String name;
/**
* Construct a new {@link Hook}
* Construct a new {@link Hook}.
*
* @param plugin the {@link HuskHomes} instance
*/
@@ -48,14 +48,18 @@ public abstract class Hook {
}
/**
* Initialize the hook and return {@code true} if it could be enabled
* Initialize the hook and return {@code true} if it could be enabled.
*/
public abstract void initialize() ;
public abstract void initialize();
/**
* Get the name of the hook.
*
* @return the name of the hook
*/
@NotNull
public String getName() {
return name;
}
}
@@ -32,7 +32,7 @@ import java.util.HashMap;
import java.util.Map;
/**
* A hook for a mapping plugin, such as Dynmap
* A hook for a mapping plugin, such as Dynmap.
*/
public abstract class MapHook extends Hook {
@@ -44,7 +44,7 @@ public abstract class MapHook extends Hook {
}
/**
* Populate the map with public homes and warps
* Populate the map with public homes and warps.
*/
protected void populateMap() {
if (plugin.getSettings().doPublicHomesOnMap()) {
@@ -60,47 +60,47 @@ public abstract class MapHook extends Hook {
}
/**
* Update a home, adding it to the map if it exists, or updating it on the map if it doesn't
* Update a home, adding it to the map if it exists, or updating it on the map if it doesn't.
*
* @param home the home to update
*/
public abstract void updateHome(@NotNull Home home);
/**
* Removes a home from the map
* Removes a home from the map.
*
* @param home the home to remove
*/
public abstract void removeHome(@NotNull Home home);
/**
* Clears homes owned by a player from the map
* Clears homes owned by a player from the map.
*
* @param user the player whose homes to clear
*/
public abstract void clearHomes(@NotNull User user);
/**
* Update a warp, adding it to the map if it exists, or updating it on the map if it doesn't
* Update a warp, adding it to the map if it exists, or updating it on the map if it doesn't.
*
* @param warp the warp to update
*/
public abstract void updateWarp(@NotNull Warp warp);
/**
* Removes a warp from the map
* Removes a warp from the map.
*
* @param warp the warp to remove
*/
public abstract void removeWarp(@NotNull Warp warp);
/**
* Clears all warps from the map
* Clears all warps from the map.
*/
public abstract void clearWarps();
/**
* Returns if the position is valid to be set on this server
* Returns if the position is valid to be set on this server.
*
* @param position the position to check
* @return if the position is valid
@@ -140,7 +140,7 @@ public abstract class MapHook extends Hook {
}
/**
* Creates an HTML Dynmap marker information popup widget
* Creates an HTML Dynmap marker information popup widget.
*/
protected static class MarkerInformationPopup {
@NotNull
@@ -158,7 +158,8 @@ public abstract class MapHook extends Hook {
}
@NotNull
protected static DynmapHook.MarkerInformationPopup warp(@NotNull Warp warp, @NotNull String thumbnail, @NotNull HuskHomes plugin) {
protected static DynmapHook.MarkerInformationPopup warp(@NotNull Warp warp, @NotNull String thumbnail,
@NotNull HuskHomes plugin) {
return MarkerInformationPopup.create(warp.getName())
.thumbnail(thumbnail)
.field("Description", plugin.getLocales().wrapText(warp.getMeta().getDescription(), 60))
@@ -167,7 +168,8 @@ public abstract class MapHook extends Hook {
}
@NotNull
protected static DynmapHook.MarkerInformationPopup publicHome(@NotNull Home home, @NotNull String thumbnail, @NotNull HuskHomes plugin) {
protected static DynmapHook.MarkerInformationPopup publicHome(@NotNull Home home, @NotNull String thumbnail,
@NotNull HuskHomes plugin) {
return MarkerInformationPopup.create(home.getName())
.thumbnail(thumbnail)
.field("Owner", home.getOwner().getUsername())
@@ -37,7 +37,7 @@ import java.util.UUID;
import java.util.logging.Level;
/**
* Hooks into Plan to provide the {@link PlanDataExtension} with stats on the web panel
* Hooks into Plan to provide the {@link PlanDataExtension} with stats on the web panel.
*/
public class PlanHook extends Hook {
@@ -66,12 +66,8 @@ public class PlanHook extends Hook {
private void registerDataExtension() {
try {
ExtensionService.getInstance().register(new PlanDataExtension(plugin.getDatabase()));
} catch (IllegalStateException planIsNotEnabled) {
plugin.log(Level.SEVERE, "Plan extension hook failed to register. Plan is not enabled.", planIsNotEnabled);
// Plan is not enabled, handle exception
} catch (IllegalArgumentException dataExtensionImplementationIsInvalid) {
plugin.log(Level.SEVERE, "Plan extension hook failed to register. Data hook implementation is invalid.", dataExtensionImplementationIsInvalid);
// The DataExtension implementation has an implementation error, handle exception
} catch (IllegalStateException | IllegalArgumentException e) {
plugin.log(Level.SEVERE, "Failed to register HuskHomes Plan extension", e);
}
}
@@ -71,7 +71,8 @@ public abstract class Importer extends Hook {
protected abstract int importData(@NotNull ImportData importData) throws Throwable;
protected final void log(@NotNull CommandUser user, @NotNull Level level, @NotNull String message, @NotNull Throwable... e) {
protected final void log(@NotNull CommandUser user, @NotNull Level level, @NotNull String message,
@NotNull Throwable... e) {
message = "[Importer] " + message;
if (user instanceof OnlineUser online) {
final TextColor color = level == Level.SEVERE || level == Level.WARNING
@@ -93,7 +94,7 @@ public abstract class Importer extends Hook {
}
/**
* Represents types of data that can be imported
* Represents types of data that can be imported.
*/
public enum ImportData {
USERS("User Data"),
@@ -38,7 +38,7 @@ import java.util.Optional;
import java.util.logging.Level;
/**
* A handler for when events take place
* A handler for when events take place.
*/
public class EventListener {
@@ -50,7 +50,7 @@ public class EventListener {
}
/**
* Handle when a {@link OnlineUser} joins the server
* Handle when a {@link OnlineUser} joins the server.
*
* @param onlineUser the joining {@link OnlineUser}
*/
@@ -64,7 +64,9 @@ public class EventListener {
this.handleInboundTeleport(onlineUser);
// Synchronize the global player list
plugin.runSyncDelayed(() -> this.synchronizeGlobalPlayerList(onlineUser, plugin.getLocalPlayerList()), 40L);
plugin.runSyncDelayed(() -> this.synchronizeGlobalPlayerList(
onlineUser, plugin.getLocalPlayerList()), 40L
);
// Request updated player lists from other servers
if (plugin.getOnlineUsers().size() == 1) {
@@ -91,7 +93,7 @@ public class EventListener {
}
/**
* Handle when a {@link OnlineUser} leaves the server
* Handle when a {@link OnlineUser} leaves the server.
*
* @param onlineUser the leaving {@link OnlineUser}
*/
@@ -123,7 +125,7 @@ public class EventListener {
}
/**
* Handle inbound cross-server teleports
* Handle inbound cross-server teleports.
*
* @param teleporter user to handle the checks for
*/
@@ -135,7 +137,10 @@ public class EventListener {
}
try {
teleporter.teleportLocally((Position) teleport.getTarget(), plugin.getSettings().doAsynchronousTeleports());
teleporter.teleportLocally(
(Position) teleport.getTarget(),
plugin.getSettings().doAsynchronousTeleports()
);
} catch (TeleportationException e) {
e.displayMessage(teleporter);
}
@@ -145,7 +150,7 @@ public class EventListener {
}
/**
* Handle an inbound global respawn
* Handle an inbound global respawn.
*
* @param teleporter the user to handle the checks for
*/
@@ -207,7 +212,7 @@ public class EventListener {
}
/**
* Handle when a {@link OnlineUser} dies
* Handle when a {@link OnlineUser} dies.
*
* @param onlineUser the {@link OnlineUser} who died
*/
@@ -219,7 +224,7 @@ public class EventListener {
}
/**
* Handle when a {@link OnlineUser} respawns after dying
* Handle when a {@link OnlineUser} respawns after dying.
*
* @param onlineUser the respawning {@link OnlineUser}
*/
@@ -228,7 +233,7 @@ public class EventListener {
// Display the return by death via /back notification
final boolean canReturnByDeath = plugin.getCommand(BackCommand.class)
.map(command -> onlineUser.hasPermission(command.getPermission())
&& onlineUser.hasPermission(command.getPermission("death")))
&& onlineUser.hasPermission(command.getPermission("death")))
.orElse(false);
if (plugin.getSettings().doBackCommandReturnByDeath() && canReturnByDeath) {
plugin.getLocales().getLocale("return_by_death_notification")
@@ -266,7 +271,7 @@ public class EventListener {
}
/**
* Handle when a player teleports
* Handle when a player teleports.
*
* @param onlineUser the {@link OnlineUser} who teleported
* @param sourcePosition the source {@link Position} they came from
@@ -281,7 +286,7 @@ public class EventListener {
}
/**
* Handle when an {@link OnlineUser}'s spawn point is updated
* Handle when an {@link OnlineUser}'s spawn point is updated.
*
* @param onlineUser the {@link OnlineUser} whose spawn point was updated
* @param position the new spawn point
@@ -293,10 +298,10 @@ public class EventListener {
}
/**
* Handle when the plugin is disabling (server is shutting down)
* Handle when the plugin is disabling (server is shutting down).
*/
public final void handlePluginDisable() {
plugin.log(Level.INFO, "Successfully disabled HuskHomes v" + plugin.getVersion());
}
}
}
@@ -53,7 +53,9 @@ public class HomesManager {
}
/**
* Cached user homes - maps a username to a list of their homes
* Cached user homes - maps a username to a list of their homes.
*
* @return a map of usernames to a list of their home names.
*/
@NotNull
public Map<String, List<String>> getUserHomes() {
@@ -62,15 +64,20 @@ public class HomesManager {
HashMap::putAll);
}
/**
* Get a list of all cached set home identifiers.
*
* @return a list of all cached set home identifiers
*/
@NotNull
public List<String> getUserHomeNames() {
public List<String> getUserHomeIdentifiers() {
return userHomes.entrySet().stream()
.flatMap(e -> e.getValue().stream().map(Home::getIdentifier))
.toList();
}
/**
* Cached public homes - maps a username to a list of their public homes
* Cached public homes - maps a username to a list of their public homes.
*/
@NotNull
public Map<String, List<String>> getPublicHomes() {
@@ -79,17 +86,33 @@ public class HomesManager {
HashMap::putAll);
}
/**
* Get a list of all cached public home identifiers.
*
* @return a list of all cached public home identifiers
*/
@NotNull
public List<String> getPublicHomeNames() {
public List<String> getPublicHomeIdentifiers() {
return publicHomes.stream()
.map(Home::getIdentifier)
.toList();
}
/**
* Cache user homes for a given user.
*
* @param user the user to cache homes for
*/
public void cacheUserHomes(@NotNull User user) {
userHomes.put(user.getUsername(), new ConcurrentLinkedQueue<>(plugin.getDatabase().getHomes(user)));
}
/**
* Cache a home for a given user.
*
* @param home the home to cache
* @param propagate whether to propagate the cache update to other servers (if cross-server is enabled)
*/
public void cacheHome(@NotNull Home home, boolean propagate) {
userHomes.computeIfPresent(home.getOwner().getUsername(), (k, v) -> {
v.remove(home);
@@ -132,6 +155,13 @@ public class HomesManager {
}
}
/**
* Propagate the update of a home/warp to other servers (if cross-server is enabled).
*
* <p>This works by broking a message requesting that other servers fetch the updated home from the database.
*
* @param homeId the UUID of the home/warp to update
*/
private void propagateCacheUpdate(@NotNull UUID homeId) {
if (plugin.getSettings().doCrossServer()) {
plugin.getOnlineUsers().stream().findAny().ifPresent(user -> Message.builder()
@@ -196,7 +226,8 @@ public class HomesManager {
this.cacheHome(home, true);
}
public void createHome(@NotNull OnlineUser owner, @NotNull String name, @NotNull Position position) throws ValidationException {
public void createHome(@NotNull OnlineUser owner, @NotNull String name,
@NotNull Position position) throws ValidationException {
createHome(owner, name, position, plugin.getSettings().doOverwriteExistingHomesWarps(), true);
}
@@ -226,7 +257,8 @@ public class HomesManager {
return deleted;
}
public void setHomePosition(@NotNull User owner, @NotNull String name, @NotNull Position position) throws ValidationException {
public void setHomePosition(@NotNull User owner, @NotNull String name,
@NotNull Position position) throws ValidationException {
final Optional<Home> optionalHome = plugin.getDatabase().getHome(owner, name);
if (optionalHome.isEmpty()) {
throw new ValidationException(ValidationException.Type.NOT_FOUND);
@@ -241,7 +273,8 @@ public class HomesManager {
this.cacheHome(home, true);
}
public void setHomeName(@NotNull User owner, @NotNull String name, @NotNull String newName) throws ValidationException {
public void setHomeName(@NotNull User owner, @NotNull String name,
@NotNull String newName) throws ValidationException {
final Optional<Home> optionalHome = plugin.getDatabase().getHome(owner, name);
if (optionalHome.isEmpty()) {
throw new ValidationException(ValidationException.Type.NOT_FOUND);
@@ -260,7 +293,8 @@ public class HomesManager {
this.cacheHome(home, true);
}
public void setHomeDescription(@NotNull User owner, @NotNull String name, @NotNull String description) throws ValidationException {
public void setHomeDescription(@NotNull User owner, @NotNull String name,
@NotNull String description) throws ValidationException {
final Optional<Home> optionalHome = plugin.getDatabase().getHome(owner, name);
if (optionalHome.isEmpty()) {
throw new ValidationException(ValidationException.Type.NOT_FOUND);
@@ -303,7 +337,8 @@ public class HomesManager {
this.cacheHome(home, true);
}
public void setHomeMetaTags(@NotNull User owner, @NotNull String name, @NotNull Map<String, String> tags) throws ValidationException {
public void setHomeMetaTags(@NotNull User owner, @NotNull String name,
@NotNull Map<String, String> tags) throws ValidationException {
final Optional<Home> optionalHome = plugin.getDatabase().getHome(owner, name);
if (optionalHome.isEmpty()) {
throw new ValidationException(ValidationException.Type.NOT_FOUND);
@@ -38,7 +38,7 @@ import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* Manages {@link TeleportRequest}s between players
* Manages {@link TeleportRequest}s between players.
*/
public class RequestsManager {
@@ -53,7 +53,7 @@ public class RequestsManager {
}
/**
* Return if a user is ignoring tpa requests
* Return if a user is ignoring tpa requests.
*
* @param user the user to check
* @return {@code true} if the user is ignoring tpa requests
@@ -63,7 +63,7 @@ public class RequestsManager {
}
/**
* Add a teleport request to a user's request queue
* Add a teleport request to a user's request queue.
*
* @param request the {@link TeleportRequest} to add
* @param recipient the {@link User} recipient of the request
@@ -73,7 +73,7 @@ public class RequestsManager {
}
/**
* Remove {@link TeleportRequest}(s) sent by a requester, by name, from a recipient's queue
* Remove {@link TeleportRequest}(s) sent by a requester, by name, from a recipient's queue.
*
* @param requesterName the sender's username, whose requests should be removed
* @param recipient the {@link User} recipient of the request
@@ -86,7 +86,7 @@ public class RequestsManager {
}
/**
* Get the last received teleport request for a user
* Get the last received teleport request for a user.
*
* @param recipient the user to get the request for
* @return the last received request, if present
@@ -200,7 +200,7 @@ public class RequestsManager {
plugin.fireEvent(plugin.getReceiveTeleportRequestEvent(recipient, request), (event -> {
addTeleportRequest(request, recipient);
plugin.getLocales().getLocale((request.getType() == TeleportRequest.Type.TPA ? "tpa" : "tpahere")
+ "_request_received", request.getRequesterName())
+ "_request_received", request.getRequesterName())
.ifPresent(recipient::sendMessage);
plugin.getLocales().getLocale("teleport_request_buttons", request.getRequesterName())
.ifPresent(recipient::sendMessage);
@@ -210,7 +210,7 @@ public class RequestsManager {
}
/**
* Respond to a teleport request with the given status by name of the sender
* Respond to a teleport request with the given status by name of the sender.
*
* @param recipient The user receiving the request
* @param senderName The name of the user sending the request
@@ -236,7 +236,7 @@ public class RequestsManager {
}
/**
* Respond to the last received teleport request for a user, if there is one
* Respond to the last received teleport request for a user if there is one.
*
* @param recipient The user receiving the request
* @param accepted Whether the request should be accepted or not
@@ -266,13 +266,14 @@ public class RequestsManager {
}
/**
* Handle; respond to; a teleport request
* Handle the response to a teleport request.
*
* @param request The request to handle
* @param recipient The recipient of the request
* @param accepted Whether the request should be accepted or not
*/
private void handleRequestResponse(@NotNull TeleportRequest request, @NotNull OnlineUser recipient, boolean accepted) {
private void handleRequestResponse(@NotNull TeleportRequest request, @NotNull OnlineUser recipient,
boolean accepted) {
// Remove the request(s) from the sender from the recipient's queue
removeTeleportRequest(request.getRequesterName(), recipient);
@@ -329,7 +330,7 @@ public class RequestsManager {
}
/**
* Handle a teleport request response for a local user
* Handle a teleport request response for a local user.
*
* @param requester The user who sent the request
* @param request The {@link TeleportRequest} to handle
@@ -94,7 +94,7 @@ public class WarpsManager {
}
/**
* Cached warp names
* Cached warp names.
*/
@NotNull
public List<String> getWarps() {
@@ -112,7 +112,8 @@ public class WarpsManager {
.toList();
}
public void createWarp(@NotNull String name, @NotNull Position position, boolean overwrite) throws ValidationException {
public void createWarp(@NotNull String name, @NotNull Position position,
boolean overwrite) throws ValidationException {
final Optional<Warp> existingWarp = plugin.getDatabase().getWarp(name);
if (existingWarp.isPresent() && !overwrite) {
throw new ValidationException(ValidationException.Type.NAME_TAKEN);
@@ -35,7 +35,7 @@ public abstract class Broker {
protected final HuskHomes plugin;
/**
* Create a new broker
* Create a new broker.
*
* @param plugin the HuskHomes plugin instance
*/
@@ -44,9 +44,9 @@ public abstract class Broker {
}
/**
* Handle an inbound {@link Message}
* Handle an inbound {@link Message}.
*
* @param receiver The user who received the message, if a receiver exists
* @param receiver The user who received the message if a receiver exists
* @param message The message
*/
protected void handle(@NotNull OnlineUser receiver, @NotNull Message message) {
@@ -117,18 +117,19 @@ public abstract class Broker {
plugin.getManager().homes().updatePublicHomeCache();
plugin.getManager().warps().updateWarpCache();
}
default -> throw new IllegalStateException("Unexpected value: " + message.getType());
}
}
/**
* Initialize the message broker
* Initialize the message broker.
*
* @throws RuntimeException if the broker fails to initialize
*/
public abstract void initialize() throws IllegalStateException;
/**
* Send a message to the broker
* Send a message to the broker.
*
* @param message the message to send
* @param sender the sender of the message
@@ -136,7 +137,7 @@ public abstract class Broker {
protected abstract void send(@NotNull Message message, @NotNull OnlineUser sender);
/**
* Move an {@link OnlineUser} to a new server on the proxy network
* Move an {@link OnlineUser} to a new server on the proxy network.
*
* @param user the user to move
* @param server the server to move the user to
@@ -144,7 +145,7 @@ public abstract class Broker {
public abstract void changeServer(@NotNull OnlineUser user, @NotNull String server);
/**
* Terminate the broker
* Terminate the broker.
*/
public abstract void close();
@@ -160,7 +161,7 @@ public abstract class Broker {
}
/**
* Identifies types of message brokers
* Identifies types of message brokers.
*/
public enum Type {
PLUGIN_MESSAGE("Plugin Messages"),
@@ -33,7 +33,7 @@ import java.util.UUID;
public class Message {
/**
* Message target indicating all players
* Message target indicating all players.
*/
public static final String TARGET_ALL = "ALL";
@@ -111,7 +111,7 @@ public class Message {
}
/**
* Builder for {@link Message}s
* Builder for {@link Message}s.
*/
public static class Builder {
private Type type;
@@ -160,7 +160,7 @@ public class Message {
}
/**
* Different types of cross-server messages
* Different types of cross-server messages.
*/
public enum Type {
TELEPORT_TO_POSITION,
@@ -30,7 +30,7 @@ import java.util.List;
import java.util.Optional;
/**
* Represents a payload sent in a cross-server {@link Message}
* Represents a payload sent in a cross-server {@link Message}.
*/
public class Payload {
@@ -53,7 +53,7 @@ public class Payload {
private List<String> stringList;
/**
* Returns an empty cross-server message payload
* Returns an empty cross-server message payload.
*
* @return an empty payload
*/
@@ -63,7 +63,7 @@ public class Payload {
}
/**
* Returns a payload containing a {@link Position}
* Returns a payload containing a {@link Position}.
*
* @param position the position to send
* @return a payload containing the position
@@ -76,7 +76,7 @@ public class Payload {
}
/**
* Returns a payload containing a {@link TeleportRequest}
* Returns a payload containing a {@link TeleportRequest}.
*
* @param teleportRequest the teleport to send
* @return a payload containing the teleport request
@@ -89,7 +89,7 @@ public class Payload {
}
/**
* A string field
* A string field.
*/
@NotNull
public static Payload withString(@NotNull String target) {
@@ -99,7 +99,7 @@ public class Payload {
}
/**
* A string list field
* A string list field.
*/
@NotNull
public static Payload withStringList(@NotNull List<String> target) {
@@ -112,7 +112,7 @@ public class Payload {
}
/**
* A position field
* A position field.
*/
public Optional<Position> getPosition() {
return Optional.ofNullable(position);
@@ -120,21 +120,21 @@ public class Payload {
/**
* A teleport request field
* A teleport request field.
*/
public Optional<TeleportRequest> getTeleportRequest() {
return Optional.ofNullable(teleportRequest);
}
/**
* A string field
* A string field.
*/
public Optional<String> getString() {
return Optional.ofNullable(string);
}
/**
* A string list field
* A string list field.
*/
public Optional<List<String>> getStringList() {
return Optional.ofNullable(stringList);
@@ -31,18 +31,15 @@ import java.util.logging.Level;
/**
* <a href="https://www.spigotmc.org/wiki/bukkit-bungee-plugin-messaging-channel/">Plugin Messaging channel</a> message
* broker implementation
* broker implementation.
*/
public class PluginMessageBroker extends Broker {
/**
* The name of BungeeCord's provided plugin channel.
*
* @implNote Technically, the effective identifier of this channel is {@code bungeecord:main}, but Spigot remaps
* {@code BungeeCord} automatically to the new one (<a href="https://wiki.vg/Plugin_channels#bungeecord:main">source</a>).
* Spigot's <a href="https://www.spigotmc.org/wiki/bukkit-bungee-plugin-messaging-channel/">official documentation</a>
* still instructs usage of {@code BungeeCord} as the name to use, however. It's all a bit inconsistent, so just in case
* it's best to leave it how it is for to maintain backwards compatibility.
* <p>Internally, this is <a href="https://wiki.vg/Plugin_channels#bungeecord:main">{@code bungeecord:main}</a>,
* but Spigot remaps {@code BungeeCord} automatically to the new one (hence BungeeCord is kept for back-compat).
*/
public static final String BUNGEE_CHANNEL_ID = "BungeeCord";
@@ -55,7 +52,6 @@ public class PluginMessageBroker extends Broker {
plugin.initializePluginChannels();
}
@SuppressWarnings("UnstableApiUsage")
public final void onReceive(@NotNull String channel, @NotNull OnlineUser user, byte[] message) {
if (!channel.equals(BUNGEE_CHANNEL_ID)) {
return;
@@ -79,7 +75,6 @@ public class PluginMessageBroker extends Broker {
}
@Override
@SuppressWarnings("UnstableApiUsage")
protected void send(@NotNull Message message, @NotNull OnlineUser sender) {
final ByteArrayDataOutput messageWriter = ByteStreams.newDataOutput();
messageWriter.writeUTF(message.getScope().getPluginMessageChannel());
@@ -102,7 +97,6 @@ public class PluginMessageBroker extends Broker {
}
@Override
@SuppressWarnings("UnstableApiUsage")
public void changeServer(@NotNull OnlineUser user, @NotNull String server) {
final ByteArrayDataOutput outputStream = ByteStreams.newDataOutput();
@@ -115,4 +109,5 @@ public class PluginMessageBroker extends Broker {
@Override
public void close() {
}
}
}
@@ -30,7 +30,7 @@ import redis.clients.jedis.JedisPubSub;
import java.util.logging.Level;
/**
* Redis PubSub broker implementation
* Redis PubSub broker implementation.
*/
public class RedisBroker extends PluginMessageBroker {
private JedisPool jedisPool;
@@ -78,13 +78,13 @@ public class RedisBroker extends PluginMessageBroker {
if (message.getScope() == Message.Scope.PLAYER) {
plugin.getOnlineUsers().stream()
.filter(online -> message.getTarget().equals(Message.TARGET_ALL)
|| online.getUsername().equals(message.getTarget()))
|| online.getUsername().equals(message.getTarget()))
.forEach(receiver -> handle(receiver, message));
return;
}
if (message.getTarget().equals(plugin.getServerName())
|| message.getTarget().equals(Message.TARGET_ALL)) {
|| message.getTarget().equals(Message.TARGET_ALL)) {
plugin.getOnlineUsers().stream()
.findAny()
.ifPresent(receiver -> handle(receiver, message));
@@ -25,10 +25,13 @@ import org.jetbrains.annotations.NotNull;
import java.util.UUID;
/**
* Represents a home set by a {@link User}
* Represents a home set by a {@link User}.
*/
public class Home extends SavedPosition {
/**
* The delimiter used to separate the owner's name from the home name in the home identifier.
*/
public static final String IDENTIFIER_DELIMITER = ".";
private final User owner;
private boolean isPublic;
@@ -46,19 +49,47 @@ public class Home extends SavedPosition {
this.setPublic(false);
}
/**
* Creates a new {@link Home} from a series of coordinates, a viewing angle, a {@link World}, a server name, a
* {@link PositionMeta}, a {@link UUID}, a {@link User} and a boolean representing whether the home is public.
*
* @param x The x coordinate of the home
* @param y The y coordinate of the home
* @param z The z coordinate of the home
* @param yaw The yaw of the home
* @param pitch The pitch of the home
* @param world The {@link World} the home is in
* @param server The name of the server the home is in
* @param positionMeta The {@link PositionMeta} of the home
* @param uuid The {@link UUID} of the home
* @param owner The {@link User} who owns the home
* @param isPublic Whether the home is public
* @return the new {@link Home}
*/
@NotNull
public static Home from(double x, double y, double z, float yaw, float pitch, @NotNull World world, @NotNull String server,
@NotNull PositionMeta positionMeta, @NotNull UUID uuid, @NotNull User owner, boolean isPublic) {
public static Home from(double x, double y, double z, float yaw, float pitch, @NotNull World world,
@NotNull String server, @NotNull PositionMeta positionMeta, @NotNull UUID uuid,
@NotNull User owner, boolean isPublic) {
return new Home(x, y, z, yaw, pitch, world, server, positionMeta, uuid, owner, isPublic);
}
/**
* Creates a new {@link Home} from a {@link Position} and {@link PositionMeta}.
*
* @param position The {@link Position} to create the home from
* @param meta The {@link PositionMeta} to create the home from
* @param owner The {@link User} who owns the home
* @return the new {@link Home}
*/
@NotNull
public static Home from(@NotNull Position position, @NotNull PositionMeta meta, @NotNull User owner) {
return new Home(position, meta, owner);
}
/**
* The {@link User} who owns this home
* Get the {@link User} who owns this home.
*
* @return the {@link User} who owns this home
*/
@NotNull
public User getOwner() {
@@ -66,22 +97,45 @@ public class Home extends SavedPosition {
}
/**
* {@code true} if this home is public
* Returns whether this home is public.
*
* @return {@code true} if this home is public.
*/
public boolean isPublic() {
return isPublic;
}
public void setPublic(boolean aPublic) {
isPublic = aPublic;
/**
* Sets whether this home is public.
*
* @param isPublic {@code true} if this home is public
*/
public void setPublic(boolean isPublic) {
this.isPublic = isPublic;
}
/**
* Get a version of the canonical home identifier string that is safe for use in formatted locales.
* Safe identifiers will only contain alphanumeric ASCII characters (a-z, A-Z, 0-9), underscores and dashes.
*
* <p>This typically consists of the owner's username, a delimiter, and the home {@link #getUuid() UUID}.
*
* @return the locale-safe canonical home identifier string
*/
@NotNull
@Override
public String getSafeIdentifier() {
return getOwner().getUsername() + IDENTIFIER_DELIMITER + super.getSafeIdentifier();
}
/**
* Get the canonical home identifier string.
*
* <p>This typically consists of the owner's username, a delimiter, and the home {@link #getName() name}.
*
* @return the canonical home identifier string
* @see #getSafeIdentifier() #getSafeIdentifier() to get a locale-safe version of this string
*/
@NotNull
@Override
public String getIdentifier() {
@@ -23,9 +23,10 @@ import com.google.gson.annotations.Expose;
import org.jetbrains.annotations.NotNull;
/**
* Represents a local position on this server
* Represents a local position on this server.
*/
public class Location {
@Expose
private double x;
@Expose
@@ -62,7 +63,7 @@ public class Location {
}
/**
* Update the position to match that of another position
* Update the position to match that of another position.
*
* @param position The position to update to
*/
@@ -76,7 +77,7 @@ public class Location {
}
/**
* The double-precision defined x coordinate of the location
* The double-precision defined x coordinate of the location.
*/
public double getX() {
return x;
@@ -87,7 +88,7 @@ public class Location {
}
/**
* The double-precision defined y coordinate of the location
* The double-precision defined y coordinate of the location.
*/
public double getY() {
return y;
@@ -98,7 +99,7 @@ public class Location {
}
/**
* The double-precision defined z coordinate of the location
* The double-precision defined z coordinate of the location.
*/
public double getZ() {
return z;
@@ -109,7 +110,7 @@ public class Location {
}
/**
* The float-precision defined yaw facing of the location
* The float-precision defined yaw facing of the location.
*/
public float getYaw() {
return yaw;
@@ -120,7 +121,7 @@ public class Location {
}
/**
* The float-precision defined pitch facing of the location
* The float-precision defined pitch facing of the location.
*/
public float getPitch() {
return pitch;
@@ -131,7 +132,7 @@ public class Location {
}
/**
* The {@link World} the location is on
* The {@link World} the location is on.
*/
public World getWorld() {
return world;
@@ -140,4 +141,5 @@ public class Location {
public void setWorld(World world) {
this.world = world;
}
}
@@ -24,20 +24,22 @@ import net.william278.huskhomes.teleport.Target;
import org.jetbrains.annotations.NotNull;
/**
* Represents a position - a {@link Location} somewhere on the proxy network or server
* Represents a position - a {@link Location} somewhere on the proxy network or server.
*/
public class Position extends Location implements Target {
@Expose
private String server;
protected Position(double x, double y, double z, float yaw, float pitch, @NotNull World world, @NotNull String server) {
protected Position(double x, double y, double z, float yaw, float pitch,
@NotNull World world, @NotNull String server) {
super(x, y, z, yaw, pitch, world);
this.setServer(server);
}
protected Position(@NotNull Location location, @NotNull String server) {
super(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch(), location.getWorld());
super(location.getX(), location.getY(), location.getZ(), location.getYaw(),
location.getPitch(), location.getWorld());
this.setServer(server);
}
@@ -46,12 +48,14 @@ public class Position extends Location implements Target {
}
@NotNull
public static Position at(double x, double y, double z, float yaw, float pitch, @NotNull World world, @NotNull String server) {
public static Position at(double x, double y, double z, float yaw, float pitch,
@NotNull World world, @NotNull String server) {
return new Position(x, y, z, yaw, pitch, world, server);
}
@NotNull
public static Position at(double x, double y, double z, @NotNull World world, @NotNull String server) {
public static Position at(double x, double y, double z,
@NotNull World world, @NotNull String server) {
return Position.at(x, y, z, 0, 0, world, server);
}
@@ -67,7 +71,7 @@ public class Position extends Location implements Target {
}
/**
* The name of the server the position is on
* The name of the server the position is on.
*/
@NotNull
public String getServer() {
@@ -80,10 +84,10 @@ public class Position extends Location implements Target {
@Override
public String toString() {
return "x: " + (int) getX() + ", " +
"y: " + (int) getY() + ", " +
"z: " + (int) getZ() + " " +
"(" + getWorld().getName() + " / " + getServer() + ")";
return "x: " + (int) getX() + ", "
+ "y: " + (int) getY() + ", "
+ "z: " + (int) getZ() + " "
+ "(" + getWorld().getName() + " / " + getServer() + ")";
}
}
@@ -29,7 +29,7 @@ import java.util.HashMap;
import java.util.Map;
/**
* Represents metadata about a {@link Position}, used in {@link SavedPosition} implementations
* Represents metadata about a {@link Position}, used in {@link SavedPosition} implementations.
*/
public class PositionMeta {
@@ -58,7 +58,7 @@ public class PositionMeta {
}
/**
* Deserialize a JSON string into a {@link Map} of meta tags
* Deserialize a JSON string into a {@link Map} of meta tags.
*
* @param serializedTags The JSON string to deserialize
* @return The deserialized {@link Map}
@@ -78,7 +78,7 @@ public class PositionMeta {
}
/**
* Serialize a {@link Map} of meta tags into a JSON string
* Serialize a {@link Map} of meta tags into a JSON string.
*
* @return The serialized JSON string
*/
@@ -96,7 +96,7 @@ public class PositionMeta {
}
/**
* The name of a position
* The name of a position.
*/
public String getName() {
return name;
@@ -107,7 +107,7 @@ public class PositionMeta {
}
/**
* A description of a position
* A description of a position.
*/
@NotNull
public String getDescription() {
@@ -119,7 +119,7 @@ public class PositionMeta {
}
/**
* Map of metadata tags for a position
* Map of metadata tags for a position.
*/
public Map<String, String> getTags() {
return tags;
@@ -130,7 +130,7 @@ public class PositionMeta {
}
/**
* The time the position was created
* The time the position was created.
*/
@NotNull
public Instant getCreationTime() {
@@ -25,7 +25,7 @@ import org.jetbrains.annotations.NotNull;
import java.util.UUID;
/**
* Represents a persistently-saved {@link Position}
* Represents a persistently-saved {@link Position}.
*/
public abstract class SavedPosition extends Position implements Comparable<SavedPosition> {
@@ -40,7 +40,7 @@ public abstract class SavedPosition extends Position implements Comparable<Saved
}
/**
* Create a new {@link SavedPosition} from a {@link Position} and {@link PositionMeta}
* Create a new {@link SavedPosition} from a {@link Position} and {@link PositionMeta}.
*
* @param position The {@link Position} to save
* @param meta {@link PositionMeta} information about this position
@@ -53,7 +53,7 @@ public abstract class SavedPosition extends Position implements Comparable<Saved
}
/**
* Metadata about this position (name, description)
* Metadata about this position (name, description).
*/
@NotNull
public PositionMeta getMeta() {
@@ -65,7 +65,7 @@ public abstract class SavedPosition extends Position implements Comparable<Saved
}
/**
* The name of this position. Shortcut for {@link #getMeta()}.{@link PositionMeta#getName()}
* The name of this position. Shortcut for {@link #getMeta()}.{@link PositionMeta#getName()}.
*/
@NotNull
public String getName() {
@@ -73,7 +73,7 @@ public abstract class SavedPosition extends Position implements Comparable<Saved
}
/**
* A unique ID representing this position
* A unique ID representing this position.
*/
@NotNull
public UUID getUuid() {
@@ -24,7 +24,7 @@ import org.jetbrains.annotations.NotNull;
import java.util.UUID;
/**
* Represents a server warp
* Represents a server warp.
*/
public class Warp extends SavedPosition {
@@ -36,7 +36,7 @@ public class Warp extends SavedPosition {
}
/**
* Create a new {@link Warp} from a {@link Position} and {@link PositionMeta}
* Create a new {@link Warp} from a {@link Position} and {@link PositionMeta}.
*
* @param position The {@link Position} to save as a warp
* @param meta {@link PositionMeta} information about this position
@@ -26,7 +26,7 @@ import java.util.Optional;
import java.util.UUID;
/**
* Represents a world on a server
* Represents a world on a server.
*/
public class World {
@@ -56,7 +56,7 @@ public class World {
}
/**
* The name of this world, as defined by the world directory name
* The name of this world, as defined by the world directory name.
*/
@NotNull
public String getName() {
@@ -68,7 +68,7 @@ public class World {
}
/**
* UUID of this world, as defined by the {@code uid.dat} file in the world directory
* UUID of this world, as defined by the {@code uid.dat} file in the world directory.
*/
@NotNull
public UUID getUuid() {
@@ -81,9 +81,9 @@ public class World {
/**
* Environment of the world ({@link Environment#OVERWORLD}, {@link Environment#NETHER}, {@link Environment#THE_END},
* or {@link Environment#CUSTOM})
* <p>
* Will return {@link Environment#OVERWORLD} if the environment is null
* or {@link Environment#CUSTOM}).
*
* <p>Will return {@link Environment#OVERWORLD} if the environment is null
*/
@NotNull
public Environment getEnvironment() {
@@ -95,7 +95,7 @@ public class World {
}
/**
* Identifies the environment of the world
* Identifies the environment of the world.
*/
public enum Environment {
OVERWORLD,
@@ -74,7 +74,7 @@ public final class NormalDistributionEngine extends RandomTeleportEngine {
}
/**
* Generate a safe ground-level {@link Location} through a randomized normally-distributed radius and random angle
* Generate a safe ground-level {@link Location} through a randomized normally-distributed radius and random angle.
*
* @param world The world to generate the location in
* @return A generated location
@@ -101,9 +101,9 @@ public final class NormalDistributionEngine extends RandomTeleportEngine {
}
/**
* Generates a random angle in the range [0, 360]
* Generates a random angle in the range {@code [0, 360]}.
*
* @return a random angle in the range [0, 360]
* @return a random angle in the range {@code [0, 360]}
*/
private static float getRandomAngle() {
return (float) (Math.random() * 360);
@@ -28,7 +28,7 @@ import java.util.Optional;
import java.util.concurrent.CompletableFuture;
/**
* Represents an engine for generating random position targets
* Represents an engine for generating random position targets.
*/
public abstract class RandomTeleportEngine {
@@ -37,7 +37,7 @@ public abstract class RandomTeleportEngine {
public long maxAttempts = 12;
/**
* Constructor for a random teleport engine
* Constructor for a random teleport engine.
*
* @param plugin The HuskHomes plugin instance
* @param name The name of the implementing random teleport engine
@@ -53,12 +53,13 @@ public abstract class RandomTeleportEngine {
}
/**
* Get the origin (center) position for the world
* Get the origin (center) position for the world.
*
* <p>Note that this will return the {@link HuskHomes#getServerSpawn() server spawn position} if it is in the same
* world as the world passed to this method, otherwise it will return a position at 0, 128, 0 on the provided world.
*
* @param world The world to get the origin position for
* @return The origin position
* @implNote This will return the {@link HuskHomes#getServerSpawn() server spawn position} if it is in the same
* world as the world passed to this method, otherwise it will return a position at 0, 128, 0 on the provided world.
*/
@NotNull
protected Position getCenterPoint(@NotNull World world) {
@@ -75,13 +76,13 @@ public abstract class RandomTeleportEngine {
/**
* Gets a random position in the {@link World}, or {@link Optional#empty()} if no position could be found in
* the configured number of attempts
* the configured number of attempts.
*
* @param world The world to find a random position in
* @param args The arguments to pass to the random teleport engine
* @return The position, optionally, which will be empty if the random teleport engine timed out after a
* {@link #maxAttempts configured number of attempts}
* @return An Optional position, if one could be found in the {@link #maxAttempts max attempts}
*/
public abstract CompletableFuture<Optional<Position>> getRandomPosition(@NotNull World world, @NotNull String[] args);
public abstract CompletableFuture<Optional<Position>> getRandomPosition(@NotNull World world,
@NotNull String[] args);
}
@@ -27,7 +27,7 @@ import org.jetbrains.annotations.NotNull;
public interface Target {
/**
* Create a {@link Target} from a player name
* Create a {@link Target} from a player name.
*
* @param target the player name
* @return the target
@@ -52,8 +52,8 @@ public class Teleport {
protected final boolean updateLastPosition;
protected Teleport(@NotNull OnlineUser executor, @NotNull Teleportable teleporter, @NotNull Target target,
@NotNull Type type, boolean updateLastPosition, @NotNull List<TransactionResolver.Action> actions,
@NotNull HuskHomes plugin) {
@NotNull Type type, boolean updateLastPosition,
@NotNull List<TransactionResolver.Action> actions, @NotNull HuskHomes plugin) {
this.plugin = plugin;
this.executor = executor;
this.teleporter = teleporter;
@@ -62,10 +62,8 @@ public class Teleport {
this.actions = actions;
this.async = plugin.getSettings().doAsynchronousTeleports();
this.updateLastPosition = updateLastPosition && plugin.getCommand(BackCommand.class)
.map(command ->
executor.hasPermission(command.getPermission()) &&
executor.hasPermission(command.getPermission("previous"))
)
.map(command -> executor.hasPermission(command.getPermission())
&& executor.hasPermission(command.getPermission("previous")))
.orElse(false);
}
@@ -217,7 +215,7 @@ public class Teleport {
}
/**
* Represents the type of teleport being used
* Represents the type of teleport being used.
*/
public enum Type {
TELEPORT(0),
@@ -28,7 +28,7 @@ import org.jetbrains.annotations.NotNull;
import java.time.Instant;
/**
* Represents a request between players for one user to teleport to another, or vice versa
* Represents a request between players for one user to teleport to another, or vice versa.
*/
public class TeleportRequest {
@@ -50,7 +50,7 @@ public class TeleportRequest {
private String recipientName;
/**
* Create a teleport request
* Create a teleport request.
*
* @param requester The user making the request
*/
@@ -67,7 +67,7 @@ public class TeleportRequest {
}
/**
* Returns if the request has now expired
* Returns if the request has now expired.
*
* @return {@code true} the request has passed its expiry time
*/
@@ -76,7 +76,7 @@ public class TeleportRequest {
}
/**
* The name of the request recipient
* The name of the request recipient.
*/
@NotNull
public String getRecipientName() {
@@ -88,7 +88,7 @@ public class TeleportRequest {
}
/**
* The user making the request
* The user making the request.
*/
@NotNull
public String getRequesterName() {
@@ -100,7 +100,7 @@ public class TeleportRequest {
}
/**
* The position of the requester, relevant in the case of a {@link Type#TPA_HERE} request
* The position of the requester, relevant in the case of a {@link Type#TPA_HERE} request.
*/
@NotNull
public Position getRequesterPosition() {
@@ -112,7 +112,7 @@ public class TeleportRequest {
}
/**
* The type of request; a {@link Type#TPA} or {@link Type#TPA_HERE}
* The type of request; a {@link Type#TPA} or {@link Type#TPA_HERE}.
*/
@NotNull
public TeleportRequest.Type getType() {
@@ -124,8 +124,7 @@ public class TeleportRequest {
}
/**
* The status of the request; a {@link Status#PENDING}, {@link Status#ACCEPTED}
* or {@link Status#DECLINED}
* The status of the request; a {@link Status#PENDING}, {@link Status#ACCEPTED} or {@link Status#DECLINED}.
*/
@NotNull
public TeleportRequest.Status getStatus() {
@@ -137,38 +136,39 @@ public class TeleportRequest {
}
/**
* Types of teleport requests ({@code /tpa} or {@code /tpahere})
* Types of teleport requests ({@code /tpa} or {@code /tpahere}).
*/
public enum Type {
/**
* The request is a {@code /tpa} request, where the requester is requesting to teleport <i>to</i> the recipient
* The request is a {@code /tpa} request, where the requester is requesting to teleport <i>to</i> the recipient.
*/
TPA,
/**
* The request is a {@code /tpahere} request, where the requester is requesting that the recipient teleport <i>to them</i>
* The request is a {@code /tpahere} request, where the requester is requesting that the recipient teleport
* <i>to them</i>.
*/
TPA_HERE
}
/**
* The current status of a teleport request
* The current status of a teleport request.
*/
public enum Status {
/**
* The request is currently pending and can be accepted or declined
* The request is currently pending and can be accepted or declined.
*/
PENDING,
/**
* The teleport request has been accepted by the recipient and teleportation will commence
* The teleport request has been accepted by the recipient and teleportation will commence.
*/
ACCEPTED,
/**
* The recipient has declined the teleport request
* The recipient has declined the teleport request.
*/
DECLINED,
/**
* The recipient was ignoring teleport requests at the time it was sent;
* the request has been automatically declined
* the request has been automatically declined.
*/
IGNORED
}
@@ -24,14 +24,14 @@ import org.jetbrains.annotations.NotNull;
/**
* Represents a teleporter; the person performing the teleport.
* <p>
* Can be represented as an {@link OnlineUser} locally or as a {@link Username username} reference
*
* <p>Can be represented as an {@link OnlineUser} locally or as a {@link Username username} reference
* that needs to be resolved first.
*/
public interface Teleportable {
/**
* Create a {@link Teleportable} from a player name
* Create a {@link Teleportable} from a player name.
*
* @param teleporter the player name
* @return the teleportable
@@ -42,7 +42,7 @@ public interface Teleportable {
}
/**
* Get the username of the teleporter
* Get the username of the teleporter.
*
* @return the username string
*/
@@ -54,6 +54,9 @@ public class TeleportationException extends IllegalStateException {
case WORLD_NOT_FOUND -> plugin.getLocales()
.getLocale("error_invalid_world")
.ifPresent(user::sendMessage);
default -> {
// Silent; no message
}
}
}
@@ -64,7 +67,7 @@ public class TeleportationException extends IllegalStateException {
}
/**
* Represents different causes of {@link TeleportationException}s
* Represents different causes of {@link TeleportationException}s.
*/
public enum Type {
TELEPORTER_NOT_FOUND,
@@ -119,9 +119,9 @@ public class TimedTeleport extends Teleport implements Runnable {
}
/**
* Ticks a timed teleport, decrementing the time left until the teleport is complete
* <p>
* A timed teleport will be canceled if certain criteria are met:
* Ticks a timed teleport, decrementing the time left until the teleport is complete.
*
* <p>A timed teleport will be canceled if certain criteria are met:
* <ul>
* <li>The player has left the server</li>
* <li>The plugin is disabling</li>
@@ -169,9 +169,9 @@ public class TimedTeleport extends Teleport implements Runnable {
private boolean hasTeleporterMoved() {
final double maxMovementDistance = 0.1d;
double movementDistance = Math.abs(startLocation.getX() - teleporter.getPosition().getX()) +
Math.abs(startLocation.getY() - teleporter.getPosition().getY()) +
Math.abs(startLocation.getZ() - teleporter.getPosition().getZ());
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;
}
@@ -36,14 +36,15 @@ public record Username(@NotNull String name) implements Teleportable, Target {
/**
* Search for a local {@link OnlineUser} by their name.
*
* <p>If a user by the name provided is on the {@link HuskHomes#getPlayerList() player list}, then this
* method will search for the user by exact name.
*
* <p>Otherwise, the lookup will first attempt to find the user by exact name, and if that fails, it will search for
* the closest name match.
*
* @param plugin The instance of {@link HuskHomes}
* @return An {@link Optional} containing the {@link OnlineUser} if found
* @throws TeleportationException If the user is not found
* @implNote If a user by the name provided is on the {@link HuskHomes#getPlayerList() player list}, then this
* method will search for the user by exact name.
* <p>
* Otherwise, the lookup will first attempt to find the user by exact name, and if that fails, it will search for
* the closest name match.
*/
@NotNull
public Optional<OnlineUser> findLocally(@NotNull HuskHomes plugin) {
@@ -52,7 +53,7 @@ public record Username(@NotNull String name) implements Teleportable, Target {
}
/**
* Get the username {@link String} being represented by this object
* Get the username {@link String} being represented by this object.
*
* @return the username
*/
@@ -38,7 +38,7 @@ import org.jetbrains.annotations.NotNull;
import java.util.*;
/**
* A cross-platform representation of a logged-in {@link User}
* A cross-platform representation of a logged-in {@link User}.
*/
public abstract class OnlineUser extends User implements Teleportable, CommandUser {
@@ -47,29 +47,28 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
}
/**
* Returns the current {@link Position} of this player
* Returns the current {@link Position} of this player.
*
* @return the player's current {@link Position}
*/
public abstract Position getPosition();
/**
* Returns the player's current bed or respawn anchor {@link Position}
* Returns the player's current bed or respawn anchor {@link Position}.
*
* @return an optional with the player's current bed or respawn anchor {@link Position} if it has been set,
* otherwise an {@link Optional#empty()}
* @return the player's current respawn {@link Position} if it has been set, or {@link Optional#empty()}
*/
public abstract Optional<Position> getBedSpawnPosition();
/**
* Returns the health of this player
* Returns the health of this player.
*
* @return the player's health points
*/
public abstract double getHealth();
/**
* Returns if the player has the permission node
* Returns if the player has the permission node.
*
* @param node The permission node string
* @return {@code true} if the player has the node; {@code false} otherwise
@@ -77,7 +76,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
public abstract boolean hasPermission(@NotNull String node);
/**
* Returns a {@link Map} of a player's permission nodes
* Returns a {@link Map} of a player's permission nodes.
*
* @return a {@link Map} of all permissions this player has to their set values
*/
@@ -85,7 +84,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
public abstract Map<String, Boolean> getPermissions();
/**
* Dispatch a MineDown-formatted title or subtitle to the player
* Dispatch a MineDown-formatted title or subtitle to the player.
*
* @param mineDown the parsed {@link MineDown} to send
* @param subTitle whether to send the title as a subtitle ({@code true} for a subtitle, {@code false} for a title)
@@ -97,7 +96,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
}
/**
* Dispatch a MineDown-formatted action bar message to this player
* Dispatch a MineDown-formatted action bar message to this player.
*
* @param mineDown the parsed {@link MineDown} to send
*/
@@ -109,7 +108,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
/**
* Dispatch a MineDown-formatted chat message to this player
* Dispatch a MineDown-formatted chat message to this player.
*
* @param mineDown the parsed {@link MineDown} to send
*/
@@ -120,7 +119,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
}
/**
* Dispatch a MineDown-formatted message to this player
* Dispatch a MineDown-formatted message to this player.
*
* @param mineDown the parsed {@link MineDown} to send
* @param slot the {@link Locales.DisplaySlot} to send the message to
@@ -138,25 +137,26 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
}
/**
* Dispatch a Minecraft translatable keyed-message to this player
* Dispatch a Minecraft translatable keyed-message to this player.
*
* <p>This method is intended for use with Minecraft's built-in translation keys.
* If the key is invalid, it will be substituted with {@code minecraft:block.minecraft.spawn.not_valid}
*
* @param translationKey the translation key of the message to send
* @implNote This method is intended for use with Minecraft's built-in translation keys. If the key is invalid,
* it will be substituted with {@code minecraft:block.minecraft.spawn.not_valid}
*/
public void sendTranslatableMessage(@Subst(Key.MINECRAFT_NAMESPACE + "block.minecraft.spawn.not_valid")
@NotNull String translationKey) {
@NotNull String translationKey) {
getAudience().sendMessage(Component.translatable(translationKey));
}
/**
* Play the specified sound to this player
* Play the specified sound to this player.
*
* @param soundEffect the sound effect to play. If the sound name is invalid, the sound will not play
* @implNote If the key is invalid, it will be substituted with {@code minecraft:block.note_block.banjo}
*/
public void playSound(@Subst(Key.MINECRAFT_NAMESPACE + "block.note_block.banjo")
@NotNull String soundEffect) throws IllegalArgumentException {
@NotNull String soundEffect) throws IllegalArgumentException {
try {
getAudience().playSound(
Sound.sound(Key.key(soundEffect), Sound.Source.PLAYER, 1.0f, 1.0f),
@@ -168,7 +168,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
}
/**
* Get the adventure {@link Audience} for this player
* Get the adventure {@link Audience} for this player.
*
* @return the adventure {@link Audience} for this player
*/
@@ -176,16 +176,16 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
public abstract Audience getAudience();
/**
* Teleport a player to the specified local {@link Location}
* Teleport a player to the specified local {@link Location}.
*
* @param location the {@link Location} to teleport the player to
* @param asynchronous if the teleport should be asynchronous
* @param location the {@link Location} to teleport the player to
* @param async if the teleport should be asynchronous
* @throws TeleportationException if the teleport fails
*/
public abstract void teleportLocally(@NotNull Location location, boolean asynchronous) throws TeleportationException;
public abstract void teleportLocally(@NotNull Location location, boolean async) throws TeleportationException;
/**
* Send a plugin message to the user
* Send a plugin message to the user.
*
* @param channel channel to send it on
* @param message byte array of message data
@@ -193,21 +193,21 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
public abstract void sendPluginMessage(@NotNull String channel, byte[] message);
/**
* Returns if a player is moving (i.e. they have momentum)
* Returns if a player is moving (i.e., they have momentum).
*
* @return {@code true} if the player is moving; {@code false} otherwise
*/
public abstract boolean isMoving();
/**
* Returns if the player is tagged as being "vanished" by a /vanish plugin
* Returns if the player is tagged as being "vanished" by a /vanish plugin.
*
* @return {@code true} if the player is tagged as being "vanished" by a /vanish plugin; {@code false} otherwise
*/
public abstract boolean isVanished();
/**
* Get the maximum number of homes this user may set
* Get the maximum number of homes this user may set.
*
* @param defaultMaxHomes the default maximum number of homes if the user has not set a custom value
* @param stack whether to stack numerical permissions that grant the user extra max homes
@@ -226,7 +226,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
}
/**
* Get the number of homes this user may make public
* Get the number of homes this user may make public.
*
* @param defaultPublicHomes the default number of homes this user may make public
* @param stack whether to stack numerical permissions that grant the user extra public homes
@@ -245,7 +245,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
}
/**
* Get the number of free home slots this user may set
* Get the number of free home slots this user may set.
*
* @param defaultFreeHomes the default number of free home slots to give this user
* @param stack whether to stack numerical permissions that grant the user extra free homes
@@ -264,7 +264,7 @@ public abstract class OnlineUser extends User implements Teleportable, CommandUs
}
/**
* Gets a list of numbers from the prefixed permission nodes
* Gets a list of numbers from the prefixed permission nodes.
*
* @param nodePrefix the prefix of the permission nodes to get
* @return a list of numbers from the prefixed permission nodes, sorted by size
@@ -27,7 +27,7 @@ import java.time.temporal.ChronoUnit;
import java.util.UUID;
/**
* Represents data about a player on the server
* Represents data about a player on the server.
*/
public class SavedUser {
@@ -36,7 +36,7 @@ public class SavedUser {
private boolean ignoringTeleports;
/**
* Create a new SavedUser object
* Create a new SavedUser object.
*
* @param user The user to create the object for
* @param homeSlots The number of home slots the user has
@@ -49,12 +49,15 @@ public class SavedUser {
}
/**
* @deprecated See {@link #SavedUser(User, int, boolean)} to create a SavedUser object
* <p>
* User RTP cooldowns are no longer stored in {@link SavedUser} objects,
* Create a new SavedUser object.
*
* <p>Please note that User RTP cooldowns are no longer stored in {@link SavedUser} objects;
* please use the new API methods for getting/setting cooldowns
*
* @deprecated See {@link #SavedUser(User, int, boolean)} to create a SavedUser object.
*/
@Deprecated(since = "4.4", forRemoval = true)
@SuppressWarnings("unused")
public SavedUser(@NotNull User user, int homeSlots, boolean ignoringTeleports, @NotNull Instant rtpCooldown) {
this(user, homeSlots, ignoringTeleports);
}
@@ -91,6 +94,8 @@ public class SavedUser {
}
/**
* Get the user's RTP cooldown. This method will always return 5 seconds before the current time since v4.4.
*
* @deprecated Use the new API methods for setting and getting cooldowns
*/
@NotNull
@@ -100,9 +105,12 @@ public class SavedUser {
}
/**
* Set the user's RTP cooldown. This method has no effect since v4.4.
*
* @deprecated Use the new API methods for setting and getting cooldowns
*/
@Deprecated(since = "4.4", forRemoval = true)
@SuppressWarnings("unused")
public void setRtpCooldown(@NotNull Instant rtpCooldown) {
// Do nothing
}
@@ -24,7 +24,7 @@ import org.jetbrains.annotations.NotNull;
import java.util.UUID;
/**
* Represents a user who has data saved in the database
* Represents a user who has data saved in the database.
*/
public class User {
@@ -35,7 +35,7 @@ public class User {
private final String username;
/**
* Get a user from a {@link UUID} and username
* Get a user from a {@link UUID} and username.
*
* @param uuid Minecraft account {@link UUID} of the player
* @param username Username of the player
@@ -31,16 +31,15 @@ public interface SafetyResolver {
int SEARCH_RADIUS = 2;
/**
* Returns a safe ground location for the specified {@link Location} if possible
* Returns a safe ground location for the specified {@link Location} if possible.
*
* @param location the {@link Location} to find a safe ground location for
* @return a {@link CompletableFuture} that will complete with an optional of the safe ground position, if it is
* possible to find one
* @return a {@link CompletableFuture} with an optional safe ground position, if one could be found
*/
CompletableFuture<Optional<Location>> findSafeGroundLocation(@NotNull Location location);
/**
* Returns if the block, by provided identifier, is unsafe to stand on
* Returns if the block, by provided identifier, is unsafe to stand on.
*
* @param blockId The block identifier (e.g. {@code minecraft:stone})
* @return {@code true} if the block is on the unsafe blocks list, {@code false} otherwise
@@ -50,10 +49,10 @@ public interface SafetyResolver {
}
/**
* Returns if the block, by provided identifier, is unsafe to stand in
* Returns if the block, by provided identifier, is unsafe to stand in.
*
* @param blockId The block identifier (e.g. {@code minecraft:stone})
* @return {@code true} if the block is able to be occupied, {@code false} otherwise
* @return {@code true} if the block can be occupied, {@code false} otherwise
*/
default boolean isBlockSafeForOccupation(@NotNull String blockId) {
return !getPlugin().getUnsafeBlocks().isUnsafeToOccupy(blockId);
@@ -30,15 +30,15 @@ import java.util.Optional;
import java.util.StringJoiner;
/**
* Class for validating and performing economy and cooldown transactions involving {@link Action}s
* Class for validating and performing economy and cooldown transactions involving {@link Action}s.
*/
public interface TransactionResolver {
/**
* Validates whether an {@link OnlineUser} can perform an {@link Action}, in terms of whether they have sufficient
* funds and are not on cooldown. This method will also send the user a message if they cannot perform the action.
* <p>
* This method will return {@code true} if the user has sufficient funds and is not on cooldown, otherwise
*
* <p>This method will return {@code true} if the user has sufficient funds and is not on cooldown, otherwise
* {@code false}.
*
* @param player the {@link OnlineUser player} to perform the check on
@@ -52,11 +52,13 @@ public interface TransactionResolver {
// Validates if the user has funds to perform an action
private boolean hasFunds(@NotNull OnlineUser player, @NotNull Action action) {
return getPlugin().getSettings().getEconomyCost(action).map(Math::abs)
.flatMap(c -> player.hasPermission(Action.BYPASS_ECONOMY_PERMISSION) ? Optional.empty() : Optional.of(c))
.flatMap(c -> player.hasPermission(Action.BYPASS_ECONOMY_PERMISSION)
? Optional.empty() : Optional.of(c))
.map(c -> getEconomyHook()
.map(hook -> {
if (hook.getPlayerBalance(player) < c) {
getPlugin().getLocales().getLocale("error_insufficient_funds", hook.formatCurrency(c))
getPlugin().getLocales().getLocale("error_insufficient_funds",
hook.formatCurrency(c))
.ifPresent(player::sendMessage);
return false;
}
@@ -110,7 +112,7 @@ public interface TransactionResolver {
}
/**
* Execute an economy transaction if needed, updating the player's balance
* Execute an economy transaction if needed, updating the player's balance.
*
* @param player the {@link OnlineUser player} to deduct the cost from if needed
* @param action the {@link Action action} to deduct the cost from if needed
@@ -118,7 +120,8 @@ public interface TransactionResolver {
default void performTransaction(@NotNull OnlineUser player, @NotNull Action action) {
getEconomyHook().ifPresent(hook -> getPlugin().getSettings()
.getEconomyCost(action).map(Math::abs)
.flatMap(c -> player.hasPermission(Action.BYPASS_ECONOMY_PERMISSION) ? Optional.empty() : Optional.of(c))
.flatMap(c -> player.hasPermission(Action.BYPASS_ECONOMY_PERMISSION)
? Optional.empty() : Optional.of(c))
.ifPresent(cost -> {
hook.changePlayerBalance(player, -cost);
hook.notifyDeducted(player, getPlugin(), action);
@@ -131,16 +134,9 @@ public interface TransactionResolver {
}
/**
* @deprecated use {@link #validateTransaction(OnlineUser, Action)} instead
*/
@SuppressWarnings("removal")
@Deprecated(since = "4.4", forRemoval = true)
default boolean canPerformTransaction(@NotNull OnlineUser player, @NotNull EconomyHook.Action action) {
return this.validateTransaction(player, action.getTransactionAction());
}
/**
* @deprecated use {@link #performTransaction(OnlineUser, Action)} instead
* Execute an economy transaction if needed, updating the player's balance.
*
* @deprecated use {@link #performTransaction(OnlineUser, Action)} instead.
*/
@SuppressWarnings("removal")
@Deprecated(since = "4.4", forRemoval = true)
@@ -149,7 +145,19 @@ public interface TransactionResolver {
}
/**
* Get the {@link EconomyHook} instance, if present
* Get whether the {@link OnlineUser} can perform the {@link EconomyHook.Action},
* in terms of whether they have sufficient funds and are not on cooldown.
*
* @deprecated use {@link #validateTransaction(OnlineUser, Action)} instead.
*/
@SuppressWarnings("removal")
@Deprecated(since = "4.4", forRemoval = true)
default boolean canPerformTransaction(@NotNull OnlineUser player, @NotNull EconomyHook.Action action) {
return this.validateTransaction(player, action.getTransactionAction());
}
/**
* Get the {@link EconomyHook} instance, if present.
*
* @return the {@link EconomyHook} instance
*/
@@ -162,7 +170,7 @@ public interface TransactionResolver {
HuskHomes getPlugin();
/**
* Represents actions that can be the subject of a transaction
* Represents actions that can be the subject of a transaction.
*/
enum Action {
@@ -204,7 +212,7 @@ public interface TransactionResolver {
}
/**
* Create an action with a default cost
* Create an action with a default cost.
*
* @return the default cost
*/
@@ -213,7 +221,7 @@ public interface TransactionResolver {
}
/**
* Get the default cooldown for this action (in seconds)
* Get the default cooldown for this action (in seconds).
*
* @return the default cooldown in seconds
*/
@@ -39,6 +39,28 @@ public class UnsafeBlocks {
@YamlKey("safe_occupation_blocks")
public List<String> safeOccupationBlocks;
/**
* Returns if the block, by provided identifier, are unsafe.
*
* @param blockId The block identifier (e.g. {@code minecraft:stone})
* @return {@code true} if the block is on the unsafe blocks list, {@code false} otherwise
*/
public boolean isUnsafe(@NotNull String blockId) {
return unsafeBlocks.contains(this.formatBlockId(blockId));
}
/**
* Returns if the block, by provided identifier, is unsafe to stand in.
*
* @param blockId The block identifier (e.g. {@code minecraft:stone})
* @return {@code true} if the block is on the unsafe blocks list, {@code false} otherwise
*/
public boolean isUnsafeToOccupy(@NotNull String blockId) {
return !safeOccupationBlocks.contains(this.formatBlockId(blockId));
}
// Format a block ID to be in the format namespace:id
@NotNull
private String formatBlockId(@NotNull String blockId) {
if (!blockId.startsWith(Key.MINECRAFT_NAMESPACE + ":")) {
blockId = Key.MINECRAFT_NAMESPACE + ":" + blockId;
@@ -46,28 +68,6 @@ public class UnsafeBlocks {
return blockId;
}
/**
* Returns if the block, by provided identifier, is unsafe
*
* @param blockId The block identifier (e.g. {@code minecraft:stone})
* @return {@code true} if the block is on the unsafe blocks list, {@code false} otherwise
*/
public boolean isUnsafe(@NotNull String blockId) {
blockId = this.formatBlockId(blockId);
return unsafeBlocks.contains(blockId);
}
/**
* Returns if the block, by provided identifier, is unsafe to stand in
*
* @param blockId The block identifier (e.g. {@code minecraft:stone})
* @return {@code true} if the block is on the unsafe blocks list, {@code false} otherwise
*/
public boolean isUnsafeToOccupy(@NotNull String blockId) {
blockId = this.formatBlockId(blockId);
return !safeOccupationBlocks.contains(blockId);
}
@SuppressWarnings("unused")
public UnsafeBlocks() {
}
@@ -33,7 +33,8 @@ public class ValidationException extends IllegalArgumentException {
this.type = type;
}
public void dispatchHomeError(@NotNull CommandUser viewer, boolean other, @NotNull HuskHomes plugin, @NotNull String... args) {
public void dispatchHomeError(@NotNull CommandUser viewer, boolean other, @NotNull HuskHomes plugin,
@NotNull String... args) {
switch (type) {
case NOT_FOUND -> plugin.getLocales()
.getLocale(other ? "error_home_invalid_other" : "error_home_invalid", args)
@@ -48,13 +49,18 @@ public class ValidationException extends IllegalArgumentException {
.getLocale("error_home_description_characters", args)
.ifPresent(viewer::sendMessage);
case NOT_ENOUGH_HOME_SLOTS, REACHED_MAX_HOMES -> plugin.getLocales()
.getLocale("error_set_home_maximum_homes", Integer.toString(plugin.getManager().homes()
.getLocale("error_set_home_maximum_homes",
Integer.toString(plugin.getManager().homes()
.getMaxHomes(viewer instanceof OnlineUser user ? user : null)))
.ifPresent(viewer::sendMessage);
case REACHED_MAX_PUBLIC_HOMES -> plugin.getLocales()
.getLocale("error_edit_home_maximum_public_homes", Integer.toString(plugin.getManager().homes()
.getLocale("error_edit_home_maximum_public_homes",
Integer.toString(plugin.getManager().homes()
.getMaxPublicHomes(viewer instanceof OnlineUser user ? user : null)))
.ifPresent(viewer::sendMessage);
default -> {
// Do nothing (silently handle validation errors)
}
}
}
@@ -72,6 +78,9 @@ public class ValidationException extends IllegalArgumentException {
case DESCRIPTION_INVALID -> plugin.getLocales()
.getLocale("error_warp_description_characters", args)
.ifPresent(viewer::sendMessage);
default -> {
// Do nothing (silently handle validation errors)
}
}
}
@@ -82,7 +91,7 @@ public class ValidationException extends IllegalArgumentException {
}
/**
* The type of validation error
* The type of validation error.
*/
public enum Type {
NOT_FOUND,
@@ -37,7 +37,7 @@ public class Validator {
}
/**
* Check if a name is valid
* Check if a name is valid.
*
* @param name The name to check
* @return True if the name is valid as per the plugin settings, false otherwise
@@ -49,7 +49,7 @@ public class Validator {
}
/**
* Validate home and warp descriptions
* Validate home and warp descriptions.
*
* @param description The meta to validate
* @return Whether the meta is valid against the plugin settings