Fix formatting to use spaces instead of tabs.

This commit is contained in:
tastybento 2023-12-04 17:44:49 -08:00
parent 22f398fe53
commit 103340657c
595 changed files with 28738 additions and 27474 deletions

View File

@ -27,19 +27,20 @@ public class BStats {
private Metrics metrics;
/**
* Counts of the islands that got created.
* It is reset to 0 when BStats gets the data.
* Counts of the islands that got created. It is reset to 0 when BStats gets the
* data.
*
* @since 1.1
*/
private int islandsCreatedCount = 0;
/**
* Contains the amount of connected players since last data send.
*
* @since 1.17.1
*/
private final Set<UUID> connectedPlayerSet = new HashSet<>();
BStats(BentoBox plugin) {
this.plugin = plugin;
}
@ -95,7 +96,9 @@ public class BStats {
}
/**
* Increases the count of islands that got create since the last "data get" request from BStats.
* Increases the count of islands that got create since the last "data get"
* request from BStats.
*
* @since 1.1
*/
public void increaseIslandsCreatedCount() {
@ -104,6 +107,7 @@ public class BStats {
/**
* Adds given UUID to the connected player set.
*
* @param uuid UUID of a player who logins.
* @since 1.17.1
*/
@ -113,6 +117,7 @@ public class BStats {
/**
* Sends the enabled addons (except GameModeAddons) of this server.
*
* @since 1.1
*/
private void registerAddonsChart() {
@ -127,6 +132,7 @@ public class BStats {
/**
* Sends the enabled GameModeAddons of this server.
*
* @since 1.4.0
*/
private void registerGameModeAddonsChart() {
@ -141,6 +147,7 @@ public class BStats {
/**
* Sends the enabled Hooks of this server.
*
* @since 1.6.0
*/
private void registerHooksChart() {
@ -153,6 +160,7 @@ public class BStats {
/**
* Sends the "category" this server is in depending on how many players it has.
*
* @since 1.6.0
*/
private void registerPlayersPerServerChart() {
@ -160,19 +168,28 @@ public class BStats {
int players = this.connectedPlayerSet.size();
this.connectedPlayerSet.clear();
if (players <= 0) return "0";
else if (players <= 10) return "1-10";
else if (players <= 30) return "11-30";
else if (players <= 50) return "31-50";
else if (players <= 100) return "51-100";
else if (players <= 150) return "101-150";
else if (players <= 200) return "151-200";
else return "201+";
if (players <= 0)
return "0";
else if (players <= 10)
return "1-10";
else if (players <= 30)
return "11-30";
else if (players <= 50)
return "31-50";
else if (players <= 100)
return "51-100";
else if (players <= 150)
return "101-150";
else if (players <= 200)
return "151-200";
else
return "201+";
}));
}
/**
* Sends the "flags display mode" of all the online players.
*
* @since 1.6.0
*/
private void registerFlagsDisplayModeChart() {
@ -194,34 +211,37 @@ public class BStats {
/**
* Sends the enabled addons (except GameModeAddons) of this server as bar chart.
*
* @since 1.17.1
*/
private void registerAddonsBarChart() {
metrics.addCustomChart(new SimpleBarChart("addonsBar", () -> {
Map<String, Integer> values = new HashMap<>();
plugin.getAddonsManager().getEnabledAddons().stream()
.filter(addon -> !(addon instanceof GameModeAddon) && addon.getDescription().isMetrics())
.forEach(addon -> values.put(addon.getDescription().getName(), 1));
.filter(addon -> !(addon instanceof GameModeAddon) && addon.getDescription().isMetrics())
.forEach(addon -> values.put(addon.getDescription().getName(), 1));
return values;
}));
}
/**
* Sends the enabled GameModeAddons of this server as a bar chart.
*
* @since 1.17.1
*/
private void registerGameModeAddonsBarChart() {
metrics.addCustomChart(new SimpleBarChart("gameModeAddonsBar", () -> {
Map<String, Integer> values = new HashMap<>();
plugin.getAddonsManager().getGameModeAddons().stream()
.filter(gameModeAddon -> gameModeAddon.getDescription().isMetrics())
.forEach(gameModeAddon -> values.put(gameModeAddon.getDescription().getName(), 1));
.filter(gameModeAddon -> gameModeAddon.getDescription().isMetrics())
.forEach(gameModeAddon -> values.put(gameModeAddon.getDescription().getName(), 1));
return values;
}));
}
/**
* Sends the enabled Hooks of this server as a bar chart.
*
* @since 1.17.1
*/
private void registerHooksBarChart() {

View File

@ -53,6 +53,7 @@ import world.bentobox.bentobox.versions.ServerCompatibility;
/**
* Main BentoBox class
*
* @author tastybento, Poslovitch
*/
public class BentoBox extends JavaPlugin implements Listener {
@ -97,7 +98,7 @@ public class BentoBox extends JavaPlugin implements Listener {
private boolean shutdown;
@Override
public void onEnable(){
public void onEnable() {
if (!ServerCompatibility.getInstance().checkCompatibility().isCanLaunch()) {
// The server's most likely incompatible.
// Show a warning
@ -105,7 +106,9 @@ public class BentoBox extends JavaPlugin implements Listener {
logWarning("BentoBox may not be compatible with this server!");
logWarning("BentoBox is tested only on the following Spigot versions:");
List<String> versions = ServerCompatibility.ServerVersion.getVersions(ServerCompatibility.Compatibility.COMPATIBLE, ServerCompatibility.Compatibility.SUPPORTED)
List<String> versions = ServerCompatibility.ServerVersion
.getVersions(ServerCompatibility.Compatibility.COMPATIBLE,
ServerCompatibility.Compatibility.SUPPORTED)
.stream().map(ServerCompatibility.ServerVersion::toString).toList();
logWarning(String.join(", ", versions));
@ -114,7 +117,8 @@ public class BentoBox extends JavaPlugin implements Listener {
// Not loaded
isLoaded = false;
// Store the current millis time so we can tell how many ms it took for BSB to fully load.
// Store the current millis time so we can tell how many ms it took for BSB to
// fully load.
final long loadStart = System.currentTimeMillis();
// Save the default config from config.yml
@ -163,7 +167,8 @@ public class BentoBox extends JavaPlugin implements Listener {
// Load hooks
hooksManager = new HooksManager(this);
// Load addons. Addons may load worlds, so they must go before islands are loaded.
// Load addons. Addons may load worlds, so they must go before islands are
// loaded.
addonsManager = new AddonsManager(this);
addonsManager.loadAddons();
@ -209,12 +214,14 @@ public class BentoBox extends JavaPlugin implements Listener {
if (!playersManager.isSaveTaskRunning()) {
playersManager.saveAll(true);
} else {
getLogger().warning("Tried to start a player data save task while the previous auto save was still running!");
getLogger().warning(
"Tried to start a player data save task while the previous auto save was still running!");
}
if (!islandsManager.isSaveTaskRunning()) {
islandsManager.saveAll(true);
} else {
getLogger().warning("Tried to start a island data save task while the previous auto save was still running!");
getLogger().warning(
"Tried to start a island data save task while the previous auto save was still running!");
}
}, getSettings().getDatabaseBackupPeriod() * 20 * 60L, getSettings().getDatabaseBackupPeriod() * 20 * 60L);
@ -232,20 +239,20 @@ public class BentoBox extends JavaPlugin implements Listener {
islandWorldManager.registerWorldsToMultiverse(true);
// TODO: re-enable after implementation
//hooksManager.registerHook(new DynmapHook());
// hooksManager.registerHook(new DynmapHook());
// TODO: re-enable after rework
//hooksManager.registerHook(new LangUtilsHook());
// hooksManager.registerHook(new LangUtilsHook());
webManager = new WebManager(this);
final long enableTime = System.currentTimeMillis() - enableStart;
// Show banner
User.getInstance(Bukkit.getConsoleSender()).sendMessage("successfully-loaded",
TextVariables.VERSION, instance.getDescription().getVersion(),
"[time]", String.valueOf(loadTime + enableTime));
User.getInstance(Bukkit.getConsoleSender()).sendMessage("successfully-loaded", TextVariables.VERSION,
instance.getDescription().getVersion(), "[time]", String.valueOf(loadTime + enableTime));
// Poll for blueprints loading to be finished - async so could be a completely variable time
// Poll for blueprints loading to be finished - async so could be a completely
// variable time
blueprintLoadingTask = Bukkit.getScheduler().runTaskTimer(instance, () -> {
if (getBlueprintsManager().isBlueprintsLoaded()) {
blueprintLoadingTask.cancel();
@ -253,7 +260,8 @@ public class BentoBox extends JavaPlugin implements Listener {
isLoaded = true;
this.addonsManager.allLoaded();
// Run ready commands
settings.getReadyCommands().forEach(cmd -> Bukkit.getServer().dispatchCommand(getServer().getConsoleSender(), cmd));
settings.getReadyCommands()
.forEach(cmd -> Bukkit.getServer().dispatchCommand(getServer().getConsoleSender(), cmd));
// Fire plugin ready event - this should go last after everything else
Bukkit.getPluginManager().callEvent(new BentoBoxReadyEvent());
instance.log("All blueprints loaded.");
@ -262,9 +270,12 @@ public class BentoBox extends JavaPlugin implements Listener {
if (getSettings().getDatabaseType().equals(DatabaseSetup.DatabaseType.YAML)) {
logWarning("*** You're still using YAML database ! ***");
logWarning("This database type is being deprecated from BentoBox as some official addons encountered difficulties supporting it correctly.");
logWarning("You should switch ASAP to an alternative database type. Please refer to the comments in BentoBox's config.yml.");
logWarning("There is NO guarantee YAML database will remain properly supported in the following updates, and its usage should as such be considered a non-viable situation.");
logWarning(
"This database type is being deprecated from BentoBox as some official addons encountered difficulties supporting it correctly.");
logWarning(
"You should switch ASAP to an alternative database type. Please refer to the comments in BentoBox's config.yml.");
logWarning(
"There is NO guarantee YAML database will remain properly supported in the following updates, and its usage should as such be considered a non-viable situation.");
logWarning("*** *** *** *** *** *** *** *** *** *** ***");
}
}
@ -333,18 +344,22 @@ public class BentoBox extends JavaPlugin implements Listener {
@EventHandler
public void onServerStop(ServerCommandEvent e) {
/* This is no longer needed as with https://github.com/Multiverse/Multiverse-Core/releases/tag/4.3.12 (or maybe earlier) the issue
* is fixed where the generator was not remembered across reboots.
/*
* This is no longer needed as with
* https://github.com/Multiverse/Multiverse-Core/releases/tag/4.3.12 (or maybe
* earlier) the issue is fixed where the generator was not remembered across
* reboots.
*/
/*
if (islandWorldManager != null && (e.getCommand().equalsIgnoreCase("stop") || e.getCommand().equalsIgnoreCase("restart"))) {
// Unregister any MV worlds if () {
//islandWorldManager.registerWorldsToMultiverse(false);
}*/
* if (islandWorldManager != null && (e.getCommand().equalsIgnoreCase("stop") ||
* e.getCommand().equalsIgnoreCase("restart"))) { // Unregister any MV worlds if
* () { //islandWorldManager.registerWorldsToMultiverse(false); }
*/
}
/**
* Returns the player manager
*
* @return the player manager
* @see #getPlayersManager()
*/
@ -354,6 +369,7 @@ public class BentoBox extends JavaPlugin implements Listener {
/**
* Returns the player manager
*
* @return the player manager
* @see #getPlayers()
* @since 1.16.0
@ -364,6 +380,7 @@ public class BentoBox extends JavaPlugin implements Listener {
/**
* Returns the island manager
*
* @return the island manager
* @see #getIslandsManager()
*/
@ -373,6 +390,7 @@ public class BentoBox extends JavaPlugin implements Listener {
/**
* Returns the island manager
*
* @return the island manager
* @see #getIslands()
* @since 1.16.0
@ -439,15 +457,18 @@ public class BentoBox extends JavaPlugin implements Listener {
}
/**
* Loads the settings from the config file.
* If it fails, it can shut the plugin down.
* Loads the settings from the config file. If it fails, it can shut the plugin
* down.
*
* @return {@code true} if it loaded successfully.
* @since 1.3.0
*/
public boolean loadSettings() {
log("Loading Settings from config.yml...");
// Load settings from config.yml. This will check if there are any issues with it too.
if (configObject == null) configObject = new Config<>(this, Settings.class);
// Load settings from config.yml. This will check if there are any issues with
// it too.
if (configObject == null)
configObject = new Config<>(this, Settings.class);
settings = configObject.loadConfigObject();
if (settings == null) {
// Settings did not load correctly. Disable plugin.
@ -460,7 +481,8 @@ public class BentoBox extends JavaPlugin implements Listener {
@Override
public void saveConfig() {
if (settings != null) configObject.saveConfigObject(settings);
if (settings != null)
configObject.saveConfigObject(settings);
}
/**
@ -490,8 +512,10 @@ public class BentoBox extends JavaPlugin implements Listener {
}
/**
* Logs the stacktrace of a Throwable that was thrown by an error.
* It should be used preferably instead of {@link Throwable#printStackTrace()} as it does not risk exposing sensitive information.
* Logs the stacktrace of a Throwable that was thrown by an error. It should be
* used preferably instead of {@link Throwable#printStackTrace()} as it does not
* risk exposing sensitive information.
*
* @param throwable the Throwable that was thrown by an error.
* @since 1.3.0
*/
@ -505,6 +529,7 @@ public class BentoBox extends JavaPlugin implements Listener {
/**
* Returns the instance of the {@link BlueprintsManager}.
*
* @return the {@link BlueprintsManager}.
* @since 1.5.0
*/
@ -513,8 +538,9 @@ public class BentoBox extends JavaPlugin implements Listener {
}
/**
* Returns whether BentoBox is fully loaded or not.
* This basically means that all managers are instantiated and can therefore be safely accessed.
* Returns whether BentoBox is fully loaded or not. This basically means that
* all managers are instantiated and can therefore be safely accessed.
*
* @return whether BentoBox is fully loaded or not.
*/
public boolean isLoaded() {
@ -530,6 +556,7 @@ public class BentoBox extends JavaPlugin implements Listener {
/**
* Convenience method to get the VaultHook.
*
* @return the Vault hook
*/
public Optional<VaultHook> getVault() {
@ -570,15 +597,21 @@ public class BentoBox extends JavaPlugin implements Listener {
// Overriding default JavaPlugin methods
/* (non-Javadoc)
* @see org.bukkit.plugin.java.JavaPlugin#getDefaultWorldGenerator(java.lang.String, java.lang.String)
/*
* (non-Javadoc)
*
* @see
* org.bukkit.plugin.java.JavaPlugin#getDefaultWorldGenerator(java.lang.String,
* java.lang.String)
*/
@Override
public ChunkGenerator getDefaultWorldGenerator(@NonNull String worldName, String id) {
return addonsManager.getDefaultWorldGenerator(worldName, id);
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see org.bukkit.plugin.java.JavaPlugin#reloadConfig()
*/
@Override
@ -588,6 +621,7 @@ public class BentoBox extends JavaPlugin implements Listener {
/**
* Check if plug has shutdown. Used to close databases that are running async.
*
* @return true if plugin has shutdown
* @since 1.13.0
*/

File diff suppressed because it is too large Load Diff

View File

@ -27,8 +27,8 @@ import world.bentobox.bentobox.managers.IslandsManager;
import world.bentobox.bentobox.managers.PlayersManager;
/**
* Add-on class for BentoBox. Extend this to create an add-on. The operation
* and methods are very similar to Bukkit's JavaPlugin.
* Add-on class for BentoBox. Extend this to create an add-on. The operation and
* methods are very similar to Bukkit's JavaPlugin.
*
* @author tastybento, ComminQ_Q
*/
@ -47,11 +47,11 @@ public abstract class Addon {
}
/**
* Executes code when enabling the addon.
* This is called after {@link #onLoad()}.
* <br/>
* Note that commands and worlds registration <b>must</b> be done in {@link #onLoad()}, if need be.
* Failure to do so <b>will</b> result in issues such as tab-completion not working for commands.
* Executes code when enabling the addon. This is called after
* {@link #onLoad()}. <br/>
* Note that commands and worlds registration <b>must</b> be done in
* {@link #onLoad()}, if need be. Failure to do so <b>will</b> result in issues
* such as tab-completion not working for commands.
*/
public abstract void onEnable();
@ -61,16 +61,18 @@ public abstract class Addon {
public abstract void onDisable();
/**
* Executes code when loading the addon.
* This is called before {@link #onEnable()}.
* This <b>must</b> be used to setup configuration, worlds and commands.
* Executes code when loading the addon. This is called before
* {@link #onEnable()}. This <b>must</b> be used to setup configuration, worlds
* and commands.
*/
public void onLoad() {}
public void onLoad() {
}
/**
* Executes code when reloading the addon.
*/
public void onReload() {}
public void onReload() {
}
public BentoBox getPlugin() {
return BentoBox.getInstance();
@ -84,6 +86,7 @@ public abstract class Addon {
public enum State {
/**
* The addon has been correctly loaded.
*
* @since 1.1
*/
LOADED,
@ -99,7 +102,8 @@ public abstract class Addon {
DISABLED,
/**
* The addon has not been loaded because it requires a different version of BentoBox or of the server software.
* The addon has not been loaded because it requires a different version of
* BentoBox or of the server software.
*/
INCOMPATIBLE,
@ -109,7 +113,8 @@ public abstract class Addon {
MISSING_DEPENDENCY,
/**
* The addon loading or enabling process has been interrupted by an unhandled error.
* The addon loading or enabling process has been interrupted by an unhandled
* error.
*/
ERROR
}
@ -167,6 +172,7 @@ public abstract class Addon {
/**
* Gets the current {@link State} of this Addon.
*
* @return the current State of this Addon.
* @since 1.1
*/
@ -195,7 +201,8 @@ public abstract class Addon {
}
/**
* Register a listener for this addon. This MUST be used in order for the addon to be reloadable
* Register a listener for this addon. This MUST be used in order for the addon
* to be reloadable
*
* @param listener - listener
*/
@ -210,12 +217,14 @@ public abstract class Addon {
try {
getConfig().save(new File(dataFolder, ADDON_CONFIG_FILENAME));
} catch (IOException e) {
Bukkit.getLogger().severe("Could not save config! " + this.getDescription().getName() + " " + e.getMessage());
Bukkit.getLogger()
.severe("Could not save config! " + this.getDescription().getName() + " " + e.getMessage());
}
}
/**
* Discards any data in getConfig() and reloads from disk.
*
* @since 1.13.0
*/
public void reloadConfig() {
@ -235,10 +244,8 @@ public abstract class Addon {
* Saves a resource contained in this add-on's jar file to the addon's data
* folder.
*
* @param resourcePath
* in jar file
* @param replace
* - if true, will overwrite previous file
* @param resourcePath in jar file
* @param replace - if true, will overwrite previous file
*/
public void saveResource(String resourcePath, boolean replace) {
saveResource(resourcePath, dataFolder, replace, false);
@ -248,14 +255,11 @@ public abstract class Addon {
* Saves a resource contained in this add-on's jar file to the destination
* folder.
*
* @param jarResource
* in jar file
* @param destinationFolder
* on file system
* @param replace
* - if true, will overwrite previous file
* @param noPath
* - if true, the resource's path will be ignored when saving
* @param jarResource in jar file
* @param destinationFolder on file system
* @param replace - if true, will overwrite previous file
* @param noPath - if true, the resource's path will be ignored when
* saving
* @return file written, or null if none
*/
public File saveResource(String jarResource, File destinationFolder, boolean replace, boolean noPath) {
@ -298,9 +302,11 @@ public abstract class Addon {
/**
* Tries to load a YAML file from the Jar
*
* @param jarResource - YAML file in jar
* @return YamlConfiguration - may be empty
* @throws IOException - if the file cannot be found or loaded from the Jar
* @throws IOException - if the file cannot be found or loaded
* from the Jar
* @throws InvalidConfigurationException - if the yaml is malformed
*/
public YamlConfiguration getYamlFromJar(String jarResource) throws IOException, InvalidConfigurationException {
@ -322,6 +328,7 @@ public abstract class Addon {
/**
* Get the resource from Jar file
*
* @param jarResource - jar resource filename
* @return resource or null if there is a problem
*/
@ -343,6 +350,7 @@ public abstract class Addon {
}
return null;
}
/**
* Set the file that contains this addon
*
@ -372,6 +380,7 @@ public abstract class Addon {
/**
* Sets the addon's state.
*
* @param state the state to set
*/
public void setState(State state) {
@ -380,6 +389,7 @@ public abstract class Addon {
/**
* Get Players Manager
*
* @return Players manager
*/
public PlayersManager getPlayers() {
@ -388,14 +398,16 @@ public abstract class Addon {
/**
* Get Islands Manager
*
* @return Islands manager
*/
public IslandsManager getIslands() {
return getPlugin().getIslands();
}
/**
* Get Islands Manager
*
* @return Islands manager
* @see #getIslands()
* @since 1.17.1
@ -406,6 +418,7 @@ public abstract class Addon {
/**
* Get the Addon By Name
*
* @return Optional Addon
*/
public Optional<Addon> getAddonByName(String name) {
@ -425,8 +438,9 @@ public abstract class Addon {
}
/**
* Returns the permission prefix corresponding to this addon.
* It contains the addon's name plus a trailing dot.
* Returns the permission prefix corresponding to this addon. It contains the
* addon's name plus a trailing dot.
*
* @return Permission prefix string
*/
public String getPermissionPrefix() {
@ -435,6 +449,7 @@ public abstract class Addon {
/**
* Register request handler to answer requests from plugins.
*
* @param handler request handler
*/
public void registerRequestHandler(AddonRequestHandler handler) {
@ -443,25 +458,27 @@ public abstract class Addon {
/**
* Send request to addon.
* @param label label
*
* @param label label
* @param metaData meta data
* @return request response, null if no response.
*/
public Object request(String label, Map<String, Object> metaData) {
label = label.toLowerCase(Locale.ENGLISH);
AddonRequestHandler handler = requestHandlers.get(label);
if(handler != null) {
if (handler != null) {
return handler.handle(metaData);
} else {
return null;
}
}
/**
* Register a flag for this addon.
*
* @param flag the flag to register.
* @return {@code true} if the flag was registered successfully, {@code false} otherwise.
* @return {@code true} if the flag was registered successfully, {@code false}
* otherwise.
* @since 1.5.0
*/
public boolean registerFlag(Flag flag) {
@ -470,7 +487,9 @@ public abstract class Addon {
/**
* Called when all addons have been loaded by BentoBox
*
* @since 1.8.0
*/
public void allLoaded() {}
public void allLoaded() {
}
}

View File

@ -26,6 +26,7 @@ import world.bentobox.bentobox.managers.AddonsManager;
/**
* Loads addons and sets up permissions
*
* @author Tastybento, ComminQ
*/
public class AddonClassLoader extends URLClassLoader {
@ -36,25 +37,23 @@ public class AddonClassLoader extends URLClassLoader {
/**
* For testing only
* @param addon addon
* @param loader Addons Manager
*
* @param addon addon
* @param loader Addons Manager
* @param jarFile Jar File
* @throws MalformedURLException exception
*/
protected AddonClassLoader(Addon addon, AddonsManager loader, File jarFile) throws MalformedURLException {
super(new URL[]{jarFile.toURI().toURL()});
super(new URL[] { jarFile.toURI().toURL() });
this.addon = addon;
this.loader = loader;
}
public AddonClassLoader(AddonsManager addonsManager, YamlConfiguration data, File jarFile, ClassLoader parent)
throws InvalidAddonInheritException,
MalformedURLException,
InvalidDescriptionException,
InvalidAddonDescriptionException,
InstantiationException,
IllegalAccessException, InvocationTargetException, NoSuchMethodException {
super(new URL[]{jarFile.toURI().toURL()}, parent);
throws InvalidAddonInheritException, MalformedURLException, InvalidDescriptionException,
InvalidAddonDescriptionException, InstantiationException, IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
super(new URL[] { jarFile.toURI().toURL() }, parent);
loader = addonsManager;
@ -65,11 +64,13 @@ public class AddonClassLoader extends URLClassLoader {
throw new InvalidAddonFormatException("addon.yml does not define a main class!");
}
javaClass = Class.forName(mainClass, true, this);
if(mainClass.startsWith("world.bentobox.bentobox")){
throw new InvalidAddonFormatException("Package declaration cannot start with 'world.bentobox.bentobox'");
if (mainClass.startsWith("world.bentobox.bentobox")) {
throw new InvalidAddonFormatException(
"Package declaration cannot start with 'world.bentobox.bentobox'");
}
} catch (Exception e) {
throw new InvalidDescriptionException("Could not load '" + jarFile.getName() + "' in folder '" + jarFile.getParent() + "' - " + e.getMessage());
throw new InvalidDescriptionException("Could not load '" + jarFile.getName() + "' in folder '"
+ jarFile.getParent() + "' - " + e.getMessage());
}
Class<? extends Addon> addonClass;
@ -83,10 +84,9 @@ public class AddonClassLoader extends URLClassLoader {
addon.setDescription(asDescription(data));
}
/**
* Converts the addon.yml to an AddonDescription
*
* @param data - yaml config (addon.yml)
* @return Addon Description
* @throws InvalidAddonDescriptionException - if there's a bug in the addon.yml
@ -104,18 +104,17 @@ public class AddonClassLoader extends URLClassLoader {
throw new InvalidAddonDescriptionException("Missing 'version' tag. A version must be listed in addon.yml");
}
if (!data.contains("authors")) {
throw new InvalidAddonDescriptionException("Missing 'authors' tag. At least one author must be listed in addon.yml");
throw new InvalidAddonDescriptionException(
"Missing 'authors' tag. At least one author must be listed in addon.yml");
}
AddonDescription.Builder builder = new AddonDescription.Builder(
// Mandatory elements
Objects.requireNonNull(data.getString("main")),
Objects.requireNonNull(data.getString("name")),
Objects.requireNonNull(data.getString("main")), Objects.requireNonNull(data.getString("name")),
Objects.requireNonNull(data.getString("version")))
.authors(Objects.requireNonNull(data.getString("authors")))
// Optional elements
.metrics(data.getBoolean("metrics", true))
.repository(data.getString("repository", ""));
.metrics(data.getBoolean("metrics", true)).repository(data.getString("repository", ""));
String depend = data.getString("depend");
if (depend != null) {
@ -127,17 +126,20 @@ public class AddonClassLoader extends URLClassLoader {
}
Material icon = Material.getMaterial(data.getString("icon", "PAPER").toUpperCase(Locale.ENGLISH));
if (icon == null) {
throw new InvalidAddonDescriptionException("'icon' tag refers to an unknown Material: " + data.getString("icon"));
throw new InvalidAddonDescriptionException(
"'icon' tag refers to an unknown Material: " + data.getString("icon"));
}
builder.icon(Objects.requireNonNull(icon));
String apiVersion = data.getString("api-version");
if (apiVersion != null) {
if (!apiVersion.replace("-SNAPSHOT", "").matches("^(\\d+\\.)?(\\d+\\.)?(\\*|\\d+)$")) {
throw new InvalidAddonDescriptionException("Provided API version '" + apiVersion + "' is not valid. It must only contain digits and dots and not end with a dot.");
throw new InvalidAddonDescriptionException("Provided API version '" + apiVersion
+ "' is not valid. It must only contain digits and dots and not end with a dot.");
}
if (apiVersion.contains("-SNAPSHOT")) {
BentoBox.getInstance().logWarning(data.getString("name") + " addon depends on development version of BentoBox plugin. Some functions may be not implemented.");
BentoBox.getInstance().logWarning(data.getString("name")
+ " addon depends on development version of BentoBox plugin. Some functions may be not implemented.");
}
builder.apiVersion(apiVersion);
}
@ -149,7 +151,9 @@ public class AddonClassLoader extends URLClassLoader {
return builder.build();
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see java.net.URLClassLoader#findClass(java.lang.String)
*/
@Override
@ -160,7 +164,8 @@ public class AddonClassLoader extends URLClassLoader {
/**
* This is a custom findClass that enables classes in other addons to be found
* @param name - class name
*
* @param name - class name
* @param checkGlobal - check globally or not when searching
* @return Class - class if found
*/

View File

@ -24,23 +24,27 @@ public final class AddonDescription {
private final @Nullable ConfigurationSection permissions;
/**
* Whether the addon should be included in Metrics or not.
*
* @since 1.1
*/
private final boolean metrics;
/**
* Name of the GitHub repository of the addon or an empty String.
* It follows a {@code Owner/Name} format.
* Name of the GitHub repository of the addon or an empty String. It follows a
* {@code Owner/Name} format.
*
* @since 1.3.0
*/
private final @NonNull String repository;
/**
* Icon representing the addon in various menus.
*
* @since 1.5.0
*/
private final @NonNull Material icon;
/**
* Minimum BentoBox version this addon requires in order to work properly.
* Defaults to {@code "1"}.
*
* @since 1.11.0
*/
private final @NonNull String apiVersion;
@ -103,7 +107,9 @@ public final class AddonDescription {
/**
* Returns whether the addon should be included in Metrics or not.
* @return {@code true} if the addon should be included in Metrics reports, {@code false} otherwise.
*
* @return {@code true} if the addon should be included in Metrics reports,
* {@code false} otherwise.
* @since 1.1
*/
public boolean isMetrics() {
@ -111,8 +117,9 @@ public final class AddonDescription {
}
/**
* Returns the name of the GitHub repository of the addon.
* It follows a {@code Owner/Name} format.
* Returns the name of the GitHub repository of the addon. It follows a
* {@code Owner/Name} format.
*
* @return the name of the GitHub repository of the addon or an empty String.
* @since 1.3.0
*/
@ -123,6 +130,7 @@ public final class AddonDescription {
/**
* Returns the material representing the addon as an icon.
*
* @return the material representing the addon as an icon.
* @since 1.5.0
*/
@ -132,22 +140,25 @@ public final class AddonDescription {
}
/**
* Returns the minimum BentoBox version this addon requires in order to work properly.
* <br/>
* Returns the minimum BentoBox version this addon requires in order to work
* properly. <br/>
* Examples:
* <ul>
* <li>{@code "1"} means that the addon relies on BentoBox {@code 1.0.0} or higher.</li>
* <li>Similarly, {@code "2"} sets the requirement to BentoBox {@code 2.0.0} or higher.</li>
* <li>
* More specific versions can be provided:
* <ul>
* <li>{@code "1.10"} -> BentoBox {@code 1.10.0} or higher.</li>
* <li>{@code "1.9.2"} -> BentoBox {@code 1.9.2} or higher.</li>
* </ul>
* </li>
* <li>{@code "1"} means that the addon relies on BentoBox {@code 1.0.0} or
* higher.</li>
* <li>Similarly, {@code "2"} sets the requirement to BentoBox {@code 2.0.0} or
* higher.</li>
* <li>More specific versions can be provided:
* <ul>
* <li>{@code "1.10"} -> BentoBox {@code 1.10.0} or higher.</li>
* <li>{@code "1.9.2"} -> BentoBox {@code 1.9.2} or higher.</li>
* </ul>
* </li>
* </ul>
* Defaults to {@code "1"}.
* @return the minimum BentoBox version this addon requires in order to work properly.
*
* @return the minimum BentoBox version this addon requires in order to work
* properly.
*/
@NonNull
public String getApiVersion() {
@ -231,8 +242,9 @@ public final class AddonDescription {
}
/**
* Sets the name of the GitHub repository.
* Must follow the {@code Owner/Name} format.
* Sets the name of the GitHub repository. Must follow the {@code Owner/Name}
* format.
*
* @since 1.3.0
*/
@NonNull
@ -243,6 +255,7 @@ public final class AddonDescription {
/**
* Sets the icon representing the addon.
*
* @param icon Material to set as the icon. Default is {@link Material#PAPER}.
* @since 1.5.0
*/
@ -253,8 +266,11 @@ public final class AddonDescription {
}
/**
* Sets the minimum BentoBox version this addon requires in order to work properly.
* @param apiVersion the minimum BentoBox version this addon requires in order to work properly.
* Sets the minimum BentoBox version this addon requires in order to work
* properly.
*
* @param apiVersion the minimum BentoBox version this addon requires in order
* to work properly.
* @since 1.11.0
* @see AddonDescription#getApiVersion()
*/
@ -271,6 +287,7 @@ public final class AddonDescription {
/**
* Sets the permission config section. Taken from the addon.yml
*
* @param permissions - YAML configuration section
* @return Builder
* @since 1.13.0
@ -282,12 +299,13 @@ public final class AddonDescription {
}
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "AddonDescription [" + "name=" + name + ", "
+ "version=" + version + "]";
return "AddonDescription [" + "name=" + name + ", " + "version=" + version + "]";
}
}

View File

@ -13,8 +13,9 @@ import world.bentobox.bentobox.api.configuration.WorldSettings;
import world.bentobox.bentobox.util.Util;
/**
* Defines the addon as a game mode.
* A game mode creates worlds, registers world settings and has blueprints in a jar folder.
* Defines the addon as a game mode. A game mode creates worlds, registers world
* settings and has blueprints in a jar folder.
*
* @author tastybento, Poslovitch
*/
public abstract class GameModeAddon extends Addon {
@ -26,23 +27,25 @@ public abstract class GameModeAddon extends Addon {
protected World endWorld;
/**
* Main player command. Addons can use this hook to into this command.
*
* @since 1.1
*/
@Nullable
protected CompositeCommand playerCommand;
/**
* Main admin command. Addons can use this hook to into this command.
*
* @since 1.1
*/
@Nullable
protected CompositeCommand adminCommand;
/**
* Make the worlds for this GameMode in this method. BentoBox will call it
* after onLoad() and before onEnable(). Do not register flags in this method.
* They ,ust be registered afterwards in onEnable()
* {@link #islandWorld} must be created and assigned,
* {@link #netherWorld} and {@link #endWorld} are optional and may be null.
* Make the worlds for this GameMode in this method. BentoBox will call it after
* onLoad() and before onEnable(). Do not register flags in this method. They
* ,ust be registered afterwards in onEnable() {@link #islandWorld} must be
* created and assigned, {@link #netherWorld} and {@link #endWorld} are optional
* and may be null.
*/
public abstract void createWorlds();
@ -53,6 +56,7 @@ public abstract class GameModeAddon extends Addon {
/**
* Checks if location is governed by this game mode
*
* @param loc - location to check
* @return true if location in covered by this addon or false if not
*/
@ -62,6 +66,7 @@ public abstract class GameModeAddon extends Addon {
/**
* Checks if world is governed by this game mode
*
* @param world - world to check
* @return true if world in covered by this addon or false if not
* @since 1.2.0
@ -116,25 +121,33 @@ public abstract class GameModeAddon extends Addon {
/**
* Defines the world generator for this game mode
*
* @param worldName - name of world that this applies to
* @param id - id if any. "delete" is used when this request is for island deletion purposes
* @return Chunk generator or null if one does not exist, e.g. the use own generator setting is true
* @param id - id if any. "delete" is used when this request is for
* island deletion purposes
* @return Chunk generator or null if one does not exist, e.g. the use own
* generator setting is true
* @since 1.2.0
*/
@Nullable
public abstract ChunkGenerator getDefaultWorldGenerator(String worldName, String id);
/**
* Tells the Game Mode Addon to save its settings. Used when world settings are changed
* in-game and need to be saved.
* Tells the Game Mode Addon to save its settings. Used when world settings are
* changed in-game and need to be saved.
*
* @since 1.4.0
*/
public abstract void saveWorldSettings();
/**
* Defines if the game mode uses the latest {@link ChunkGenerator} API or
* deprecated {@link ChunkGenerator#generateChunkData(World, java.util.Random, int, int, org.bukkit.generator.ChunkGenerator.BiomeGrid)} approach.
* @return true if this game mode is a void world and should just be deleted as such
* Defines if the game mode uses the latest {@link ChunkGenerator} API or
* deprecated
* {@link ChunkGenerator#generateChunkData(World, java.util.Random, int, int, org.bukkit.generator.ChunkGenerator.BiomeGrid)}
* approach.
*
* @return true if this game mode is a void world and should just be deleted as
* such
*/
public boolean isUsesNewChunkGeneration() {
return false;

View File

@ -8,8 +8,9 @@ import org.bukkit.plugin.java.JavaPlugin;
import com.google.common.io.Files;
/**
* Provides a shell for addons to become Plugins so that other Plugins
* can tap into their API more easily. Plugin + addon = Pladdon
* Provides a shell for addons to become Plugins so that other Plugins can tap
* into their API more easily. Plugin + addon = Pladdon
*
* @author tastybento
*
*/
@ -18,7 +19,9 @@ public abstract class Pladdon extends JavaPlugin {
private static final String ADDONS_FOLDER = "BentoBox" + File.separator + "addons";
/**
* This must return a new instance of the addon. It is called when the Pladdon is loaded.
* This must return a new instance of the addon. It is called when the Pladdon
* is loaded.
*
* @return new instance of the addon
*/
public abstract Addon getAddon();
@ -33,7 +36,8 @@ public abstract class Pladdon extends JavaPlugin {
}
protected void moveJar() {
getLogger().severe(getFile().getName() + " must be in the " + ADDONS_FOLDER + " folder! Trying to move it there...");
getLogger().severe(
getFile().getName() + " must be in the " + ADDONS_FOLDER + " folder! Trying to move it there...");
File addons = new File(getFile().getParent(), ADDONS_FOLDER);
if (addons.exists() || addons.mkdirs()) {
File to = new File(addons, getFile().getName());
@ -44,10 +48,12 @@ public abstract class Pladdon extends JavaPlugin {
} catch (IOException ex) {
getLogger().severe("Failed to move it. " + ex.getMessage());
getLogger().severe("Move " + getFile().getName() + " manually into the " + ADDONS_FOLDER + " folder. Then restart server.");
getLogger().severe("Move " + getFile().getName() + " manually into the " + ADDONS_FOLDER
+ " folder. Then restart server.");
}
} else {
getLogger().warning(getFile().getName() + " already is in the addons folder. Delete the one in the plugins folder.");
getLogger().warning(getFile().getName()
+ " already is in the addons folder. Delete the one in the plugins folder.");
}
} else {
getLogger().severe("BentoBox addons folder could not be made! " + addons.getAbsolutePath());
@ -55,10 +61,9 @@ public abstract class Pladdon extends JavaPlugin {
}
/**
* This method enables marks pladdons as enabled.
* By default, enable status is not set because onEnable and onLoad is not triggered.
* This method enables marks pladdons as enabled. By default, enable status is
* not set because onEnable and onLoad is not triggered.
*/
public void setEnabled() {
this.setEnabled(true);

View File

@ -10,7 +10,7 @@ public abstract class AddonException extends Exception {
@Serial
private static final long serialVersionUID = 4203162022348693854L;
protected AddonException(String errorMessage){
protected AddonException(String errorMessage) {
super("AddonException : " + errorMessage);
}

View File

@ -2,12 +2,11 @@ package world.bentobox.bentobox.api.addons.exceptions;
import java.io.Serial;
public class AddonRequestException extends AddonException
{
@Serial
public class AddonRequestException extends AddonException {
@Serial
private static final long serialVersionUID = -5698456013070166174L;
public AddonRequestException(String errorMessage) {
super(errorMessage);
}
public AddonRequestException(String errorMessage) {
super(errorMessage);
}
}

View File

@ -18,7 +18,7 @@ public class InvalidAddonFormatException extends AddonException {
}
@Override
public void printStackTrace(){
public void printStackTrace() {
super.printStackTrace();
Bukkit.getLogger().log(Level.WARNING, " Basic format : (addon.yml)");

View File

@ -1,8 +1,8 @@
/**
* This package covers all addon-specific API
* <p>
* The Addon class and the associated Pladdon are like Bukkit plugins
* but contain extra API specific for BentoBox games.
* The Addon class and the associated Pladdon are like Bukkit plugins but
* contain extra API specific for BentoBox games.
* </p>
*
* @since 1.0

View File

@ -10,14 +10,15 @@ import world.bentobox.bentobox.BentoBox;
import world.bentobox.bentobox.api.addons.Addon;
/**
* API to enable plugins to request data from addons.
* Addons can expose data that they want to expose. To access it, call this class with the appropriate addon name, the label for the
* data that is requested and if required, a map of key-value pairs that will be given to the addon.
* API to enable plugins to request data from addons. Addons can expose data
* that they want to expose. To access it, call this class with the appropriate
* addon name, the label for the data that is requested and if required, a map
* of key-value pairs that will be given to the addon.
*
* @author HyKurtis
*
*/
public class AddonRequestBuilder
{
public class AddonRequestBuilder {
private String addonName;
private String requestLabel;
private final Map<String, Object> metaData = new HashMap<>();
@ -45,7 +46,7 @@ public class AddonRequestBuilder
/**
* Add meta data to addon request.
*
* @param key key
* @param key key
* @param value value
*/
public AddonRequestBuilder addMetaData(String key, Object value) {
@ -63,7 +64,7 @@ public class AddonRequestBuilder
Validate.notNull(requestLabel);
Optional<Addon> addonOptional = BentoBox.getInstance().getAddonsManager().getAddonByName(addonName);
if(addonOptional.isPresent()) {
if (addonOptional.isPresent()) {
Addon addon = addonOptional.get();
return addon.request(requestLabel, metaData);
}

View File

@ -20,9 +20,8 @@ public abstract class AddonRequestHandler {
}
/**
* Handle an addon request.
* This is used only for Addons to respond to addon requests from plugins.
* Example: request island level from Levels addon.
* Handle an addon request. This is used only for Addons to respond to addon
* requests from plugins. Example: request island level from Levels addon.
*
* @param metaData meta data
* @return request response

View File

@ -1,11 +1,14 @@
/**
* API to enable plugins to request data from addons.
* <p>
* Addons can expose data that they want to expose. To access it, call this class with the appropriate addon name,
* the label for the data that is requested and if required, a map of key-value pairs that will be given to the addon.
* Addons can expose data that they want to expose. To access it, call this
* class with the appropriate addon name, the label for the data that is
* requested and if required, a map of key-value pairs that will be given to the
* addon.
* <p>
* <b>Note</b> Since BentoBox 1.17.0, Addons can be declared as Pladdons and be loaded by the Bukkit classloader. This
* enables Plugins to access Addon methods directly so this API is not required.
* <b>Note</b> Since BentoBox 1.17.0, Addons can be declared as Pladdons and be
* loaded by the Bukkit classloader. This enables Plugins to access Addon
* methods directly so this API is not required.
* </p>
*
* @author tastybento

View File

@ -7,31 +7,37 @@ import world.bentobox.bentobox.api.user.User;
/**
* Interface for BentoBox Commands
*
* @author tastybento
*/
public interface BentoBoxCommand {
/**
* Setups anything that is needed for this command.
* <br/><br/>
* Setups anything that is needed for this command. <br/>
* <br/>
* It is recommended you do the following in this method:
* <ul>
* <li>Register any of the sub-commands of this command;</li>
* <li>Define the permission required to use this command using {@link CompositeCommand#setPermission(String)};</li>
* <li>Define whether this command can only be run by players or not using {@link CompositeCommand#setOnlyPlayer(boolean)};</li>
* <li>Register any of the sub-commands of this command;</li>
* <li>Define the permission required to use this command using
* {@link CompositeCommand#setPermission(String)};</li>
* <li>Define whether this command can only be run by players or not using
* {@link CompositeCommand#setOnlyPlayer(boolean)};</li>
* </ul>
*/
void setup();
/**
* Returns whether the command can be executed by this user or not.
* It is recommended to send messages to let this user know why they could not execute the command.
* Note that this is run previous to {@link #execute(User, String, List)}.
* @param user the {@link User} who is executing this command.
* @param label the label which has been used to execute this command.
* It can be {@link CompositeCommand#getLabel()} or an alias.
* @param args the command arguments.
* @return {@code true} if this command can be executed, {@code false} otherwise.
* Returns whether the command can be executed by this user or not. It is
* recommended to send messages to let this user know why they could not execute
* the command. Note that this is run previous to
* {@link #execute(User, String, List)}.
*
* @param user the {@link User} who is executing this command.
* @param label the label which has been used to execute this command. It can be
* {@link CompositeCommand#getLabel()} or an alias.
* @param args the command arguments.
* @return {@code true} if this command can be executed, {@code false}
* otherwise.
* @since 1.3.0
*/
default boolean canExecute(User user, String label, List<String> args) {
@ -40,21 +46,24 @@ public interface BentoBoxCommand {
/**
* Defines what will be executed when this command is run.
* @param user the {@link User} who is executing this command.
* @param label the label which has been used to execute this command.
* It can be {@link CompositeCommand#getLabel()} or an alias.
* @param args the command arguments.
* @return {@code true} if the command executed successfully, {@code false} otherwise.
*
* @param user the {@link User} who is executing this command.
* @param label the label which has been used to execute this command. It can be
* {@link CompositeCommand#getLabel()} or an alias.
* @param args the command arguments.
* @return {@code true} if the command executed successfully, {@code false}
* otherwise.
*/
boolean execute(User user, String label, List<String> args);
/**
* Tab Completer for CompositeCommands.
* Note that any registered sub-commands will be automatically added to the list.
* Use this to add tab-complete for things like names.
* @param user the {@link User} who is executing this command.
* Tab Completer for CompositeCommands. Note that any registered sub-commands
* will be automatically added to the list. Use this to add tab-complete for
* things like names.
*
* @param user the {@link User} who is executing this command.
* @param alias alias for command
* @param args command arguments
* @param args command arguments
* @return List of strings that could be used to complete this command.
*/
default Optional<List<String>> tabComplete(User user, String alias, List<String> args) {

View File

@ -10,9 +10,10 @@ import world.bentobox.bentobox.api.addons.Addon;
import world.bentobox.bentobox.api.user.User;
/**
* BentoBox Confirmable Command
* Adds ability to confirm a command before execution.
* See {@link #askConfirmation(User, Runnable)}, {@link #askConfirmation(User, String, Runnable)}
* BentoBox Confirmable Command Adds ability to confirm a command before
* execution. See {@link #askConfirmation(User, Runnable)},
* {@link #askConfirmation(User, String, Runnable)}
*
* @author tastybento
* @author Poslovitch
*/
@ -25,8 +26,9 @@ public abstract class ConfirmableCommand extends CompositeCommand {
/**
* Top level command
* @param addon - addon creating the command
* @param label - string for this command
*
* @param addon - addon creating the command
* @param label - string for this command
* @param aliases - aliases
*/
protected ConfirmableCommand(Addon addon, String label, String... aliases) {
@ -34,19 +36,21 @@ public abstract class ConfirmableCommand extends CompositeCommand {
}
/**
* Command to register a command from an addon under a parent command (that could be from another addon)
* @param addon - this command's addon
* @param parent - parent command
* Command to register a command from an addon under a parent command (that
* could be from another addon)
*
* @param addon - this command's addon
* @param parent - parent command
* @param aliases - aliases for this command
*/
protected ConfirmableCommand(Addon addon, CompositeCommand parent, String label, String... aliases ) {
protected ConfirmableCommand(Addon addon, CompositeCommand parent, String label, String... aliases) {
super(addon, parent, label, aliases);
}
/**
*
* @param parent - parent command
* @param label - command label
* @param parent - parent command
* @param label - command label
* @param aliases - command aliases
*/
protected ConfirmableCommand(CompositeCommand parent, String label, String... aliases) {
@ -55,20 +59,24 @@ public abstract class ConfirmableCommand extends CompositeCommand {
/**
* Tells user to confirm command by retyping it.
* @param user User to ask confirmation to.
* @param message Optional message to send to the user to give them a bit more context. It must already be translated.
*
* @param user User to ask confirmation to.
* @param message Optional message to send to the user to give them a bit more
* context. It must already be translated.
* @param confirmed Runnable to be executed if successfully confirmed.
*/
public void askConfirmation(User user, String message, Runnable confirmed) {
// Check for pending confirmations
if (toBeConfirmed.containsKey(user)) {
if (toBeConfirmed.get(user).topLabel().equals(getTopLabel()) && toBeConfirmed.get(user).label().equalsIgnoreCase(getLabel())) {
if (toBeConfirmed.get(user).topLabel().equals(getTopLabel())
&& toBeConfirmed.get(user).label().equalsIgnoreCase(getLabel())) {
toBeConfirmed.get(user).task().cancel();
Bukkit.getScheduler().runTask(getPlugin(), toBeConfirmed.get(user).runnable());
toBeConfirmed.remove(user);
return;
} else {
// Player has another outstanding confirmation request that will now be cancelled
// Player has another outstanding confirmation request that will now be
// cancelled
user.sendMessage("commands.confirmation.previous-request-cancelled");
}
}
@ -77,7 +85,8 @@ public abstract class ConfirmableCommand extends CompositeCommand {
user.sendRawMessage(message);
}
// Tell user that they need to confirm
user.sendMessage("commands.confirmation.confirm", "[seconds]", String.valueOf(getSettings().getConfirmationTime()));
user.sendMessage("commands.confirmation.confirm", "[seconds]",
String.valueOf(getSettings().getConfirmationTime()));
// Set up a cancellation task
BukkitTask task = Bukkit.getScheduler().runTaskLater(getPlugin(), () -> {
user.sendMessage("commands.confirmation.request-cancelled");
@ -89,9 +98,13 @@ public abstract class ConfirmableCommand extends CompositeCommand {
}
/**
* Tells user to confirm command by retyping it. Uses the default message to retype it.<p>
* If you need a custom message, use {@link #askConfirmation(User, String, Runnable)}
* @param user User to ask confirmation to.
* Tells user to confirm command by retyping it. Uses the default message to
* retype it.
* <p>
* If you need a custom message, use
* {@link #askConfirmation(User, String, Runnable)}
*
* @param user User to ask confirmation to.
* @param confirmed Runnable to be executed if successfully confirmed.
*/
public void askConfirmation(User user, Runnable confirmed) {
@ -102,6 +115,7 @@ public abstract class ConfirmableCommand extends CompositeCommand {
* Record to hold the data to run once the confirmation is given
*
*/
private record Confirmer (String topLabel, String label, Runnable runnable, BukkitTask task) { }
private record Confirmer(String topLabel, String label, Runnable runnable, BukkitTask task) {
}
}

View File

@ -12,6 +12,7 @@ import world.bentobox.bentobox.api.user.User;
/**
* Adds a default help to every command that will show the usage of the command
* and the usage of any subcommands that the command has.
*
* @author tastybento
*
*/
@ -40,24 +41,29 @@ public class DefaultHelpCommand extends CompositeCommand {
@Override
public boolean execute(User user, String label, List<String> args) {
// If command is hidden, do not show anything
if (parent.isHidden()) return true;
if (parent.isHidden())
return true;
// Show default help
int depth = 0;
if (args.size() == 1) {
if (NumberUtils.isDigits(args.get(0))) {
// Converts first argument into an int, or returns -1 if it cannot. Avoids exceptions.
// Converts first argument into an int, or returns -1 if it cannot. Avoids
// exceptions.
depth = Optional.ofNullable(args.get(0)).map(NumberUtils::toInt).orElse(-1);
} else {
String usage = parent.getUsage();
String params = user.getTranslation("commands.help.parameters");
String desc = user.getTranslation("commands.help.description");
user.sendMessage(HELP_SYNTAX_REF, USAGE_PLACEHOLDER, usage, PARAMS_PLACEHOLDER, params, DESC_PLACEHOLDER, desc);
user.sendMessage(HELP_SYNTAX_REF, USAGE_PLACEHOLDER, usage, PARAMS_PLACEHOLDER, params,
DESC_PLACEHOLDER, desc);
return true;
}
}
if (depth == 0) {
// Get the name of the world for the help header, or console if there is no world association
String labelText = getWorld() != null ? getIWM().getFriendlyName(getWorld()) : user.getTranslation("commands.help.console");
// Get the name of the world for the help header, or console if there is no
// world association
String labelText = getWorld() != null ? getIWM().getFriendlyName(getWorld())
: user.getTranslation("commands.help.console");
user.sendMessage("commands.help.header", TextVariables.LABEL, labelText);
}
if (depth < MAX_DEPTH) {
@ -87,7 +93,8 @@ public class DefaultHelpCommand extends CompositeCommand {
if (!subCommand.getLabel().equals(HELP)) {
// Every command should have help because every command has a default help
Optional<CompositeCommand> sub = subCommand.getSubCommand(HELP);
sub.ifPresent(compositeCommand -> compositeCommand.execute(user, HELP, Collections.singletonList(String.valueOf(newDepth))));
sub.ifPresent(compositeCommand -> compositeCommand.execute(user, HELP,
Collections.singletonList(String.valueOf(newDepth))));
}
}
}
@ -100,10 +107,12 @@ public class DefaultHelpCommand extends CompositeCommand {
if (params == null || params.isEmpty()) {
user.sendMessage(HELP_SYNTAX_NO_PARAMETERS_REF, USAGE_PLACEHOLDER, usage, DESC_PLACEHOLDER, desc);
} else {
user.sendMessage(HELP_SYNTAX_REF, USAGE_PLACEHOLDER, usage, PARAMS_PLACEHOLDER, params, DESC_PLACEHOLDER, desc);
user.sendMessage(HELP_SYNTAX_REF, USAGE_PLACEHOLDER, usage, PARAMS_PLACEHOLDER, params,
DESC_PLACEHOLDER, desc);
}
} else {
// No permission, nothing to see here. If you don't have permission, you cannot see any sub commands
// No permission, nothing to see here. If you don't have permission, you cannot
// see any sub commands
return true;
}
} else if (!parent.isOnlyPlayer()) {
@ -111,7 +120,8 @@ public class DefaultHelpCommand extends CompositeCommand {
if (params == null || params.isEmpty()) {
user.sendMessage(HELP_SYNTAX_NO_PARAMETERS_REF, USAGE_PLACEHOLDER, usage, DESC_PLACEHOLDER, desc);
} else {
user.sendMessage(HELP_SYNTAX_REF, USAGE_PLACEHOLDER, usage, PARAMS_PLACEHOLDER, params, DESC_PLACEHOLDER, desc);
user.sendMessage(HELP_SYNTAX_REF, USAGE_PLACEHOLDER, usage, PARAMS_PLACEHOLDER, params,
DESC_PLACEHOLDER, desc);
}
}
return false;

View File

@ -17,8 +17,9 @@ import world.bentobox.bentobox.api.addons.Addon;
import world.bentobox.bentobox.api.user.User;
/**
* BentoBox Delayed Teleport Command
* Adds ability to require the player stays still for a period of time before a command is executed
* BentoBox Delayed Teleport Command Adds ability to require the player stays
* still for a period of time before a command is executed
*
* @author tastybento
*/
public abstract class DelayedTeleportCommand extends CompositeCommand implements Listener {
@ -32,7 +33,8 @@ public abstract class DelayedTeleportCommand extends CompositeCommand implements
public void onPlayerMove(PlayerMoveEvent e) {
UUID uuid = e.getPlayer().getUniqueId();
// Only check x,y,z
if (toBeMonitored.containsKey(uuid) && !e.getTo().toVector().equals(toBeMonitored.get(uuid).location().toVector())) {
if (toBeMonitored.containsKey(uuid)
&& !e.getTo().toVector().equals(toBeMonitored.get(uuid).location().toVector())) {
moved(uuid);
}
}
@ -41,7 +43,8 @@ public abstract class DelayedTeleportCommand extends CompositeCommand implements
// Player moved
toBeMonitored.get(uuid).task().cancel();
toBeMonitored.remove(uuid);
// Player has another outstanding confirmation request that will now be cancelled
// Player has another outstanding confirmation request that will now be
// cancelled
User.getInstance(uuid).notify("commands.delay.moved-so-command-cancelled");
}
@ -53,11 +56,11 @@ public abstract class DelayedTeleportCommand extends CompositeCommand implements
}
}
/**
* Top level command
* @param addon - addon creating the command
* @param label - string for this command
*
* @param addon - addon creating the command
* @param label - string for this command
* @param aliases - aliases
*/
protected DelayedTeleportCommand(Addon addon, String label, String... aliases) {
@ -66,20 +69,22 @@ public abstract class DelayedTeleportCommand extends CompositeCommand implements
}
/**
* Command to register a command from an addon under a parent command (that could be from another addon)
* @param addon - this command's addon
* @param parent - parent command
* Command to register a command from an addon under a parent command (that
* could be from another addon)
*
* @param addon - this command's addon
* @param parent - parent command
* @param aliases - aliases for this command
*/
protected DelayedTeleportCommand(Addon addon, CompositeCommand parent, String label, String... aliases ) {
protected DelayedTeleportCommand(Addon addon, CompositeCommand parent, String label, String... aliases) {
super(addon, parent, label, aliases);
Bukkit.getPluginManager().registerEvents(this, getPlugin());
}
/**
*
* @param parent - parent command
* @param label - command label
* @param parent - parent command
* @param label - command label
* @param aliases - command aliases
*/
protected DelayedTeleportCommand(CompositeCommand parent, String label, String... aliases) {
@ -89,12 +94,15 @@ public abstract class DelayedTeleportCommand extends CompositeCommand implements
/**
* Tells user to stand still for a period of time before teleporting
* @param user User to tell
* @param message Optional message to send to the user to give them a bit more context. It must already be translated.
*
* @param user User to tell
* @param message Optional message to send to the user to give them a bit more
* context. It must already be translated.
* @param confirmed Runnable to be executed if successfully delayed.
*/
public void delayCommand(User user, String message, Runnable confirmed) {
if (getSettings().getDelayTime() < 1 || user.isOp() || user.hasPermission(getPermissionPrefix() + "mod.bypasscooldowns")
if (getSettings().getDelayTime() < 1 || user.isOp()
|| user.hasPermission(getPermissionPrefix() + "mod.bypasscooldowns")
|| user.hasPermission(getPermissionPrefix() + "mod.bypassdelays")) {
Bukkit.getScheduler().runTask(getPlugin(), confirmed);
return;
@ -105,7 +113,8 @@ public abstract class DelayedTeleportCommand extends CompositeCommand implements
// A double request - clear out the old one
toBeMonitored.get(uuid).task().cancel();
toBeMonitored.remove(uuid);
// Player has another outstanding confirmation request that will now be cancelled
// Player has another outstanding confirmation request that will now be
// cancelled
user.sendMessage("commands.delay.previous-command-cancelled");
}
// Send user the context message if it is not empty
@ -126,7 +135,8 @@ public abstract class DelayedTeleportCommand extends CompositeCommand implements
/**
* Tells user to stand still for a period of time before teleporting
* @param user User to monitor.
*
* @param user User to monitor.
* @param command Runnable to be executed if player does not move.
*/
public void delayCommand(User user, Runnable command) {
@ -137,6 +147,7 @@ public abstract class DelayedTeleportCommand extends CompositeCommand implements
* Holds the data to run once the confirmation is given
*
*/
private record DelayedCommand(Runnable runnable, BukkitTask task, Location location) {}
private record DelayedCommand(Runnable runnable, BukkitTask task, Location location) {
}
}

View File

@ -45,7 +45,8 @@ public class AdminDeleteCommand extends ConfirmableCommand {
return false;
}
// Team members should be kicked before deleting otherwise the whole team will become weird
// Team members should be kicked before deleting otherwise the whole team will
// become weird
if (getIslands().inTeam(getWorld(), targetUUID) && user.getUniqueId().equals(island.getOwner())) {
user.sendMessage("commands.admin.delete.cannot-delete-owner");
return false;
@ -66,14 +67,10 @@ public class AdminDeleteCommand extends ConfirmableCommand {
// Delete player and island
for (Island oldIsland : getIslands().getIslands(getWorld(), targetUUID)) {
// Fire island preclear event
IslandEvent.builder()
.involvedPlayer(user.getUniqueId())
.reason(Reason.PRECLEAR)
.island(oldIsland)
.oldIsland(oldIsland)
.location(oldIsland.getCenter())
.build();
user.sendMessage("commands.admin.delete.deleted-island", TextVariables.XYZ, Util.xyz(oldIsland.getCenter().toVector()));
IslandEvent.builder().involvedPlayer(user.getUniqueId()).reason(Reason.PRECLEAR).island(oldIsland)
.oldIsland(oldIsland).location(oldIsland.getCenter()).build();
user.sendMessage("commands.admin.delete.deleted-island", TextVariables.XYZ,
Util.xyz(oldIsland.getCenter().toVector()));
getIslands().deleteIsland(oldIsland, true, targetUUID);
}
// Check if player is online and on the island
@ -118,7 +115,7 @@ public class AdminDeleteCommand extends ConfirmableCommand {
@Override
public Optional<List<String>> tabComplete(User user, String alias, List<String> args) {
String lastArg = !args.isEmpty() ? args.get(args.size()-1) : "";
String lastArg = !args.isEmpty() ? args.get(args.size() - 1) : "";
if (args.isEmpty()) {
// Don't show every player on the server. Require at least the first letter
return Optional.empty();

View File

@ -14,6 +14,7 @@ import world.bentobox.bentobox.util.Util;
/**
* Deletes all named homes from an island
*
* @author tastybento
*
*/
@ -55,7 +56,8 @@ public class AdminDeleteHomesCommand extends ConfirmableCommand {
return false;
}
// Confirm
askConfirmation(user, user.getTranslation("commands.admin.deletehomes.warning"), () -> deleteHomes(user, island));
askConfirmation(user, user.getTranslation("commands.admin.deletehomes.warning"),
() -> deleteHomes(user, island));
return true;
}
@ -67,7 +69,7 @@ public class AdminDeleteHomesCommand extends ConfirmableCommand {
@Override
public Optional<List<String>> tabComplete(User user, String alias, List<String> args) {
String lastArg = !args.isEmpty() ? args.get(args.size()-1) : "";
String lastArg = !args.isEmpty() ? args.get(args.size() - 1) : "";
if (args.isEmpty()) {
// Don't show every player on the server. Require at least the first letter
return Optional.empty();

View File

@ -13,6 +13,7 @@ public class AdminEmptyTrashCommand extends ConfirmableCommand {
/**
* Clear trash for player, or all unowned islands in trash
*
* @param parent - admin command
* @since 1.3.0
*/

View File

@ -17,6 +17,7 @@ import world.bentobox.bentobox.util.Util;
/**
* Tells the rank of the player
*
* @author tastybento
*
*/
@ -63,7 +64,8 @@ public class AdminGetrankCommand extends CompositeCommand {
} else {
// We want to get the rank of the player on the island of the owner we specify.
// So we have to make sure that the island owner actually owns an island
@Nullable UUID ownerUUID = getPlayers().getUUID(args.get(1));
@Nullable
UUID ownerUUID = getPlayers().getUUID(args.get(1));
if (ownerUUID == null) {
user.sendMessage("general.errors.unknown-player", TextVariables.NAME, args.get(1));
return false;
@ -86,8 +88,9 @@ public class AdminGetrankCommand extends CompositeCommand {
RanksManager rm = getPlugin().getRanksManager();
User target = User.getInstance(targetUUID);
int currentRank = island.getRank(target);
user.sendMessage("commands.admin.getrank.rank-is", TextVariables.RANK, user.getTranslation(rm.getRank(currentRank)),
TextVariables.NAME, getPlayers().getName(island.getOwner()));
user.sendMessage("commands.admin.getrank.rank-is", TextVariables.RANK,
user.getTranslation(rm.getRank(currentRank)), TextVariables.NAME,
getPlayers().getName(island.getOwner()));
return true;
}

View File

@ -33,10 +33,12 @@ public class AdminInfoCommand extends CompositeCommand {
showHelp(this, user);
return false;
}
// If there are no args, then the player wants info on the island at this location
// If there are no args, then the player wants info on the island at this
// location
if (args.isEmpty()) {
getIslands().getIslandAt(user.getLocation()).ifPresentOrElse(i -> new IslandInfo(i).showAdminInfo(user, getAddon()), () ->
user.sendMessage("commands.admin.info.no-island"));
getIslands().getIslandAt(user.getLocation()).ifPresentOrElse(
i -> new IslandInfo(i).showAdminInfo(user, getAddon()),
() -> user.sendMessage("commands.admin.info.no-island"));
return true;
}
// Get target player
@ -61,7 +63,7 @@ public class AdminInfoCommand extends CompositeCommand {
@Override
public Optional<List<String>> tabComplete(User user, String alias, List<String> args) {
String lastArg = !args.isEmpty() ? args.get(args.size()-1) : "";
String lastArg = !args.isEmpty() ? args.get(args.size() - 1) : "";
if (args.isEmpty()) {
// Don't show every player on the server. Require at least the first letter
return Optional.empty();

View File

@ -61,21 +61,21 @@ public class AdminRegisterCommand extends ConfirmableCommand {
}
// Check if island is owned
Optional<Island> island = getIslands().getIslandAt(user.getLocation());
if (island.filter(Island::isOwned)
.filter(i -> !i.getOwner().equals(targetUUID))
.isPresent()) {
if (island.filter(Island::isOwned).filter(i -> !i.getOwner().equals(targetUUID)).isPresent()) {
user.sendMessage("commands.admin.register.already-owned");
return false;
}
// Check if island is spawn
if (island.map(Island::isSpawn).orElse(false)) {
askConfirmation(user, user.getTranslation("commands.admin.register.island-is-spawn"), () -> register(user, args.get(0), targetUUID, island, closestIsland));
askConfirmation(user, user.getTranslation("commands.admin.register.island-is-spawn"),
() -> register(user, args.get(0), targetUUID, island, closestIsland));
return false;
}
return register(user, args.get(0),targetUUID, island, closestIsland);
return register(user, args.get(0), targetUUID, island, closestIsland);
}
private boolean register(User user, String targetName, UUID targetUUID, Optional<Island> island, Location closestIsland) {
private boolean register(User user, String targetName, UUID targetUUID, Optional<Island> island,
Location closestIsland) {
// Register island if it exists
if (!island.map(i -> {
// Island exists
@ -83,24 +83,15 @@ public class AdminRegisterCommand extends ConfirmableCommand {
if (i.isSpawn()) {
getIslands().clearSpawn(i.getWorld());
}
user.sendMessage("commands.admin.register.registered-island", TextVariables.XYZ, Util.xyz(i.getCenter().toVector()),
TextVariables.NAME, targetName);
user.sendMessage("commands.admin.register.registered-island", TextVariables.XYZ,
Util.xyz(i.getCenter().toVector()), TextVariables.NAME, targetName);
user.sendMessage("general.success");
// Build and call event
IslandEvent.builder()
.island(i)
.location(i.getCenter())
.reason(IslandEvent.Reason.REGISTERED)
.involvedPlayer(targetUUID)
.admin(true)
.build();
IslandEvent.builder()
.island(i)
.involvedPlayer(targetUUID)
.admin(true)
.reason(IslandEvent.Reason.RANK_CHANGE)
.rankChange(RanksManager.VISITOR_RANK, RanksManager.OWNER_RANK)
.build();
IslandEvent.builder().island(i).location(i.getCenter()).reason(IslandEvent.Reason.REGISTERED)
.involvedPlayer(targetUUID).admin(true).build();
IslandEvent.builder().island(i).involvedPlayer(targetUUID).admin(true)
.reason(IslandEvent.Reason.RANK_CHANGE)
.rankChange(RanksManager.VISITOR_RANK, RanksManager.OWNER_RANK).build();
return true;
}).orElse(false)) {
// Island does not exist - this is a reservation
@ -114,16 +105,11 @@ public class AdminRegisterCommand extends ConfirmableCommand {
getIslands().setOwner(user, targetUUID, i);
i.setReserved(true);
i.getCenter().getBlock().setType(Material.BEDROCK);
user.sendMessage("commands.admin.register.reserved-island", TextVariables.XYZ, Util.xyz(i.getCenter().toVector()),
TextVariables.NAME, targetName);
user.sendMessage("commands.admin.register.reserved-island", TextVariables.XYZ,
Util.xyz(i.getCenter().toVector()), TextVariables.NAME, targetName);
// Build and fire event
IslandEvent.builder()
.island(i)
.location(i.getCenter())
.reason(IslandEvent.Reason.RESERVED)
.involvedPlayer(targetUUID)
.admin(true)
.build();
IslandEvent.builder().island(i).location(i.getCenter()).reason(IslandEvent.Reason.RESERVED)
.involvedPlayer(targetUUID).admin(true).build();
});
return false;
}
@ -132,7 +118,7 @@ public class AdminRegisterCommand extends ConfirmableCommand {
@Override
public Optional<List<String>> tabComplete(User user, String alias, List<String> args) {
String lastArg = !args.isEmpty() ? args.get(args.size()-1) : "";
String lastArg = !args.isEmpty() ? args.get(args.size() - 1) : "";
if (args.isEmpty()) {
// Don't show every player on the server. Require at least the first letter
return Optional.empty();

View File

@ -6,8 +6,9 @@ import world.bentobox.bentobox.api.commands.CompositeCommand;
import world.bentobox.bentobox.api.user.User;
/**
* Generic reload command for addons to use that will just call the onReload() method
* after checking permissions
* Generic reload command for addons to use that will just call the onReload()
* method after checking permissions
*
* @author tastybento
*/
public class AdminReloadCommand extends CompositeCommand {

View File

@ -13,7 +13,9 @@ import world.bentobox.bentobox.api.user.User;
import world.bentobox.bentobox.util.Util;
/**
* Admin command to reset all islands in a world to the default flag setting in the game mode config.yml
* Admin command to reset all islands in a world to the default flag setting in
* the game mode config.yml
*
* @author tastybento
* @since 1.3.0
*/
@ -24,8 +26,8 @@ public class AdminResetFlagsCommand extends ConfirmableCommand {
public AdminResetFlagsCommand(CompositeCommand parent) {
super(parent, "resetflags");
options = getPlugin().getFlagsManager().getFlags().stream()
.filter(f -> f.getType().equals(Type.PROTECTION) || f.getType().equals(Type.SETTING))
.map(Flag::getID).toList();
.filter(f -> f.getType().equals(Type.PROTECTION) || f.getType().equals(Type.SETTING)).map(Flag::getID)
.toList();
}
@Override
@ -45,11 +47,11 @@ public class AdminResetFlagsCommand extends ConfirmableCommand {
});
return true;
} else if (args.size() == 1 && options.contains(args.get(0).toUpperCase(Locale.ENGLISH))) {
getPlugin().getFlagsManager().getFlag(args.get(0).toUpperCase(Locale.ENGLISH)).ifPresent(flag ->
askConfirmation(user, user.getTranslation("commands.admin.resetflags.confirm"), () -> {
getIslands().resetFlag(getWorld(), flag);
user.sendMessage("commands.admin.resetflags.success-one", TextVariables.NAME, flag.getID());
}));
getPlugin().getFlagsManager().getFlag(args.get(0).toUpperCase(Locale.ENGLISH)).ifPresent(
flag -> askConfirmation(user, user.getTranslation("commands.admin.resetflags.confirm"), () -> {
getIslands().resetFlag(getWorld(), flag);
user.sendMessage("commands.admin.resetflags.success-one", TextVariables.NAME, flag.getID());
}));
return true;
}
// Show help
@ -59,7 +61,7 @@ public class AdminResetFlagsCommand extends ConfirmableCommand {
@Override
public Optional<List<String>> tabComplete(User user, String alias, List<String> args) {
String lastArg = !args.isEmpty() ? args.get(args.size()-1) : "";
String lastArg = !args.isEmpty() ? args.get(args.size() - 1) : "";
return Optional.of(Util.tabLimit(options, lastArg));
}
}

View File

@ -12,64 +12,54 @@ import world.bentobox.bentobox.api.user.User;
import world.bentobox.bentobox.database.objects.Island;
import world.bentobox.bentobox.util.Util;
/**
* This command resets players island name.
*
* @author BONNe
*/
public class AdminResetNameCommand extends CompositeCommand
{
public class AdminResetNameCommand extends CompositeCommand {
/**
* Default constructor.
*
* @param command Parent command.
*/
public AdminResetNameCommand(CompositeCommand command)
{
public AdminResetNameCommand(CompositeCommand command) {
super(command, "resetname");
}
/**
* {@inheritDoc}
*/
@Override
public void setup()
{
public void setup() {
this.setPermission("mod.resetname");
this.setOnlyPlayer(true);
this.setDescription("commands.admin.resetname.description");
}
/**
* @param user the {@link User} who is executing this command.
* @param label the label which has been used to execute this command.
* It can be {@link CompositeCommand#getLabel()} or an alias.
* @param args the command arguments.
* @param user the {@link User} who is executing this command.
* @param label the label which has been used to execute this command. It can be
* {@link CompositeCommand#getLabel()} or an alias.
* @param args the command arguments.
* @return {@code true} if name can be reset, {@code false} otherwise.
*/
@Override
public boolean canExecute(User user, String label, List<String> args)
{
if (args.size() == 1)
{
public boolean canExecute(User user, String label, List<String> args) {
if (args.size() == 1) {
UUID playerUUID = Util.getUUID(args.get(0));
if (playerUUID == null)
{
if (playerUUID == null) {
user.sendMessage("general.errors.unknown-player", TextVariables.NAME, args.get(0));
return false;
}
this.island = this.getIslandsManager().getIsland(this.getWorld(), playerUUID);
}
else
{
} else {
this.island = this.getIslandsManager().getIslandAt(user.getLocation()).orElse(null);
}
if (this.island == null)
{
if (this.island == null) {
user.sendMessage("general.errors.player-has-no-island");
return false;
}
@ -77,51 +67,44 @@ public class AdminResetNameCommand extends CompositeCommand
return true;
}
/**
* @param user the {@link User} who is executing this command.
* @param label the label which has been used to execute this command.
* It can be {@link CompositeCommand#getLabel()} or an alias.
* @param args the command arguments.
* @param user the {@link User} who is executing this command.
* @param label the label which has been used to execute this command. It can be
* {@link CompositeCommand#getLabel()} or an alias.
* @param args the command arguments.
* @return {@code true}
*/
@Override
public boolean execute(User user, String label, List<String> args)
{
if (this.island == null)
{
public boolean execute(User user, String label, List<String> args) {
if (this.island == null) {
this.showHelp(this, user);
return true;
}
// Resets the island name
this.island.setName(null);
user.sendMessage("commands.admin.resetname.success", TextVariables.NAME, this.getPlayers().getName(this.island.getOwner()));
user.sendMessage("commands.admin.resetname.success", TextVariables.NAME,
this.getPlayers().getName(this.island.getOwner()));
return true;
}
/**
* @param user the {@link User} who is executing this command.
* @param user the {@link User} who is executing this command.
* @param alias alias for command
* @param args command arguments
* @param args command arguments
* @return Optional of possible values.
*/
@Override
public Optional<List<String>> tabComplete(User user, String alias, List<String> args) {
// Return the player names
if (args.size() == 1)
{
if (args.size() == 1) {
return Optional.of(Util.getOnlinePlayerList(user));
}
else
{
} else {
return Optional.empty();
}
}
/**
* Island which name must be changed.
*/

View File

@ -1,6 +1,5 @@
package world.bentobox.bentobox.api.commands.admin;
import java.util.List;
import java.util.Optional;
@ -13,21 +12,18 @@ import world.bentobox.bentobox.api.user.User;
import world.bentobox.bentobox.database.objects.Island;
import world.bentobox.bentobox.util.Util;
/**
* This command sets the center of the protected area.
* The location can be anywhere inside the island range area. Therefore the protected
* range can be up to 2x the island range.
* The location will change for all environments.
* This command sets the center of the protected area. The location can be
* anywhere inside the island range area. Therefore the protected range can be
* up to 2x the island range. The location will change for all environments.
*
* @author tastybento
* @since 1.16.0
*/
public class AdminSetProtectionCenterCommand extends ConfirmableCommand
{
public class AdminSetProtectionCenterCommand extends ConfirmableCommand {
private Location targetLoc;
private Island island;
/**
* Sub-command constructor
*
@ -37,10 +33,8 @@ public class AdminSetProtectionCenterCommand extends ConfirmableCommand
super(parent, "setprotectionlocation");
}
@Override
public void setup()
{
public void setup() {
this.setPermission("admin.setprotectionlocation");
this.setParametersHelp("commands.admin.setprotectionlocation.parameters");
this.setDescription("commands.admin.setprotectionlocation.description");
@ -52,7 +46,8 @@ public class AdminSetProtectionCenterCommand extends ConfirmableCommand
// Get location
targetLoc = getLocation(args);
} else {
targetLoc = new Location(getWorld(), user.getLocation().getBlockX(), user.getLocation().getBlockY(), user.getLocation().getBlockZ());
targetLoc = new Location(getWorld(), user.getLocation().getBlockX(), user.getLocation().getBlockY(),
user.getLocation().getBlockZ());
}
if (targetLoc == null) {
user.sendMessage("commands.admin.setprotectionlocation.xyz-error");
@ -81,25 +76,28 @@ public class AdminSetProtectionCenterCommand extends ConfirmableCommand
@Override
public boolean execute(User user, String label, List<String> args) {
String name = getPlayers().getName(island.getOwner());
user.sendMessage("commands.admin.setprotectionlocation.island", TextVariables.XYZ, Util.xyz(island.getCenter().toVector()), TextVariables.NAME, name);
user.sendMessage("commands.admin.setprotectionlocation.island", TextVariables.XYZ,
Util.xyz(island.getCenter().toVector()), TextVariables.NAME, name);
// Confirm
this.askConfirmation(user, user.getTranslation("commands.admin.setprotectionlocation.confirmation", TextVariables.XYZ, Util.xyz(targetLoc.toVector())),
() -> this.setLocation(user));
this.askConfirmation(user, user.getTranslation("commands.admin.setprotectionlocation.confirmation",
TextVariables.XYZ, Util.xyz(targetLoc.toVector())), () -> this.setLocation(user));
return true;
}
/**
* Set the island location to the user's location.
*
* @param user User who initiate change.
*/
private void setLocation(User user) {
try {
// Set
island.setProtectionCenter(targetLoc);
user.sendMessage("commands.admin.setprotectionlocation.success", TextVariables.XYZ, Util.xyz(targetLoc.toVector()));
user.sendMessage("commands.admin.setprotectionlocation.success", TextVariables.XYZ,
Util.xyz(targetLoc.toVector()));
} catch (Exception e) {
user.sendMessage("commands.admin.setprotectionlocation.failure", TextVariables.XYZ, Util.xyz(targetLoc.toVector()));
user.sendMessage("commands.admin.setprotectionlocation.failure", TextVariables.XYZ,
Util.xyz(targetLoc.toVector()));
getAddon().logError("Protection location could not be changed because the island does not exist");
}

View File

@ -1,6 +1,5 @@
package world.bentobox.bentobox.api.commands.admin;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
@ -12,84 +11,71 @@ import world.bentobox.bentobox.api.commands.ConfirmableCommand;
import world.bentobox.bentobox.api.user.User;
import world.bentobox.bentobox.database.objects.Island;
/**
* This command sets spawn point for island at admin location for island on which admin is located.
* This command is only for player entity.
* This command sets spawn point for island at admin location for island on
* which admin is located. This command is only for player entity.
*
* @author BONNe
* @since 1.13.0
*/
public class AdminSetSpawnPointCommand extends ConfirmableCommand
{
public class AdminSetSpawnPointCommand extends ConfirmableCommand {
/**
* Sub-command constructor
*
* @param parent - the parent composite command
*/
public AdminSetSpawnPointCommand(CompositeCommand parent)
{
public AdminSetSpawnPointCommand(CompositeCommand parent) {
super(parent, "setspawnpoint");
}
/**
* {@inheritDoc}
*/
@Override
public void setup()
{
public void setup() {
this.setPermission("admin.setspawnpoint");
this.setOnlyPlayer(true);
this.setDescription("commands.admin.setspawnpoint.description");
}
/**
* This method finds an island in user location and asks confirmation if spawn point
* must be changed to that location.
* {@inheritDoc}
* This method finds an island in user location and asks confirmation if spawn
* point must be changed to that location. {@inheritDoc}
*/
@Override
public boolean execute(User user, String label, List<String> args)
{
public boolean execute(User user, String label, List<String> args) {
Optional<Island> optionalIsland = this.getIslands().getIslandAt(user.getLocation());
if (optionalIsland.isPresent() &&
(optionalIsland.get().hasNetherIsland() ||
!World.Environment.NETHER.equals(user.getLocation().getWorld().getEnvironment())) &&
(optionalIsland.get().hasEndIsland() ||
!World.Environment.THE_END.equals(user.getLocation().getWorld().getEnvironment())))
{
if (optionalIsland.isPresent()
&& (optionalIsland.get().hasNetherIsland()
|| !World.Environment.NETHER.equals(user.getLocation().getWorld().getEnvironment()))
&& (optionalIsland.get().hasEndIsland()
|| !World.Environment.THE_END.equals(user.getLocation().getWorld().getEnvironment()))) {
// Everything's fine, we can set the location as spawn point for island :)
this.askConfirmation(user, user.getTranslation("commands.admin.setspawnpoint.confirmation"),
() -> this.setSpawnPoint(user, optionalIsland.get()));
() -> this.setSpawnPoint(user, optionalIsland.get()));
return true;
}
else
{
} else {
user.sendMessage("commands.admin.setspawnpoint.no-island-here");
return false;
}
}
/**
* This method changes spawn point for island at given user location.
* @param user User who initiate spawn point change.
*
* @param user User who initiate spawn point change.
* @param island Island which is targeted by user.
*/
private void setSpawnPoint(User user, Island island)
{
private void setSpawnPoint(User user, Island island) {
island.setSpawnPoint(Objects.requireNonNull(user.getLocation().getWorld()).getEnvironment(),
user.getLocation());
user.getLocation());
user.sendMessage("commands.admin.setspawnpoint.success");
if (!island.isSpawn())
{
island.getPlayersOnIsland().forEach(player ->
User.getInstance(player).sendMessage("commands.admin.setspawnpoint.island-spawnpoint-changed",
"[user]", user.getName()));
if (!island.isSpawn()) {
island.getPlayersOnIsland().forEach(player -> User.getInstance(player)
.sendMessage("commands.admin.setspawnpoint.island-spawnpoint-changed", "[user]", user.getName()));
}
}
}

View File

@ -69,7 +69,8 @@ public class AdminSetrankCommand extends CompositeCommand {
// We want to change the player's rank on the island he is part of.
// Check if the target is part of an island
if (!getIslands().hasIsland(getWorld(), targetUUID) && !getPlugin().getIslands().inTeam(getWorld(), targetUUID)) {
if (!getIslands().hasIsland(getWorld(), targetUUID)
&& !getPlugin().getIslands().inTeam(getWorld(), targetUUID)) {
user.sendMessage("general.errors.player-has-no-island");
return false;
}
@ -106,13 +107,8 @@ public class AdminSetrankCommand extends CompositeCommand {
}
int currentRank = island.getRank(target);
island.setRank(target, rankValue);
IslandEvent.builder()
.island(island)
.involvedPlayer(targetUUID)
.admin(true)
.reason(IslandEvent.Reason.RANK_CHANGE)
.rankChange(currentRank, rankValue)
.build();
IslandEvent.builder().island(island).involvedPlayer(targetUUID).admin(true)
.reason(IslandEvent.Reason.RANK_CHANGE).rankChange(currentRank, rankValue).build();
String ownerName;
if (ownerUUID != null) {
@ -120,10 +116,8 @@ public class AdminSetrankCommand extends CompositeCommand {
} else {
ownerName = target.getName();
}
user.sendMessage("commands.admin.setrank.rank-set",
"[from]", user.getTranslation(rm.getRank(currentRank)),
"[to]", user.getTranslation(rm.getRank(rankValue)),
TextVariables.NAME, ownerName);
user.sendMessage("commands.admin.setrank.rank-set", "[from]", user.getTranslation(rm.getRank(currentRank)),
"[to]", user.getTranslation(rm.getRank(rankValue)), TextVariables.NAME, ownerName);
return true;
}
@ -136,8 +130,7 @@ public class AdminSetrankCommand extends CompositeCommand {
// Return the ranks
if (args.size() == 3) {
return Optional.of(getPlugin().getRanksManager().getRanks()
.entrySet().stream()
return Optional.of(getPlugin().getRanksManager().getRanks().entrySet().stream()
.filter(entry -> entry.getValue() > RanksManager.VISITOR_RANK)
.map(entry -> user.getTranslation(entry.getKey())).toList());
}

View File

@ -16,6 +16,7 @@ import world.bentobox.bentobox.database.objects.Island;
/**
* Admin command (only player) to set an island as the world's spawn.
*
* @author Poslovitch, tastybento
* @since 1.1
*/
@ -44,7 +45,8 @@ public class AdminSetspawnCommand extends ConfirmableCommand {
}
// Everything's fine, we can set the island as spawn :)
askConfirmation(user, user.getTranslation("commands.admin.setspawn.confirmation"), () -> setSpawn(user, island.get()));
askConfirmation(user, user.getTranslation("commands.admin.setspawn.confirmation"),
() -> setSpawn(user, island.get()));
return true;
} else {
user.sendMessage("commands.admin.setspawn.no-island-here");
@ -56,17 +58,12 @@ public class AdminSetspawnCommand extends ConfirmableCommand {
if (!i.getMembers().isEmpty()) {
if (i.isOwned()) {
// Build and fire event
IslandEvent.builder()
.island(i)
.location(i.getCenter())
.reason(IslandEvent.Reason.UNREGISTERED)
.involvedPlayer(i.getOwner())
.admin(true)
.build();
IslandEvent.builder().island(i).location(i.getCenter()).reason(IslandEvent.Reason.UNREGISTERED)
.involvedPlayer(i.getOwner()).admin(true).build();
}
// If island is owned, then unregister the owner and any members
new ImmutableSet.Builder<UUID>().addAll(i.getMembers().keySet()).build().forEach(m ->
getIslands().removePlayer(getWorld(), m));
new ImmutableSet.Builder<UUID>().addAll(i.getMembers().keySet()).build()
.forEach(m -> getIslands().removePlayer(getWorld(), m));
}
getIslands().setSpawn(i);
i.setSpawnPoint(World.Environment.NORMAL, user.getLocation());

View File

@ -52,18 +52,15 @@ public class AdminSettingsCommand extends CompositeCommand {
protectionFlagNames = getPlugin().getFlagsManager().getFlags().stream()
.filter(f -> f.getType().equals(Type.PROTECTION))
.filter(f -> f.getGameModes().isEmpty() || gameMode == null || f.getGameModes().contains(gameMode))
.map(Flag::getID)
.toList();
.map(Flag::getID).toList();
settingFlagNames = getPlugin().getFlagsManager().getFlags().stream()
.filter(f -> f.getType().equals(Type.SETTING))
.filter(f -> f.getGameModes().isEmpty() || gameMode == null || f.getGameModes().contains(gameMode))
.map(Flag::getID)
.toList();
.map(Flag::getID).toList();
worldSettingFlagNames = getPlugin().getFlagsManager().getFlags().stream()
.filter(f -> f.getType().equals(Type.WORLD_SETTING))
.filter(f -> f.getGameModes().isEmpty() || gameMode == null || f.getGameModes().contains(gameMode))
.map(Flag::getID)
.toList();
.map(Flag::getID).toList();
}
@Override
@ -92,7 +89,8 @@ public class AdminSettingsCommand extends CompositeCommand {
return true;
}
// Get target player
@Nullable UUID targetUUID = Util.getUUID(args.get(0));
@Nullable
UUID targetUUID = Util.getUUID(args.get(0));
if (targetUUID == null) {
user.sendMessage("general.errors.unknown-player", TextVariables.NAME, args.get(0));
return false;
@ -170,7 +168,8 @@ public class AdminSettingsCommand extends CompositeCommand {
/**
* Check the rank given.
* @param user - user
*
* @param user - user
* @param string - the rank given in the command line
* @return true if rank is valid
*/
@ -228,25 +227,15 @@ public class AdminSettingsCommand extends CompositeCommand {
}
getPlayers().setFlagsDisplayMode(user.getUniqueId(), Mode.EXPERT);
if (args.isEmpty()) {
new TabbedPanelBuilder()
.user(user)
.world(getWorld())
.tab(1, new SettingsTab(getWorld(), user, Flag.Type.WORLD_SETTING))
.tab(2, new WorldDefaultSettingsTab(getWorld(), user))
.startingSlot(1)
.size(54)
.build().openPanel();
new TabbedPanelBuilder().user(user).world(getWorld())
.tab(1, new SettingsTab(getWorld(), user, Flag.Type.WORLD_SETTING))
.tab(2, new WorldDefaultSettingsTab(getWorld(), user)).startingSlot(1).size(54).build().openPanel();
return true;
}
// Player settings
new TabbedPanelBuilder()
.user(user)
.world(island.getWorld())
.tab(1, new SettingsTab(user, island, Flag.Type.PROTECTION))
.tab(2, new SettingsTab(user, island, Flag.Type.SETTING))
.startingSlot(1)
.size(54)
.build().openPanel();
new TabbedPanelBuilder().user(user).world(island.getWorld())
.tab(1, new SettingsTab(user, island, Flag.Type.PROTECTION))
.tab(2, new SettingsTab(user, island, Flag.Type.SETTING)).startingSlot(1).size(54).build().openPanel();
return true;
}
@ -257,7 +246,7 @@ public class AdminSettingsCommand extends CompositeCommand {
String active = ChatColor.stripColor(user.getTranslation("protection.panel.flag-item.setting-active"));
String disabled = ChatColor.stripColor(user.getTranslation("protection.panel.flag-item.setting-disabled"));
List<String> options = new ArrayList<>();
String lastArg = !args.isEmpty() ? args.get(args.size()-1) : "";
String lastArg = !args.isEmpty() ? args.get(args.size() - 1) : "";
if (args.size() == 2) {
// Player names or world settings
options = Util.tabLimit(Util.getOnlinePlayerList(user), lastArg);
@ -276,15 +265,15 @@ public class AdminSettingsCommand extends CompositeCommand {
}
} else if (args.size() == 4) {
// Get flag in previous argument
options = getPlugin().getFlagsManager().getFlag(args.get(2).toUpperCase(Locale.ENGLISH)).map(f -> switch (f.getType()) {
case PROTECTION -> getPlugin().getRanksManager()
.getRanks().entrySet().stream()
.filter(en -> en.getValue() > RanksManager.BANNED_RANK && en.getValue() <= RanksManager.OWNER_RANK)
.map(Entry::getKey)
.map(user::getTranslation).toList();
case SETTING -> Arrays.asList(active, disabled);
default -> Collections.<String>emptyList();
}).orElse(Collections.emptyList());
options = getPlugin().getFlagsManager().getFlag(args.get(2).toUpperCase(Locale.ENGLISH))
.map(f -> switch (f.getType()) {
case PROTECTION -> getPlugin().getRanksManager().getRanks().entrySet().stream()
.filter(en -> en.getValue() > RanksManager.BANNED_RANK
&& en.getValue() <= RanksManager.OWNER_RANK)
.map(Entry::getKey).map(user::getTranslation).toList();
case SETTING -> Arrays.asList(active, disabled);
default -> Collections.<String>emptyList();
}).orElse(Collections.emptyList());
}
return Optional.of(Util.tabLimit(options, lastArg));

View File

@ -17,6 +17,7 @@ public class AdminSwitchCommand extends ConfirmableCommand {
/**
* Switches bypass on and off
*
* @param parent - admin command
* @since 1.5.0
*/

View File

@ -21,6 +21,7 @@ public class AdminSwitchtoCommand extends ConfirmableCommand {
/**
* Switch player's island to the numbered one in trash
*
* @param parent - admin command
* @since 1.3.0
*/
@ -65,11 +66,12 @@ public class AdminSwitchtoCommand extends ConfirmableCommand {
try {
int n = Integer.parseInt(args.get(1));
if (n < 1 || n > islands.size()) {
user.sendMessage("commands.admin.switchto.out-of-range", TextVariables.NUMBER, String.valueOf(islands.size()), TextVariables.LABEL, getTopLabel());
user.sendMessage("commands.admin.switchto.out-of-range", TextVariables.NUMBER,
String.valueOf(islands.size()), TextVariables.LABEL, getTopLabel());
return false;
}
this.askConfirmation(user, () -> {
if (getIslands().switchIsland(getWorld(), targetUUID, islands.get(n -1))) {
if (getIslands().switchIsland(getWorld(), targetUUID, islands.get(n - 1))) {
user.sendMessage("commands.admin.switchto.success");
} else {
user.sendMessage("commands.admin.switchto.cannot-switch");

View File

@ -24,7 +24,7 @@ public class AdminTeleportCommand extends CompositeCommand {
private @Nullable User userToTeleport;
/**
* @param parent - parent command
* @param parent - parent command
* @param tpCommand - should be "tp", "tpnether" or "tpend"
*/
public AdminTeleportCommand(CompositeCommand parent, String tpCommand) {
@ -98,8 +98,8 @@ public class AdminTeleportCommand extends CompositeCommand {
}
// Otherwise, ask the admin to go to a safe spot
String failureMessage = user.getTranslation("commands.admin.tp.manual", "[location]", warpSpot.getBlockX() + " " + warpSpot.getBlockY() + " "
+ warpSpot.getBlockZ());
String failureMessage = user.getTranslation("commands.admin.tp.manual", "[location]",
warpSpot.getBlockX() + " " + warpSpot.getBlockY() + " " + warpSpot.getBlockZ());
// Set the player
Player player = args.size() == 2 ? userToTeleport.getPlayer() : user.getPlayer();
if (args.size() == 2) {
@ -107,12 +107,8 @@ public class AdminTeleportCommand extends CompositeCommand {
}
// Teleport
new SafeSpotTeleport.Builder(getPlugin())
.entity(player)
.location(warpSpot)
.failureMessage(failureMessage)
.thenRun(() -> user.sendMessage("general.success"))
.build();
new SafeSpotTeleport.Builder(getPlugin()).entity(player).location(warpSpot).failureMessage(failureMessage)
.thenRun(() -> user.sendMessage("general.success")).build();
return true;
}
@ -128,7 +124,7 @@ public class AdminTeleportCommand extends CompositeCommand {
@Override
public Optional<List<String>> tabComplete(User user, String alias, List<String> args) {
String lastArg = !args.isEmpty() ? args.get(args.size()-1) : "";
String lastArg = !args.isEmpty() ? args.get(args.size() - 1) : "";
if (args.isEmpty()) {
// Don't show every player on the server. Require at least the first letter
return Optional.empty();

View File

@ -13,6 +13,7 @@ public class AdminTrashCommand extends CompositeCommand {
/**
* A command for viewing islands in the database trash
*
* @param parent - admin command
* @since 1.3.0
*/
@ -63,7 +64,7 @@ public class AdminTrashCommand extends CompositeCommand {
private void showTrash(User user, List<Island> islands) {
user.sendMessage("commands.admin.trash.title");
for (int i = 0; i < islands.size(); i++) {
user.sendMessage("commands.admin.trash.count", TextVariables.NUMBER, String.valueOf(i+1));
user.sendMessage("commands.admin.trash.count", TextVariables.NUMBER, String.valueOf(i + 1));
new IslandInfo(islands.get(i)).showInfo(user);
}
user.sendMessage("commands.admin.trash.use-switch", TextVariables.LABEL, getTopLabel());

View File

@ -52,40 +52,32 @@ public class AdminUnregisterCommand extends ConfirmableCommand {
// Get target
UUID targetUUID = getPlayers().getUUID(args.get(0));
// Everything's fine, we can set the island as spawn :)
askConfirmation(user, () -> unregisterPlayer(user, args.get(0), targetUUID));
askConfirmation(user, () -> unregisterPlayer(user, args.get(0), targetUUID));
return true;
}
void unregisterPlayer(User user, String targetName, UUID targetUUID) {
// Unregister island
Island oldIsland = getIslands().getIsland(getWorld(), targetUUID);
if (oldIsland == null) return;
IslandEvent.builder()
.island(oldIsland)
.location(oldIsland.getCenter())
.reason(IslandEvent.Reason.UNREGISTERED)
.involvedPlayer(targetUUID)
.admin(true)
.build();
IslandEvent.builder()
.island(oldIsland)
.involvedPlayer(targetUUID)
.admin(true)
.reason(IslandEvent.Reason.RANK_CHANGE)
.rankChange(RanksManager.OWNER_RANK, RanksManager.VISITOR_RANK)
.build();
if (oldIsland == null)
return;
IslandEvent.builder().island(oldIsland).location(oldIsland.getCenter()).reason(IslandEvent.Reason.UNREGISTERED)
.involvedPlayer(targetUUID).admin(true).build();
IslandEvent.builder().island(oldIsland).involvedPlayer(targetUUID).admin(true)
.reason(IslandEvent.Reason.RANK_CHANGE).rankChange(RanksManager.OWNER_RANK, RanksManager.VISITOR_RANK)
.build();
// Remove all island members
oldIsland.getMemberSet().forEach(m -> getIslands().removePlayer(getWorld(), m));
// Remove all island players that reference this island
oldIsland.getMembers().clear();
getIslands().save(oldIsland);
user.sendMessage("commands.admin.unregister.unregistered-island", TextVariables.XYZ, Util.xyz(oldIsland.getCenter().toVector()),
TextVariables.NAME, targetName);
user.sendMessage("commands.admin.unregister.unregistered-island", TextVariables.XYZ,
Util.xyz(oldIsland.getCenter().toVector()), TextVariables.NAME, targetName);
}
@Override
public Optional<List<String>> tabComplete(User user, String alias, List<String> args) {
String lastArg = !args.isEmpty() ? args.get(args.size()-1) : "";
String lastArg = !args.isEmpty() ? args.get(args.size() - 1) : "";
if (args.isEmpty()) {
// Don't show every player on the server. Require at least the first letter
return Optional.empty();

View File

@ -21,8 +21,9 @@ public class AdminVersionCommand extends CompositeCommand {
@Override
public boolean execute(User user, String label, List<String> args) {
user.sendMessage("commands.bentobox.version.addon-syntax", TextVariables.NAME, getAddon().getDescription().getName(),
TextVariables.VERSION, getAddon().getDescription().getVersion(), "[state]", getAddon().getState().name());
user.sendMessage("commands.bentobox.version.addon-syntax", TextVariables.NAME,
getAddon().getDescription().getName(), TextVariables.VERSION, getAddon().getDescription().getVersion(),
"[state]", getAddon().getState().name());
return true;
}

View File

@ -48,23 +48,26 @@ public class AdminWhyCommand extends ConfirmableCommand {
}
// Determine the debug mode and toggle if required
boolean newValue = !target.getPlayer().getMetadata(getWorld().getName() + "_why_debug").stream()
.filter(p -> getPlugin().equals(p.getOwningPlugin())).findFirst().map(MetadataValue::asBoolean).orElse(false);
.filter(p -> getPlugin().equals(p.getOwningPlugin())).findFirst().map(MetadataValue::asBoolean)
.orElse(false);
if (newValue) {
user.sendMessage("commands.admin.why.turning-on", TextVariables.NAME, target.getName());
} else {
user.sendMessage("commands.admin.why.turning-off", TextVariables.NAME, target.getName());
}
// Set the debug meta
target.getPlayer().setMetadata(getWorld().getName() + "_why_debug", new FixedMetadataValue(getPlugin(), newValue));
target.getPlayer().setMetadata(getWorld().getName() + "_why_debug",
new FixedMetadataValue(getPlugin(), newValue));
if (user.isPlayer()) {
target.getPlayer().setMetadata(getWorld().getName() + "_why_debug_issuer", new FixedMetadataValue(getPlugin(), user.getUniqueId().toString()));
target.getPlayer().setMetadata(getWorld().getName() + "_why_debug_issuer",
new FixedMetadataValue(getPlugin(), user.getUniqueId().toString()));
}
return true;
}
@Override
public Optional<List<String>> tabComplete(User user, String alias, List<String> args) {
String lastArg = !args.isEmpty() ? args.get(args.size()-1) : "";
String lastArg = !args.isEmpty() ? args.get(args.size() - 1) : "";
if (args.isEmpty()) {
// Don't show every player on the server. Require at least the first letter
return Optional.empty();

View File

@ -19,8 +19,9 @@ import world.bentobox.bentobox.api.localization.TextVariables;
import world.bentobox.bentobox.api.user.User;
/**
* This is default Admin command for console and op. It contains all necessary parts that
* for main command.
* This is default Admin command for console and op. It contains all necessary
* parts that for main command.
*
* @since 1.13.0
* @author BONNe
*/
@ -28,18 +29,18 @@ public abstract class DefaultAdminCommand extends CompositeCommand {
/**
* This is the top-level command constructor for commands that have no parent.
*
* @param addon - GameMode addon
* @param addon - GameMode addon
*/
protected DefaultAdminCommand(GameModeAddon addon) {
// Register command with alias from config.
// The first command listed is the "label" and the others are aliases.
super(addon,
addon.getWorldSettings().getAdminCommandAliases().split(" ")[0],
super(addon, addon.getWorldSettings().getAdminCommandAliases().split(" ")[0],
addon.getWorldSettings().getAdminCommandAliases().split(" "));
}
/**
* Setups anything that is necessary for default main admin command.
*
* @see world.bentobox.bentobox.api.commands.BentoBoxCommand#setup()
*/
@Override
@ -103,7 +104,9 @@ public abstract class DefaultAdminCommand extends CompositeCommand {
/**
* Defines what will be executed when this command is run.
* @see world.bentobox.bentobox.api.commands.BentoBoxCommand#execute(User, String, List)
*
* @see world.bentobox.bentobox.api.commands.BentoBoxCommand#execute(User,
* String, List)
*/
@Override
public boolean execute(User user, String label, List<String> args) {

View File

@ -62,30 +62,25 @@ public class AdminBlueprintCommand extends ConfirmableCommand {
return clipboards;
}
/**
* This method shows clipboard for requested user.
*
* @param user User who need to see clipboard.
*/
protected void showClipboard(User user)
{
protected void showClipboard(User user) {
this.displayClipboards.computeIfAbsent(user,
key -> Bukkit.getScheduler().scheduleSyncRepeatingTask(this.getPlugin(), () ->
{
if (!key.isPlayer() || !key.getPlayer().isOnline())
{
this.hideClipboard(key);
}
key -> Bukkit.getScheduler().scheduleSyncRepeatingTask(this.getPlugin(), () -> {
if (!key.isPlayer() || !key.getPlayer().isOnline()) {
this.hideClipboard(key);
}
if (this.clipboards.containsKey(key.getUniqueId()))
{
BlueprintClipboard clipboard = this.clipboards.get(key.getUniqueId());
this.paintAxis(key, clipboard);
}
}, 20, 20));
if (this.clipboards.containsKey(key.getUniqueId())) {
BlueprintClipboard clipboard = this.clipboards.get(key.getUniqueId());
this.paintAxis(key, clipboard);
}
}, 20, 20));
}
private void paintAxis(User user, BlueprintClipboard clipboard) {
if (clipboard.getPos1() == null || clipboard.getPos2() == null) {
return;

View File

@ -7,37 +7,29 @@ import world.bentobox.bentobox.api.commands.CompositeCommand;
import world.bentobox.bentobox.api.user.User;
import world.bentobox.bentobox.blueprints.BlueprintClipboard;
public class AdminBlueprintCopyCommand extends CompositeCommand
{
public AdminBlueprintCopyCommand(AdminBlueprintCommand parent)
{
public class AdminBlueprintCopyCommand extends CompositeCommand {
public AdminBlueprintCopyCommand(AdminBlueprintCommand parent) {
super(parent, "copy");
}
@Override
public void setup()
{
public void setup() {
setPermission("admin.blueprint.copy");
setParametersHelp("commands.admin.blueprint.copy.parameters");
setDescription("commands.admin.blueprint.copy.description");
}
@Override
public boolean execute(User user, String label, List<String> args)
{
if (args.size() > 2)
{
public boolean execute(User user, String label, List<String> args) {
if (args.size() > 2) {
this.showHelp(this, user);
return false;
}
AdminBlueprintCommand parent = (AdminBlueprintCommand) getParent();
BlueprintClipboard clipboard =
parent.getClipboards().computeIfAbsent(user.getUniqueId(), v -> new BlueprintClipboard());
BlueprintClipboard clipboard = parent.getClipboards().computeIfAbsent(user.getUniqueId(),
v -> new BlueprintClipboard());
boolean copyAir = args.stream().anyMatch(key -> key.equalsIgnoreCase("air"));
boolean copyBiome = args.stream().anyMatch(key -> key.equalsIgnoreCase("biome"));
@ -45,10 +37,8 @@ public class AdminBlueprintCopyCommand extends CompositeCommand
return clipboard.copy(user, copyAir, copyBiome);
}
@Override
public Optional<List<String>> tabComplete(User user, String alias, List<String> args)
{
public Optional<List<String>> tabComplete(User user, String alias, List<String> args) {
return Optional.of(List.of("air", "biome"));
}
}

View File

@ -9,34 +9,27 @@ import world.bentobox.bentobox.api.localization.TextVariables;
import world.bentobox.bentobox.api.user.User;
import world.bentobox.bentobox.util.Util;
/**
* Command that deletes a Blueprint.
*
* @author Poslovitch
* @since 1.9.0
*/
public class AdminBlueprintDeleteCommand extends ConfirmableCommand
{
public AdminBlueprintDeleteCommand(AdminBlueprintCommand parent)
{
public class AdminBlueprintDeleteCommand extends ConfirmableCommand {
public AdminBlueprintDeleteCommand(AdminBlueprintCommand parent) {
super(parent, "delete", "remove");
}
@Override
public void setup()
{
public void setup() {
setPermission("admin.blueprint.delete");
this.setParametersHelp("commands.admin.blueprint.delete.parameters");
this.setDescription("commands.admin.blueprint.delete.description");
}
@Override
public boolean execute(User user, String label, List<String> args)
{
if (args.size() != 1)
{
public boolean execute(User user, String label, List<String> args) {
if (args.size() != 1) {
this.showHelp(this, user);
return false;
}
@ -44,26 +37,21 @@ public class AdminBlueprintDeleteCommand extends ConfirmableCommand
String blueprintName = Util.sanitizeInput(args.get(0));
// Check if blueprint exist
if (this.getPlugin().getBlueprintsManager().getBlueprints(this.getAddon()).containsKey(blueprintName))
{
this.askConfirmation(user, user.getTranslation("commands.admin.blueprint.delete.confirmation"),
() -> {
this.getPlugin().getBlueprintsManager().deleteBlueprint(this.getAddon(), blueprintName);
user.sendMessage("commands.admin.blueprint.delete.success", TextVariables.NAME, blueprintName);
});
if (this.getPlugin().getBlueprintsManager().getBlueprints(this.getAddon()).containsKey(blueprintName)) {
this.askConfirmation(user, user.getTranslation("commands.admin.blueprint.delete.confirmation"), () -> {
this.getPlugin().getBlueprintsManager().deleteBlueprint(this.getAddon(), blueprintName);
user.sendMessage("commands.admin.blueprint.delete.success", TextVariables.NAME, blueprintName);
});
return true;
}
else
{
} else {
user.sendMessage("commands.admin.blueprint.delete.no-blueprint", TextVariables.NAME, blueprintName);
return false;
}
}
@Override
public Optional<List<String>> tabComplete(User user, String alias, List<String> args)
{
return Optional.of(new LinkedList<>(this.getPlugin().getBlueprintsManager().getBlueprints(this.getAddon()).keySet()));
public Optional<List<String>> tabComplete(User user, String alias, List<String> args) {
return Optional
.of(new LinkedList<>(this.getPlugin().getBlueprintsManager().getBlueprints(this.getAddon()).keySet()));
}
}

View File

@ -10,28 +10,21 @@ import world.bentobox.bentobox.api.commands.CompositeCommand;
import world.bentobox.bentobox.api.user.User;
import world.bentobox.bentobox.managers.BlueprintsManager;
public class AdminBlueprintListCommand extends CompositeCommand
{
public class AdminBlueprintListCommand extends CompositeCommand {
public AdminBlueprintListCommand(AdminBlueprintCommand parent)
{
public AdminBlueprintListCommand(AdminBlueprintCommand parent) {
super(parent, "list");
}
@Override
public void setup()
{
public void setup() {
setPermission("admin.blueprint.list");
this.setDescription("commands.admin.blueprint.list.description");
}
@Override
public boolean canExecute(User user, String label, List<String> args)
{
if (!args.isEmpty())
{
public boolean canExecute(User user, String label, List<String> args) {
if (!args.isEmpty()) {
this.showHelp(this, user);
return false;
}
@ -39,26 +32,21 @@ public class AdminBlueprintListCommand extends CompositeCommand
return true;
}
@Override
public boolean execute(User user, String label, List<String> args)
{
public boolean execute(User user, String label, List<String> args) {
File blueprints = new File(this.getAddon().getDataFolder(), BlueprintsManager.FOLDER_NAME);
if (!blueprints.exists())
{
if (!blueprints.exists()) {
user.sendMessage("commands.admin.blueprint.list.no-blueprints");
return false;
}
FilenameFilter blueprintFilter = (File dir, String name) -> name.endsWith(BlueprintsManager.BLUEPRINT_SUFFIX);
List<String> blueprintList = Arrays.stream(Objects.requireNonNull(blueprints.list(blueprintFilter))).
map(name -> name.substring(0, name.length() - BlueprintsManager.BLUEPRINT_SUFFIX.length())).
toList();
List<String> blueprintList = Arrays.stream(Objects.requireNonNull(blueprints.list(blueprintFilter)))
.map(name -> name.substring(0, name.length() - BlueprintsManager.BLUEPRINT_SUFFIX.length())).toList();
if (blueprintList.isEmpty())
{
if (blueprintList.isEmpty()) {
user.sendMessage("commands.admin.blueprint.list.no-blueprints");
return false;
}

View File

@ -46,7 +46,7 @@ public class AdminBlueprintLoadCommand extends CompositeCommand {
options.add("island");
options.add("nether-island");
options.add("end-island");
String lastArg = !args.isEmpty() ? args.get(args.size()-1) : "";
String lastArg = !args.isEmpty() ? args.get(args.size() - 1) : "";
return Optional.of(Util.tabLimit(options, lastArg));
}

View File

@ -28,14 +28,16 @@ public class AdminBlueprintOriginCommand extends CompositeCommand {
public boolean execute(User user, String label, List<String> args) {
AdminBlueprintCommand parent = (AdminBlueprintCommand) getParent();
BlueprintClipboard clipboard = parent.getClipboards().computeIfAbsent(user.getUniqueId(), v -> new BlueprintClipboard());
BlueprintClipboard clipboard = parent.getClipboards().computeIfAbsent(user.getUniqueId(),
v -> new BlueprintClipboard());
if (clipboard.getPos1() == null || clipboard.getPos2() == null) {
user.sendMessage("commands.admin.blueprint.need-pos1-pos2");
return false;
}
// Get the block player is looking at
Block b = Objects.requireNonNull(user.getPlayer()).getLineOfSight(null, 20).stream().filter(x -> !x.getType().equals(Material.AIR)).findFirst().orElse(null);
Block b = Objects.requireNonNull(user.getPlayer()).getLineOfSight(null, 20).stream()
.filter(x -> !x.getType().equals(Material.AIR)).findFirst().orElse(null);
if (b != null) {
clipboard.setOrigin(b.getLocation().toVector());
user.getPlayer().sendBlockChange(b.getLocation(), Material.REDSTONE_BLOCK.createBlockData());

View File

@ -23,7 +23,8 @@ public class AdminBlueprintPasteCommand extends CompositeCommand {
@Override
public boolean execute(User user, String label, List<String> args) {
AdminBlueprintCommand parent = (AdminBlueprintCommand) getParent();
BlueprintClipboard clipboard = parent.getClipboards().computeIfAbsent(user.getUniqueId(), v -> new BlueprintClipboard());
BlueprintClipboard clipboard = parent.getClipboards().computeIfAbsent(user.getUniqueId(),
v -> new BlueprintClipboard());
if (clipboard.isFull()) {
new BlueprintPaster(getPlugin(), clipboard, user.getLocation()).paste().thenAccept(b -> {
user.sendMessage("general.success");

View File

@ -23,7 +23,8 @@ public class AdminBlueprintPos1Command extends CompositeCommand {
@Override
public boolean execute(User user, String label, List<String> args) {
AdminBlueprintCommand parent = (AdminBlueprintCommand) getParent();
BlueprintClipboard clipboard = parent.getClipboards().computeIfAbsent(user.getUniqueId(), v -> new BlueprintClipboard());
BlueprintClipboard clipboard = parent.getClipboards().computeIfAbsent(user.getUniqueId(),
v -> new BlueprintClipboard());
if (user.getLocation().equals(clipboard.getPos2())) {
user.sendMessage("commands.admin.blueprint.set-different-pos");

View File

@ -23,7 +23,8 @@ public class AdminBlueprintPos2Command extends CompositeCommand {
@Override
public boolean execute(User user, String label, List<String> args) {
AdminBlueprintCommand parent = (AdminBlueprintCommand) getParent();
BlueprintClipboard clipboard = parent.getClipboards().computeIfAbsent(user.getUniqueId(), v -> new BlueprintClipboard());
BlueprintClipboard clipboard = parent.getClipboards().computeIfAbsent(user.getUniqueId(),
v -> new BlueprintClipboard());
if (user.getLocation().equals(clipboard.getPos1())) {
user.sendMessage("commands.admin.blueprint.set-different-pos");

View File

@ -10,34 +10,27 @@ import world.bentobox.bentobox.blueprints.Blueprint;
import world.bentobox.bentobox.managers.BlueprintsManager;
import world.bentobox.bentobox.util.Util;
/**
* Renames an existing blueprint.
*
* @author Poslovitch
* @since 1.10.0
*/
public class AdminBlueprintRenameCommand extends ConfirmableCommand
{
public AdminBlueprintRenameCommand(AdminBlueprintCommand parent)
{
public class AdminBlueprintRenameCommand extends ConfirmableCommand {
public AdminBlueprintRenameCommand(AdminBlueprintCommand parent) {
super(parent, "rename");
}
@Override
public void setup()
{
public void setup() {
setPermission("admin.blueprint.rename");
this.setParametersHelp("commands.admin.blueprint.rename.parameters");
this.setDescription("commands.admin.blueprint.rename.description");
}
@Override
public boolean canExecute(User user, String label, List<String> args)
{
if (args.size() != 2)
{
public boolean canExecute(User user, String label, List<String> args) {
if (args.size() != 2) {
// Blueprint must have a name.
this.showHelp(this, user);
return false;
@ -47,8 +40,7 @@ public class AdminBlueprintRenameCommand extends ConfirmableCommand
String to = Util.sanitizeInput(args.get(1));
// Check if name is changed.
if (from.equals(to))
{
if (from.equals(to)) {
user.sendMessage("commands.admin.blueprint.rename.pick-different-name");
return false;
}
@ -57,8 +49,7 @@ public class AdminBlueprintRenameCommand extends ConfirmableCommand
AdminBlueprintCommand parent = (AdminBlueprintCommand) this.getParent();
File fromFile = new File(parent.getBlueprintsFolder(), from + BlueprintsManager.BLUEPRINT_SUFFIX);
if (!fromFile.exists())
{
if (!fromFile.exists()) {
user.sendMessage("commands.admin.blueprint.no-such-file");
return false;
}
@ -66,10 +57,8 @@ public class AdminBlueprintRenameCommand extends ConfirmableCommand
return true;
}
@Override
public boolean execute(User user, String label, List<String> args)
{
public boolean execute(User user, String label, List<String> args) {
AdminBlueprintCommand parent = (AdminBlueprintCommand) getParent();
// Check if the names are the same
@ -79,34 +68,23 @@ public class AdminBlueprintRenameCommand extends ConfirmableCommand
// Check if the 'to' file exists
File toFile = new File(parent.getBlueprintsFolder(), to + BlueprintsManager.BLUEPRINT_SUFFIX);
if (toFile.exists())
{
if (toFile.exists()) {
// Ask for confirmation to overwrite
this.askConfirmation(user,
user.getTranslation("commands.admin.blueprint.file-exists"),
this.askConfirmation(user, user.getTranslation("commands.admin.blueprint.file-exists"),
() -> this.rename(user, from, to, args.get(1)));
}
else
{
} else {
this.askConfirmation(user, () -> this.rename(user, from, to, args.get(1)));
}
return true;
}
private void rename(User user, String blueprintName, String fileName, String displayName)
{
private void rename(User user, String blueprintName, String fileName, String displayName) {
Blueprint blueprint = this.getPlugin().getBlueprintsManager().getBlueprints(this.getAddon()).get(blueprintName);
this.getPlugin().getBlueprintsManager().renameBlueprint(this.getAddon(), blueprint, fileName, displayName);
user.sendMessage("commands.admin.blueprint.rename.success",
"[old]",
blueprintName,
TextVariables.NAME,
blueprint.getName(),
"[display]",
blueprint.getDisplayName());
user.sendMessage("commands.admin.blueprint.rename.success", "[old]", blueprintName, TextVariables.NAME,
blueprint.getName(), "[display]", blueprint.getDisplayName());
}
}

View File

@ -10,49 +10,39 @@ import world.bentobox.bentobox.managers.BlueprintClipboardManager;
import world.bentobox.bentobox.managers.BlueprintsManager;
import world.bentobox.bentobox.util.Util;
/**
* This method allows to save blueprint from the clipboard.
*/
public class AdminBlueprintSaveCommand extends ConfirmableCommand
{
public AdminBlueprintSaveCommand(AdminBlueprintCommand parent)
{
public class AdminBlueprintSaveCommand extends ConfirmableCommand {
public AdminBlueprintSaveCommand(AdminBlueprintCommand parent) {
super(parent, "save");
}
@Override
public void setup()
{
public void setup() {
setPermission("admin.blueprint.save");
this.setParametersHelp("commands.admin.blueprint.save.parameters");
this.setDescription("commands.admin.blueprint.save.description");
}
@Override
public boolean canExecute(User user, String label, List<String> args)
{
if (args.size() != 1)
{
public boolean canExecute(User user, String label, List<String> args) {
if (args.size() != 1) {
// Blueprint must have a name.
this.showHelp(this, user);
return false;
}
BlueprintClipboard clipboard = ((AdminBlueprintCommand) this.getParent()).getClipboards().
computeIfAbsent(user.getUniqueId(), v -> new BlueprintClipboard());
BlueprintClipboard clipboard = ((AdminBlueprintCommand) this.getParent()).getClipboards()
.computeIfAbsent(user.getUniqueId(), v -> new BlueprintClipboard());
if (!clipboard.isFull())
{
if (!clipboard.isFull()) {
// Clipboard is not set up.
user.sendMessage("commands.admin.blueprint.copy-first");
return false;
}
if (clipboard.getBlueprint() != null && clipboard.getBlueprint().getBedrock() == null)
{
if (clipboard.getBlueprint() != null && clipboard.getBlueprint().getBedrock() == null) {
// Bedrock is required for all blueprints.
user.sendMessage("commands.admin.blueprint.bedrock-required");
return false;
@ -61,23 +51,19 @@ public class AdminBlueprintSaveCommand extends ConfirmableCommand
return true;
}
@Override
public boolean execute(User user, String label, List<String> args)
{
public boolean execute(User user, String label, List<String> args) {
AdminBlueprintCommand parent = (AdminBlueprintCommand) this.getParent();
BlueprintClipboard clipboard = parent.getClipboards().
computeIfAbsent(user.getUniqueId(), v -> new BlueprintClipboard());
BlueprintClipboard clipboard = parent.getClipboards().computeIfAbsent(user.getUniqueId(),
v -> new BlueprintClipboard());
String fileName = Util.sanitizeInput(args.get(0));
// Check if file exists
File newFile = new File(parent.getBlueprintsFolder(), fileName + BlueprintsManager.BLUEPRINT_SUFFIX);
if (newFile.exists())
{
this.askConfirmation(user,
user.getTranslation("commands.admin.blueprint.file-exists"),
if (newFile.exists()) {
this.askConfirmation(user, user.getTranslation("commands.admin.blueprint.file-exists"),
() -> this.hideAndSave(user, parent, clipboard, fileName, args.get(0)));
return false;
}
@ -85,29 +71,23 @@ public class AdminBlueprintSaveCommand extends ConfirmableCommand
return this.hideAndSave(user, parent, clipboard, fileName, args.get(0));
}
/**
* This method saves given blueprint.
* @param user User that triggers blueprint save.
* @param parent Parent command that contains clipboard.
* @param clipboard Active clipboard.
* @param name Filename for the blueprint
*
* @param user User that triggers blueprint save.
* @param parent Parent command that contains clipboard.
* @param clipboard Active clipboard.
* @param name Filename for the blueprint
* @param displayName Display name for the blueprint.
* @return {@code true} if blueprint is saved, {@code false} otherwise.
*/
private boolean hideAndSave(User user,
AdminBlueprintCommand parent,
BlueprintClipboard clipboard,
String name,
String displayName)
{
private boolean hideAndSave(User user, AdminBlueprintCommand parent, BlueprintClipboard clipboard, String name,
String displayName) {
parent.hideClipboard(user);
boolean result = new BlueprintClipboardManager(this.getPlugin(),
parent.getBlueprintsFolder(), clipboard).
save(user, name, displayName);
boolean result = new BlueprintClipboardManager(this.getPlugin(), parent.getBlueprintsFolder(), clipboard)
.save(user, name, displayName);
if (result && clipboard.isFull())
{
if (result && clipboard.isFull()) {
this.getPlugin().getBlueprintsManager().addBlueprint(this.getAddon(), clipboard.getBlueprint());
}

View File

@ -12,6 +12,7 @@ import world.bentobox.bentobox.database.objects.Island;
/**
* Renames a home
*
* @author tastybento
*
*/

View File

@ -40,10 +40,10 @@ public class AdminDeathsAddCommand extends CompositeCommand {
} else if (!Util.isInteger(args.get(1), true) || Integer.parseInt(args.get(1)) < 0) {
user.sendMessage("general.errors.must-be-positive-number", TextVariables.NUMBER, args.get(1));
} else {
getPlayers().setDeaths(getWorld(), targetUUID, getPlayers().getDeaths(getWorld(), targetUUID) + Integer.parseInt(args.get(1)));
user.sendMessage("commands.admin.deaths.add.success",
TextVariables.NAME, args.get(0), TextVariables.NUMBER, args.get(1),
"[total]", String.valueOf(getPlayers().getDeaths(getWorld(), targetUUID)));
getPlayers().setDeaths(getWorld(), targetUUID,
getPlayers().getDeaths(getWorld(), targetUUID) + Integer.parseInt(args.get(1)));
user.sendMessage("commands.admin.deaths.add.success", TextVariables.NAME, args.get(0), TextVariables.NUMBER,
args.get(1), "[total]", String.valueOf(getPlayers().getDeaths(getWorld(), targetUUID)));
return true;
}

View File

@ -43,9 +43,8 @@ public class AdminDeathsRemoveCommand extends CompositeCommand {
// Make sure it cannot go under 0.
int newDeaths = Math.max(getPlayers().getDeaths(getWorld(), targetUUID) - Integer.parseInt(args.get(1)), 0);
getPlayers().setDeaths(getWorld(), targetUUID, newDeaths);
user.sendMessage("commands.admin.deaths.remove.success",
TextVariables.NAME, args.get(0), TextVariables.NUMBER, args.get(1),
"[total]", String.valueOf(newDeaths));
user.sendMessage("commands.admin.deaths.remove.success", TextVariables.NAME, args.get(0),
TextVariables.NUMBER, args.get(1), "[total]", String.valueOf(newDeaths));
return true;
}

View File

@ -40,7 +40,8 @@ public class AdminDeathsSetCommand extends CompositeCommand {
user.sendMessage("general.errors.must-be-positive-number", TextVariables.NUMBER, args.get(1));
} else {
getPlayers().setDeaths(getWorld(), targetUUID, Integer.parseInt(args.get(1)));
user.sendMessage("commands.admin.deaths.set.success", TextVariables.NAME, args.get(0), TextVariables.NUMBER, args.get(1));
user.sendMessage("commands.admin.deaths.set.success", TextVariables.NAME, args.get(0), TextVariables.NUMBER,
args.get(1));
return true;
}

View File

@ -76,13 +76,14 @@ public class AdminPurgeCommand extends CompositeCommand implements Listener {
return false;
}
islands = getOldIslands(days);
user.sendMessage("commands.admin.purge.purgable-islands", TextVariables.NUMBER, String.valueOf(islands.size()));
user.sendMessage("commands.admin.purge.purgable-islands", TextVariables.NUMBER,
String.valueOf(islands.size()));
if (!islands.isEmpty()) {
toBeConfirmed = true;
user.sendMessage("commands.admin.purge.confirm", TextVariables.LABEL, this.getTopLabel());
return false;
}
} catch(Exception e) {
} catch (Exception e) {
user.sendMessage("commands.admin.purge.number-error");
return false;
}
@ -103,8 +104,9 @@ public class AdminPurgeCommand extends CompositeCommand implements Listener {
getIslands().getIslandById(it.next()).ifPresent(i -> {
getIslands().deleteIsland(i, true, null);
count++;
String percentage = String.format("%.1f", (((float) count)/getPurgeableIslandsCount() * 100));
getPlugin().log(count + " islands purged out of " + getPurgeableIslandsCount() + " (" + percentage + " %)");
String percentage = String.format("%.1f", (((float) count) / getPurgeableIslandsCount() * 100));
getPlugin().log(
count + " islands purged out of " + getPurgeableIslandsCount() + " (" + percentage + " %)");
});
} else {
user.sendMessage("commands.admin.purge.completed");
@ -121,28 +123,26 @@ public class AdminPurgeCommand extends CompositeCommand implements Listener {
}
Set<String> getOldIslands(int days) {
getPlugin().getIslands().getIslands().stream()
.filter(i -> !i.isSpawn())
.filter(i -> !i.getPurgeProtected())
.filter(i -> i.getWorld().equals(this.getWorld()))
.filter(Island::isOwned)
.filter(i -> i.getMembers().size() == 1)
.filter(i -> ((double)(System.currentTimeMillis() - Bukkit.getOfflinePlayer(i.getOwner()).getLastPlayed()) / 1000 / 3600 / 24) > days)
.forEach(i -> {
Date date = new Date(Bukkit.getOfflinePlayer(i.getOwner()).getLastPlayed());
BentoBox.getInstance().log("Will purge " +
BentoBox.getInstance().getPlayers().getName(i.getOwner()) +
" last logged in " + (int)((double)(System.currentTimeMillis() - Bukkit.getOfflinePlayer(i.getOwner()).getLastPlayed()) / 1000 / 3600 / 24) + " days ago. " + date);
});
return getPlugin().getIslands().getIslands().stream()
.filter(i -> !i.isSpawn())
.filter(i -> !i.getPurgeProtected())
.filter(i -> i.getWorld().equals(this.getWorld()))
.filter(Island::isOwned)
getPlugin().getIslands().getIslands().stream().filter(i -> !i.isSpawn()).filter(i -> !i.getPurgeProtected())
.filter(i -> i.getWorld().equals(this.getWorld())).filter(Island::isOwned)
.filter(i -> i.getMembers().size() == 1)
.filter(i -> ((double)(System.currentTimeMillis() - Bukkit.getOfflinePlayer(i.getOwner()).getLastPlayed()) / 1000 / 3600 / 24) > days)
.map(Island::getUniqueId)
.collect(Collectors.toSet());
.filter(i -> ((double) (System.currentTimeMillis()
- Bukkit.getOfflinePlayer(i.getOwner()).getLastPlayed()) / 1000 / 3600 / 24) > days)
.forEach(i -> {
Date date = new Date(Bukkit.getOfflinePlayer(i.getOwner()).getLastPlayed());
BentoBox.getInstance()
.log("Will purge " + BentoBox.getInstance().getPlayers().getName(i.getOwner())
+ " last logged in "
+ (int) ((double) (System.currentTimeMillis()
- Bukkit.getOfflinePlayer(i.getOwner()).getLastPlayed()) / 1000 / 3600 / 24)
+ " days ago. " + date);
});
return getPlugin().getIslands().getIslands().stream().filter(i -> !i.isSpawn())
.filter(i -> !i.getPurgeProtected()).filter(i -> i.getWorld().equals(this.getWorld()))
.filter(Island::isOwned).filter(i -> i.getMembers().size() == 1)
.filter(i -> ((double) (System.currentTimeMillis()
- Bukkit.getOfflinePlayer(i.getOwner()).getLastPlayed()) / 1000 / 3600 / 24) > days)
.map(Island::getUniqueId).collect(Collectors.toSet());
}
/**
@ -175,6 +175,7 @@ public class AdminPurgeCommand extends CompositeCommand implements Listener {
/**
* Returns the amount of purged islands.
*
* @return the amount of islands that have been purged.
* @since 1.13.0
*/
@ -184,6 +185,7 @@ public class AdminPurgeCommand extends CompositeCommand implements Listener {
/**
* Returns the amount of islands that can be purged.
*
* @return the amount of islands that can be purged.
* @since 1.13.0
*/

View File

@ -8,6 +8,7 @@ import world.bentobox.bentobox.api.user.User;
/**
* Displays the current status and progress of the purge.
*
* @since 1.13.0
* @author Poslovitch
*/
@ -32,15 +33,14 @@ public class AdminPurgeStatusCommand extends CompositeCommand {
showHelp(this, user);
return false;
}
AdminPurgeCommand parentCommand = ((AdminPurgeCommand)getParent());
AdminPurgeCommand parentCommand = ((AdminPurgeCommand) getParent());
if (parentCommand.isInPurge()) {
int purged = parentCommand.getPurgedIslandsCount();
int purgeable = parentCommand.getPurgeableIslandsCount();
user.sendMessage("commands.admin.purge.purge-in-progress", TextVariables.LABEL, this.getTopLabel());
user.sendMessage("commands.admin.purge.status.status",
"[purged]", String.valueOf(purged),
"[purgeable]", String.valueOf(purgeable),
"[percentage]", String.format("%.1f", (((float) purged)/purgeable) * 100));
user.sendMessage("commands.admin.purge.status.status", "[purged]", String.valueOf(purged), "[purgeable]",
String.valueOf(purgeable), "[percentage]",
String.format("%.1f", (((float) purged) / purgeable) * 100));
} else {
user.sendMessage("commands.admin.purge.no-purge-in-progress");
}

View File

@ -25,7 +25,7 @@ public class AdminPurgeStopCommand extends CompositeCommand {
showHelp(this, user);
return false;
}
AdminPurgeCommand parentCommand = ((AdminPurgeCommand)getParent());
AdminPurgeCommand parentCommand = ((AdminPurgeCommand) getParent());
if (parentCommand.isInPurge()) {
user.sendMessage("commands.admin.purge.stop.stopping");
parentCommand.stop();

View File

@ -30,13 +30,14 @@ public class AdminPurgeUnownedCommand extends ConfirmableCommand {
showHelp(this, user);
return false;
}
AdminPurgeCommand parentCommand = ((AdminPurgeCommand)getParent());
AdminPurgeCommand parentCommand = ((AdminPurgeCommand) getParent());
if (parentCommand.isInPurge()) {
user.sendMessage("commands.admin.purge.purge-in-progress", TextVariables.LABEL, this.getTopLabel());
return false;
}
Set<String> unowned = getUnownedIslands();
user.sendMessage("commands.admin.purge.unowned.unowned-islands", TextVariables.NUMBER, String.valueOf(unowned.size()));
user.sendMessage("commands.admin.purge.unowned.unowned-islands", TextVariables.NUMBER,
String.valueOf(unowned.size()));
if (!unowned.isEmpty()) {
this.askConfirmation(user, () -> {
parentCommand.setUser(user);
@ -48,13 +49,9 @@ public class AdminPurgeUnownedCommand extends ConfirmableCommand {
}
Set<String> getUnownedIslands() {
return getPlugin().getIslands().getIslands().stream()
.filter(i -> !i.isSpawn())
.filter(i -> !i.getPurgeProtected())
.filter(i -> i.getWorld().equals(this.getWorld()))
.filter(Island::isUnowned)
.map(Island::getUniqueId)
.collect(Collectors.toSet());
return getPlugin().getIslands().getIslands().stream().filter(i -> !i.isSpawn())
.filter(i -> !i.getPurgeProtected()).filter(i -> i.getWorld().equals(this.getWorld()))
.filter(Island::isUnowned).map(Island::getUniqueId).collect(Collectors.toSet());
}

View File

@ -57,7 +57,8 @@ public class AdminRangeAddCommand extends CompositeCommand {
int newRange = island.getProtectionRange() + Integer.parseInt(args.get(1));
if (newRange > island.getRange()) {
user.sendMessage("commands.admin.range.invalid-value.too-high", TextVariables.NUMBER, String.valueOf(island.getRange()));
user.sendMessage("commands.admin.range.invalid-value.too-high", TextVariables.NUMBER,
String.valueOf(island.getRange()));
return false;
} else if (newRange == island.getProtectionRange()) {
user.sendMessage("commands.admin.range.invalid-value.same-as-before", TextVariables.NUMBER, args.get(1));
@ -71,18 +72,11 @@ public class AdminRangeAddCommand extends CompositeCommand {
island.setProtectionRange(newRange);
// Call Protection Range Change event. Does not support cancelling.
IslandEvent.builder()
.island(island)
.location(island.getCenter())
.reason(IslandEvent.Reason.RANGE_CHANGE)
.involvedPlayer(targetUUID)
.admin(true)
.protectionRange(newRange, oldRange)
.build();
IslandEvent.builder().island(island).location(island.getCenter()).reason(IslandEvent.Reason.RANGE_CHANGE)
.involvedPlayer(targetUUID).admin(true).protectionRange(newRange, oldRange).build();
user.sendMessage("commands.admin.range.add.success",
TextVariables.NAME, args.get(0), TextVariables.NUMBER, args.get(1),
"[total]", String.valueOf(newRange));
user.sendMessage("commands.admin.range.add.success", TextVariables.NAME, args.get(0), TextVariables.NUMBER,
args.get(1), "[total]", String.valueOf(newRange));
return true;
}

View File

@ -11,7 +11,7 @@ import world.bentobox.bentobox.api.user.User;
public class AdminRangeCommand extends CompositeCommand {
public AdminRangeCommand(CompositeCommand parent) {
super (parent, "range");
super(parent, "range");
}
@Override

View File

@ -40,7 +40,8 @@ public class AdminRangeDisplayCommand extends CompositeCommand {
@Override
public boolean execute(User user, String label, List<String> args) {
// According to the label used to execute the command, there is a different behaviour
// According to the label used to execute the command, there is a different
// behaviour
// - display : toggle on/off
// - show : only set on - and send "error" if already on
// - hide : only set off - same if already off
@ -72,15 +73,18 @@ public class AdminRangeDisplayCommand extends CompositeCommand {
getIslands().getIslandAt(user.getLocation()).ifPresent(island -> {
// Draw the island protected area
drawZone(user, Particle.BLOCK_MARKER, Material.BARRIER.createBlockData(), island, island.getProtectionRange());
drawZone(user, Particle.BLOCK_MARKER, Material.BARRIER.createBlockData(), island,
island.getProtectionRange());
// Draw the default protected area if island protected zone is different
if (island.getProtectionRange() != getPlugin().getIWM().getIslandProtectionRange(getWorld())) {
drawZone(user, Particle.VILLAGER_HAPPY, null, island, getPlugin().getIWM().getIslandProtectionRange(getWorld()));
drawZone(user, Particle.VILLAGER_HAPPY, null, island,
getPlugin().getIWM().getIslandProtectionRange(getWorld()));
}
// Draw the island area
drawZone(user, Particle.REDSTONE, new Particle.DustOptions(Color.GRAY, 1.0F), island, island.getRange());
drawZone(user, Particle.REDSTONE, new Particle.DustOptions(Color.GRAY, 1.0F), island,
island.getRange());
});
}, 20, 30));
}
@ -97,12 +101,16 @@ public class AdminRangeDisplayCommand extends CompositeCommand {
int playerY = user.getPlayer().getLocation().getBlockY() + 1;
// Draw 3 "stages" (one line below, at and above player's y coordinate)
for (int stage = -1 ; stage <= 1 ; stage++) {
for (int i = -range ; i <= range ; i++) {
user.spawnParticle(particle, dustOptions, (double)center.getBlockX() + i, (double)playerY + stage, (double)center.getBlockZ() + range);
user.spawnParticle(particle, dustOptions, (double)center.getBlockX() + i, (double)playerY + stage, (double)center.getBlockZ() - range);
user.spawnParticle(particle, dustOptions, (double)center.getBlockX() + range, (double)playerY + stage, (double)center.getBlockZ() + i);
user.spawnParticle(particle, dustOptions, (double)center.getBlockX() - range, (double)playerY + stage, (double)center.getBlockZ() + i);
for (int stage = -1; stage <= 1; stage++) {
for (int i = -range; i <= range; i++) {
user.spawnParticle(particle, dustOptions, (double) center.getBlockX() + i, (double) playerY + stage,
(double) center.getBlockZ() + range);
user.spawnParticle(particle, dustOptions, (double) center.getBlockX() + i, (double) playerY + stage,
(double) center.getBlockZ() - range);
user.spawnParticle(particle, dustOptions, (double) center.getBlockX() + range, (double) playerY + stage,
(double) center.getBlockZ() + i);
user.spawnParticle(particle, dustOptions, (double) center.getBlockX() - range, (double) playerY + stage,
(double) center.getBlockZ() + i);
}
}
}

View File

@ -57,7 +57,8 @@ public class AdminRangeRemoveCommand extends CompositeCommand {
int newRange = island.getProtectionRange() - Integer.parseInt(args.get(1));
if (newRange <= 1) {
user.sendMessage("commands.admin.range.invalid-value.too-low", TextVariables.NUMBER, String.valueOf(island.getRange()));
user.sendMessage("commands.admin.range.invalid-value.too-low", TextVariables.NUMBER,
String.valueOf(island.getRange()));
return false;
} else if (newRange == island.getProtectionRange()) {
user.sendMessage("commands.admin.range.invalid-value.same-as-before", TextVariables.NUMBER, args.get(1));
@ -71,18 +72,11 @@ public class AdminRangeRemoveCommand extends CompositeCommand {
island.setProtectionRange(newRange);
// Call Protection Range Change event. Does not support cancelling.
IslandEvent.builder()
.island(island)
.location(island.getCenter())
.reason(IslandEvent.Reason.RANGE_CHANGE)
.involvedPlayer(targetUUID)
.admin(true)
.protectionRange(newRange, oldRange)
.build();
IslandEvent.builder().island(island).location(island.getCenter()).reason(IslandEvent.Reason.RANGE_CHANGE)
.involvedPlayer(targetUUID).admin(true).protectionRange(newRange, oldRange).build();
user.sendMessage("commands.admin.range.remove.success",
TextVariables.NAME, args.get(0), TextVariables.NUMBER, args.get(1),
"[total]", String.valueOf(newRange));
user.sendMessage("commands.admin.range.remove.success", TextVariables.NAME, args.get(0), TextVariables.NUMBER,
args.get(1), "[total]", String.valueOf(newRange));
return true;
}

View File

@ -57,14 +57,8 @@ public class AdminRangeResetCommand extends CompositeCommand {
if (oldRange != range) {
// Call Protection Range Change event. Does not support cancelling.
IslandEvent.builder()
.island(island)
.location(island.getCenter())
.reason(IslandEvent.Reason.RANGE_CHANGE)
.involvedPlayer(targetUUID)
.admin(true)
.protectionRange(range, oldRange)
.build();
IslandEvent.builder().island(island).location(island.getCenter()).reason(IslandEvent.Reason.RANGE_CHANGE)
.involvedPlayer(targetUUID).admin(true).protectionRange(range, oldRange).build();
}
user.sendMessage("commands.admin.range.reset.success", TextVariables.NUMBER, String.valueOf(range));
@ -74,7 +68,7 @@ public class AdminRangeResetCommand extends CompositeCommand {
@Override
public Optional<List<String>> tabComplete(User user, String alias, List<String> args) {
String lastArg = !args.isEmpty() ? args.get(args.size()-1) : "";
String lastArg = !args.isEmpty() ? args.get(args.size() - 1) : "";
if (args.isEmpty()) {
// Don't show every player on the server. Require at least the first letter
return Optional.empty();

View File

@ -55,13 +55,15 @@ public class AdminRangeSetCommand extends CompositeCommand {
// Get island
Island island = Objects.requireNonNull(getIslands().getIsland(getWorld(), targetUUID));
// Do some sanity checks to make sure the new protection range won't cause problems
// Do some sanity checks to make sure the new protection range won't cause
// problems
if (range < 1) {
user.sendMessage("commands.admin.range.invalid-value.too-low", TextVariables.NUMBER, args.get(1));
return false;
}
if (range > island.getRange() * 2) {
user.sendMessage("commands.admin.range.invalid-value.too-high", TextVariables.NUMBER, String.valueOf(2 * island.getRange()));
user.sendMessage("commands.admin.range.invalid-value.too-high", TextVariables.NUMBER,
String.valueOf(2 * island.getRange()));
return false;
}
if (range == island.getProtectionRange()) {
@ -76,14 +78,8 @@ public class AdminRangeSetCommand extends CompositeCommand {
island.setProtectionRange(range);
// Call Protection Range Change event. Does not support canceling.
IslandEvent.builder()
.island(island)
.location(island.getCenter())
.reason(IslandEvent.Reason.RANGE_CHANGE)
.involvedPlayer(targetUUID)
.admin(true)
.protectionRange(range, oldRange)
.build();
IslandEvent.builder().island(island).location(island.getCenter()).reason(IslandEvent.Reason.RANGE_CHANGE)
.involvedPlayer(targetUUID).admin(true).protectionRange(range, oldRange).build();
user.sendMessage("commands.admin.range.set.success", TextVariables.NUMBER, String.valueOf(range));
@ -92,7 +88,7 @@ public class AdminRangeSetCommand extends CompositeCommand {
@Override
public Optional<List<String>> tabComplete(User user, String alias, List<String> args) {
String lastArg = !args.isEmpty() ? args.get(args.size()-1) : "";
String lastArg = !args.isEmpty() ? args.get(args.size() - 1) : "";
if (args.isEmpty()) {
// Don't show every player on the server. Require at least the first letter
return Optional.empty();

View File

@ -40,10 +40,10 @@ public class AdminResetsAddCommand extends CompositeCommand {
} else if (!Util.isInteger(args.get(1), true) || Integer.parseInt(args.get(1)) < 0) {
user.sendMessage("general.errors.must-be-positive-number", TextVariables.NUMBER, args.get(1));
} else {
getPlayers().setResets(getWorld(), targetUUID, getPlayers().getResets(getWorld(), targetUUID) + Integer.parseInt(args.get(1)));
user.sendMessage("commands.admin.resets.add.success",
TextVariables.NAME, args.get(0), TextVariables.NUMBER, args.get(1),
"[total]", String.valueOf(getPlayers().getResets(getWorld(), targetUUID)));
getPlayers().setResets(getWorld(), targetUUID,
getPlayers().getResets(getWorld(), targetUUID) + Integer.parseInt(args.get(1)));
user.sendMessage("commands.admin.resets.add.success", TextVariables.NAME, args.get(0), TextVariables.NUMBER,
args.get(1), "[total]", String.valueOf(getPlayers().getResets(getWorld(), targetUUID)));
return true;
}

View File

@ -43,9 +43,8 @@ public class AdminResetsRemoveCommand extends CompositeCommand {
// Make sure it cannot go under 0.
int newResets = Math.max(getPlayers().getResets(getWorld(), targetUUID) - Integer.parseInt(args.get(1)), 0);
getPlayers().setResets(getWorld(), targetUUID, newResets);
user.sendMessage("commands.admin.resets.remove.success",
TextVariables.NAME, args.get(0), TextVariables.NUMBER, args.get(1),
"[total]", String.valueOf(newResets));
user.sendMessage("commands.admin.resets.remove.success", TextVariables.NAME, args.get(0),
TextVariables.NUMBER, args.get(1), "[total]", String.valueOf(newResets));
return true;
}

View File

@ -40,7 +40,8 @@ public class AdminResetsResetCommand extends ConfirmableCommand {
// Set the reset epoch to now
getIWM().setResetEpoch(getWorld());
// Reset all current players
Bukkit.getOnlinePlayers().stream().map(Player::getUniqueId).filter(getPlayers()::isKnown).forEach(u -> getPlayers().setResets(getWorld(), u, 0));
Bukkit.getOnlinePlayers().stream().map(Player::getUniqueId).filter(getPlayers()::isKnown)
.forEach(u -> getPlayers().setResets(getWorld(), u, 0));
user.sendMessage("commands.admin.resets.reset.success-everyone");
});
return true;

View File

@ -35,8 +35,8 @@ public class AdminResetsSetCommand extends CompositeCommand {
user.sendMessage("general.errors.must-be-positive-number", TextVariables.NUMBER, args.get(1));
} else {
getPlayers().setResets(getWorld(), targetUUID, Integer.parseInt(args.get(1)));
user.sendMessage("commands.admin.resets.set.success",
TextVariables.NAME, args.get(0), TextVariables.NUMBER, args.get(1));
user.sendMessage("commands.admin.resets.set.success", TextVariables.NAME, args.get(0), TextVariables.NUMBER,
args.get(1));
return true;
}

View File

@ -15,73 +15,73 @@ import world.bentobox.bentobox.util.Util;
public class AdminTeamAddCommand extends CompositeCommand {
public AdminTeamAddCommand(CompositeCommand parent) {
super(parent, "add");
}
public AdminTeamAddCommand(CompositeCommand parent) {
super(parent, "add");
}
@Override
public void setup() {
setPermission("mod.team.add");
setParametersHelp("commands.admin.team.add.parameters");
setDescription("commands.admin.team.add.description");
}
@Override
public void setup() {
setPermission("mod.team.add");
setParametersHelp("commands.admin.team.add.parameters");
setDescription("commands.admin.team.add.description");
}
@Override
public boolean execute(User user, String label, List<String> args) {
// If args are not right, show help
if (args.size() != 2) {
showHelp(this, user);
return false;
}
// Get owner and target
UUID ownerUUID = Util.getUUID(args.get(0));
if (ownerUUID == null) {
user.sendMessage("general.errors.unknown-player", TextVariables.NAME, args.get(0));
return false;
}
UUID targetUUID = Util.getUUID(args.get(1));
if (targetUUID == null) {
user.sendMessage("general.errors.unknown-player", TextVariables.NAME, args.get(1));
return false;
}
if (!getIslands().hasIsland(getWorld(), ownerUUID)) {
user.sendMessage("general.errors.player-has-no-island");
return false;
}
Island island = getIslands().getPrimaryIsland(getWorld(), ownerUUID);
if (getIslands().inTeam(getWorld(), ownerUUID) && island != null && !ownerUUID.equals(island.getOwner())) {
user.sendMessage("commands.admin.team.add.name-not-owner", TextVariables.NAME, args.get(0));
new IslandInfo(island).showMembers(user);
return false;
}
if (getIslands().inTeam(getWorld(), targetUUID)) {
user.sendMessage("commands.island.team.invite.errors.already-on-team");
return false;
}
if (getIslands().hasIsland(getWorld(), targetUUID)) {
user.sendMessage("commands.admin.team.add.name-has-island", TextVariables.NAME, args.get(1));
return false;
}
// Success
User target = User.getInstance(targetUUID);
User owner = User.getInstance(ownerUUID);
owner.sendMessage("commands.island.team.invite.accept.name-joined-your-island", TextVariables.NAME,
getPlugin().getPlayers().getName(targetUUID));
target.sendMessage("commands.island.team.invite.accept.you-joined-island", TextVariables.LABEL, getTopLabel());
Island teamIsland = getIslands().getIsland(getWorld(), ownerUUID);
if (teamIsland != null) {
getIslands().setJoinTeam(teamIsland, targetUUID);
user.sendMessage("commands.admin.team.add.success", TextVariables.NAME, target.getName(), "[owner]",
owner.getName());
TeamEvent.builder().island(teamIsland).reason(TeamEvent.Reason.JOINED).involvedPlayer(targetUUID)
.admin(true).build();
IslandEvent.builder().island(teamIsland).involvedPlayer(targetUUID).admin(true)
.reason(IslandEvent.Reason.RANK_CHANGE)
.rankChange(teamIsland.getRank(target), RanksManager.MEMBER_RANK).build();
return true;
} else {
user.sendMessage("general.errors.player-has-no-island");
return false;
}
}
@Override
public boolean execute(User user, String label, List<String> args) {
// If args are not right, show help
if (args.size() != 2) {
showHelp(this, user);
return false;
}
// Get owner and target
UUID ownerUUID = Util.getUUID(args.get(0));
if (ownerUUID == null) {
user.sendMessage("general.errors.unknown-player", TextVariables.NAME, args.get(0));
return false;
}
UUID targetUUID = Util.getUUID(args.get(1));
if (targetUUID == null) {
user.sendMessage("general.errors.unknown-player", TextVariables.NAME, args.get(1));
return false;
}
if (!getIslands().hasIsland(getWorld(), ownerUUID)) {
user.sendMessage("general.errors.player-has-no-island");
return false;
}
Island island = getIslands().getPrimaryIsland(getWorld(), ownerUUID);
if (getIslands().inTeam(getWorld(), ownerUUID) && island != null && !ownerUUID.equals(island.getOwner())) {
user.sendMessage("commands.admin.team.add.name-not-owner", TextVariables.NAME, args.get(0));
new IslandInfo(island).showMembers(user);
return false;
}
if (getIslands().inTeam(getWorld(), targetUUID)) {
user.sendMessage("commands.island.team.invite.errors.already-on-team");
return false;
}
if (getIslands().hasIsland(getWorld(), targetUUID)) {
user.sendMessage("commands.admin.team.add.name-has-island", TextVariables.NAME, args.get(1));
return false;
}
// Success
User target = User.getInstance(targetUUID);
User owner = User.getInstance(ownerUUID);
owner.sendMessage("commands.island.team.invite.accept.name-joined-your-island", TextVariables.NAME,
getPlugin().getPlayers().getName(targetUUID));
target.sendMessage("commands.island.team.invite.accept.you-joined-island", TextVariables.LABEL, getTopLabel());
Island teamIsland = getIslands().getIsland(getWorld(), ownerUUID);
if (teamIsland != null) {
getIslands().setJoinTeam(teamIsland, targetUUID);
user.sendMessage("commands.admin.team.add.success", TextVariables.NAME, target.getName(), "[owner]",
owner.getName());
TeamEvent.builder().island(teamIsland).reason(TeamEvent.Reason.JOINED).involvedPlayer(targetUUID)
.admin(true).build();
IslandEvent.builder().island(teamIsland).involvedPlayer(targetUUID).admin(true)
.reason(IslandEvent.Reason.RANK_CHANGE)
.rankChange(teamIsland.getRank(target), RanksManager.MEMBER_RANK).build();
return true;
} else {
user.sendMessage("general.errors.player-has-no-island");
return false;
}
}
}

View File

@ -3,30 +3,23 @@
// Copyright - 2022
//
package world.bentobox.bentobox.api.commands.admin.team;
import java.util.List;
import world.bentobox.bentobox.api.commands.CompositeCommand;
import world.bentobox.bentobox.api.user.User;
/**
* Parent command for all Admin Team commands.
*/
public class AdminTeamCommand extends CompositeCommand
{
public AdminTeamCommand(CompositeCommand parent)
{
public class AdminTeamCommand extends CompositeCommand {
public AdminTeamCommand(CompositeCommand parent) {
super(parent, "team");
}
@Override
public void setup()
{
public void setup() {
this.setPermission("mod.team");
this.setDescription("commands.admin.team.description");
@ -37,10 +30,8 @@ public class AdminTeamCommand extends CompositeCommand
new AdminTeamSetownerCommand(this);
}
@Override
public boolean execute(User user, String label, List<String> args)
{
public boolean execute(User user, String label, List<String> args) {
this.showHelp(this, user);
return true;
}

View File

@ -14,58 +14,58 @@ import world.bentobox.bentobox.util.Util;
public class AdminTeamDisbandCommand extends CompositeCommand {
public AdminTeamDisbandCommand(CompositeCommand parent) {
super(parent, "disband");
}
public AdminTeamDisbandCommand(CompositeCommand parent) {
super(parent, "disband");
}
@Override
public void setup() {
setPermission("mod.team.disband");
setParametersHelp("commands.admin.team.disband.parameters");
setDescription("commands.admin.team.disband.description");
}
@Override
public void setup() {
setPermission("mod.team.disband");
setParametersHelp("commands.admin.team.disband.parameters");
setDescription("commands.admin.team.disband.description");
}
@Override
public boolean execute(User user, String label, List<String> args) {
// If args are not right, show help
if (args.size() != 1) {
showHelp(this, user);
return false;
}
// Get target
UUID targetUUID = Util.getUUID(args.get(0));
if (targetUUID == null) {
user.sendMessage("general.errors.unknown-player", TextVariables.NAME, args.get(0));
return false;
}
if (!getIslands().hasIsland(getWorld(), targetUUID)) {
user.sendMessage("general.errors.no-island");
return false;
}
if (!getIslands().inTeam(getWorld(), targetUUID)) {
user.sendMessage("general.errors.not-in-team");
return false;
}
Island island = getIslands().getPrimaryIsland(getWorld(), targetUUID);
if (!targetUUID.equals(island.getOwner())) {
user.sendMessage("commands.admin.team.disband.use-disband-owner", "[owner]",
getPlayers().getName(island.getOwner()));
return false;
}
// Disband team
island.getMemberSet().forEach(m -> {
User mUser = User.getInstance(m);
mUser.sendMessage("commands.admin.team.disband.disbanded");
// The owner gets to keep the island
if (!m.equals(targetUUID)) {
getIslands().removePlayer(island, m);
TeamEvent.builder().island(island).reason(TeamEvent.Reason.KICK).involvedPlayer(m).admin(true).build();
IslandEvent.builder().island(island).involvedPlayer(targetUUID).admin(true)
.reason(IslandEvent.Reason.RANK_CHANGE)
.rankChange(island.getRank(mUser), RanksManager.VISITOR_RANK).build();
}
});
user.sendMessage("commands.admin.team.disband.success", TextVariables.NAME, args.get(0));
return true;
}
@Override
public boolean execute(User user, String label, List<String> args) {
// If args are not right, show help
if (args.size() != 1) {
showHelp(this, user);
return false;
}
// Get target
UUID targetUUID = Util.getUUID(args.get(0));
if (targetUUID == null) {
user.sendMessage("general.errors.unknown-player", TextVariables.NAME, args.get(0));
return false;
}
if (!getIslands().hasIsland(getWorld(), targetUUID)) {
user.sendMessage("general.errors.no-island");
return false;
}
if (!getIslands().inTeam(getWorld(), targetUUID)) {
user.sendMessage("general.errors.not-in-team");
return false;
}
Island island = getIslands().getPrimaryIsland(getWorld(), targetUUID);
if (!targetUUID.equals(island.getOwner())) {
user.sendMessage("commands.admin.team.disband.use-disband-owner", "[owner]",
getPlayers().getName(island.getOwner()));
return false;
}
// Disband team
island.getMemberSet().forEach(m -> {
User mUser = User.getInstance(m);
mUser.sendMessage("commands.admin.team.disband.disbanded");
// The owner gets to keep the island
if (!m.equals(targetUUID)) {
getIslands().removePlayer(island, m);
TeamEvent.builder().island(island).reason(TeamEvent.Reason.KICK).involvedPlayer(m).admin(true).build();
IslandEvent.builder().island(island).involvedPlayer(targetUUID).admin(true)
.reason(IslandEvent.Reason.RANK_CHANGE)
.rankChange(island.getRank(mUser), RanksManager.VISITOR_RANK).build();
}
});
user.sendMessage("commands.admin.team.disband.success", TextVariables.NAME, args.get(0));
return true;
}
}

View File

@ -7,7 +7,6 @@ import world.bentobox.bentobox.api.user.User;
public class AdminTeamFixCommand extends CompositeCommand {
public AdminTeamFixCommand(CompositeCommand parent) {
super(parent, "fix");
}
@ -27,6 +26,7 @@ public class AdminTeamFixCommand extends CompositeCommand {
}
return true;
}
@Override
public boolean execute(User user, String label, List<String> args) {
getIslands().checkTeams(user, getWorld());

View File

@ -18,6 +18,7 @@ import world.bentobox.bentobox.util.Util;
/**
* Kicks the specified player from the island team.
*
* @author tastybento
*/
public class AdminTeamKickCommand extends CompositeCommand {
@ -72,22 +73,14 @@ public class AdminTeamKickCommand extends CompositeCommand {
target.sendMessage("commands.admin.team.kick.admin-kicked");
getIslands().removePlayer(getWorld(), targetUUID);
user.sendMessage("commands.admin.team.kick.success", TextVariables.NAME, target.getName(), "[owner]", getPlayers().getName(island.getOwner()));
user.sendMessage("commands.admin.team.kick.success", TextVariables.NAME, target.getName(), "[owner]",
getPlayers().getName(island.getOwner()));
// Fire event so add-ons know
TeamEvent.builder()
.island(island)
.reason(TeamEvent.Reason.KICK)
.involvedPlayer(targetUUID)
.admin(true)
.build();
IslandEvent.builder()
.island(island)
.involvedPlayer(targetUUID)
.admin(true)
.reason(IslandEvent.Reason.RANK_CHANGE)
.rankChange(island.getRank(target), RanksManager.VISITOR_RANK)
.build();
TeamEvent.builder().island(island).reason(TeamEvent.Reason.KICK).involvedPlayer(targetUUID).admin(true).build();
IslandEvent.builder().island(island).involvedPlayer(targetUUID).admin(true)
.reason(IslandEvent.Reason.RANK_CHANGE).rankChange(island.getRank(target), RanksManager.VISITOR_RANK)
.build();
return true;
}
}

View File

@ -19,67 +19,67 @@ import world.bentobox.bentobox.util.Util;
*/
public class AdminTeamSetownerCommand extends CompositeCommand {
public AdminTeamSetownerCommand(CompositeCommand parent) {
super(parent, "setowner");
}
public AdminTeamSetownerCommand(CompositeCommand parent) {
super(parent, "setowner");
}
@Override
public void setup() {
setPermission("mod.team.setowner");
setParametersHelp("commands.admin.team.setowner.parameters");
setDescription("commands.admin.team.setowner.description");
}
@Override
public void setup() {
setPermission("mod.team.setowner");
setParametersHelp("commands.admin.team.setowner.parameters");
setDescription("commands.admin.team.setowner.description");
}
@Override
public boolean execute(User user, String label, List<String> args) {
// If args are not right, show help
if (args.size() != 1) {
showHelp(this, user);
return false;
}
// Get target
UUID targetUUID = Util.getUUID(args.get(0));
if (targetUUID == null) {
user.sendMessage("general.errors.unknown-player", TextVariables.NAME, args.get(0));
return false;
}
if (!getIslands().inTeam(getWorld(), targetUUID)) {
user.sendMessage("general.errors.not-in-team");
return false;
}
Island island = getIslands().getPrimaryIsland(getWorld(), targetUUID);
UUID previousOwnerUUID = island.getOwner();
if (targetUUID.equals(previousOwnerUUID)) {
user.sendMessage("commands.admin.team.setowner.already-owner", TextVariables.NAME, args.get(0));
return false;
}
@Override
public boolean execute(User user, String label, List<String> args) {
// If args are not right, show help
if (args.size() != 1) {
showHelp(this, user);
return false;
}
// Get target
UUID targetUUID = Util.getUUID(args.get(0));
if (targetUUID == null) {
user.sendMessage("general.errors.unknown-player", TextVariables.NAME, args.get(0));
return false;
}
if (!getIslands().inTeam(getWorld(), targetUUID)) {
user.sendMessage("general.errors.not-in-team");
return false;
}
Island island = getIslands().getPrimaryIsland(getWorld(), targetUUID);
UUID previousOwnerUUID = island.getOwner();
if (targetUUID.equals(previousOwnerUUID)) {
user.sendMessage("commands.admin.team.setowner.already-owner", TextVariables.NAME, args.get(0));
return false;
}
// Get the User corresponding to the current owner
User target = User.getInstance(targetUUID);
// Get the User corresponding to the current owner
User target = User.getInstance(targetUUID);
// Fire event so add-ons know
// Call the setowner event
TeamEvent.builder().island(island).reason(TeamEvent.Reason.SETOWNER).involvedPlayer(targetUUID).admin(true)
.build();
// Fire event so add-ons know
// Call the setowner event
TeamEvent.builder().island(island).reason(TeamEvent.Reason.SETOWNER).involvedPlayer(targetUUID).admin(true)
.build();
// Call the rank change event for the new island owner
// We need to call it BEFORE the actual change, in order to retain the player's
// previous rank.
IslandEvent.builder().island(island).involvedPlayer(targetUUID).admin(true)
.reason(IslandEvent.Reason.RANK_CHANGE).rankChange(island.getRank(target), RanksManager.OWNER_RANK)
.build();
// Call the rank change event for the new island owner
// We need to call it BEFORE the actual change, in order to retain the player's
// previous rank.
IslandEvent.builder().island(island).involvedPlayer(targetUUID).admin(true)
.reason(IslandEvent.Reason.RANK_CHANGE).rankChange(island.getRank(target), RanksManager.OWNER_RANK)
.build();
// Make new owner
getIslands().setOwner(getWorld(), user, targetUUID);
user.sendMessage("commands.admin.team.setowner.success", TextVariables.NAME, args.get(0));
// Make new owner
getIslands().setOwner(getWorld(), user, targetUUID);
user.sendMessage("commands.admin.team.setowner.success", TextVariables.NAME, args.get(0));
// Call the rank change event for the old island owner
if (previousOwnerUUID != null) {
// We need to call it AFTER the actual change.
IslandEvent.builder().island(island).involvedPlayer(previousOwnerUUID).admin(true)
.reason(IslandEvent.Reason.RANK_CHANGE)
.rankChange(RanksManager.OWNER_RANK, island.getRank(previousOwnerUUID)).build();
}
return true;
}
// Call the rank change event for the old island owner
if (previousOwnerUUID != null) {
// We need to call it AFTER the actual change.
IslandEvent.builder().island(island).involvedPlayer(previousOwnerUUID).admin(true)
.reason(IslandEvent.Reason.RANK_CHANGE)
.rankChange(RanksManager.OWNER_RANK, island.getRank(previousOwnerUUID)).build();
}
return true;
}
}

View File

@ -10,7 +10,9 @@ import world.bentobox.bentobox.api.localization.TextVariables;
import world.bentobox.bentobox.api.user.User;
/**
* This is default player command class. It contains all necessary parts for main /[gamemode] command.
* This is default player command class. It contains all necessary parts for
* main /[gamemode] command.
*
* @since 1.13.0
* @author BONNe
*/
@ -19,18 +21,18 @@ public abstract class DefaultPlayerCommand extends CompositeCommand {
/**
* This is the top-level command constructor for commands that have no parent.
*
* @param addon - GameMode addon
* @param addon - GameMode addon
*/
protected DefaultPlayerCommand(GameModeAddon addon) {
// Register command with alias from config.
// The first command listed is the "label" and the others are aliases.
super(addon,
addon.getWorldSettings().getPlayerCommandAliases().split(" ")[0],
super(addon, addon.getWorldSettings().getPlayerCommandAliases().split(" ")[0],
addon.getWorldSettings().getPlayerCommandAliases().split(" "));
}
/**
* Setups anything that is necessary for default main user command.
*
* @see world.bentobox.bentobox.api.commands.BentoBoxCommand#setup()
*/
@Override
@ -82,10 +84,11 @@ public abstract class DefaultPlayerCommand extends CompositeCommand {
new IslandHomesCommand(this);
}
/**
* Defines what will be executed when this command is run.
* @see world.bentobox.bentobox.api.commands.BentoBoxCommand#execute(User, String, List)
*
* @see world.bentobox.bentobox.api.commands.BentoBoxCommand#execute(User,
* String, List)
*/
@Override
public boolean execute(User user, String label, List<String> args) {
@ -101,10 +104,12 @@ public abstract class DefaultPlayerCommand extends CompositeCommand {
// Check if user has an island.
if (this.getIslands().getIsland(this.getWorld(), user.getUniqueId()) != null) {
// Default command if user has an island.
return runCommand(user, label, this.<GameModeAddon>getAddon().getWorldSettings().getDefaultPlayerAction(), "go");
return runCommand(user, label, this.<GameModeAddon>getAddon().getWorldSettings().getDefaultPlayerAction(),
"go");
} else {
// Default command if user does not have an island.
return runCommand(user, label, this.<GameModeAddon>getAddon().getWorldSettings().getDefaultNewPlayerAction(), "create");
return runCommand(user, label,
this.<GameModeAddon>getAddon().getWorldSettings().getDefaultNewPlayerAction(), "create");
}
}
@ -114,11 +119,11 @@ public abstract class DefaultPlayerCommand extends CompositeCommand {
}
// Call sub command or perform command if it does not exist
if (this.getSubCommand(command).isPresent()) {
return this.getSubCommand(command).
map(c -> c.call(user, c.getLabel(), Collections.emptyList())).
orElse(false);
return this.getSubCommand(command).map(c -> c.call(user, c.getLabel(), Collections.emptyList()))
.orElse(false);
} else {
// Command is not a known sub command - try to perform it directly - some plugins trap these commands, like Deluxe menus
// Command is not a known sub command - try to perform it directly - some
// plugins trap these commands, like Deluxe menus
if (command.startsWith("/")) {
// If commands starts with Slash, don't append the prefix
return user.performCommand(command.substring(1));

View File

@ -21,132 +21,132 @@ import world.bentobox.bentobox.util.Util;
public class IslandBanCommand extends CompositeCommand {
private @Nullable User target;
private @Nullable User target;
public IslandBanCommand(CompositeCommand islandCommand) {
super(islandCommand, "ban");
}
public IslandBanCommand(CompositeCommand islandCommand) {
super(islandCommand, "ban");
}
@Override
public void setup() {
setPermission("island.ban");
setOnlyPlayer(true);
setParametersHelp("commands.island.ban.parameters");
setDescription("commands.island.ban.description");
setConfigurableRankCommand();
}
@Override
public void setup() {
setPermission("island.ban");
setOnlyPlayer(true);
setParametersHelp("commands.island.ban.parameters");
setDescription("commands.island.ban.description");
setConfigurableRankCommand();
}
@Override
public boolean canExecute(User user, String label, List<String> args) {
if (args.size() != 1) {
// Show help
showHelp(this, user);
return false;
}
UUID playerUUID = user.getUniqueId();
// Player issuing the command must have an island or be in a team
if (!getIslands().inTeam(getWorld(), user.getUniqueId())
&& !getIslands().hasIsland(getWorld(), user.getUniqueId())) {
user.sendMessage("general.errors.no-island");
return false;
}
// Check rank to use command
Island island = Objects.requireNonNull(getIslands().getIsland(getWorld(), user));
int rank = island.getRank(user);
if (rank < island.getRankCommand(getUsage())) {
user.sendMessage("general.errors.insufficient-rank", TextVariables.RANK,
user.getTranslation(getPlugin().getRanksManager().getRank(rank)));
return false;
}
// Get target player
UUID targetUUID = getPlayers().getUUID(args.get(0));
if (targetUUID == null) {
user.sendMessage("general.errors.unknown-player", TextVariables.NAME, args.get(0));
return false;
}
// Player cannot ban themselves
if (playerUUID.equals(targetUUID)) {
user.sendMessage("commands.island.ban.cannot-ban-yourself");
return false;
}
if (getIslands().getPrimaryIsland(getWorld(), user.getUniqueId()).getMemberSet().contains(targetUUID)) {
user.sendMessage("commands.island.ban.cannot-ban-member");
return false;
}
if (island.isBanned(targetUUID)) {
user.sendMessage("commands.island.ban.player-already-banned");
return false;
}
if (getSettings().getBanCooldown() > 0 && checkCooldown(user, island.getUniqueId(), targetUUID.toString())) {
return false;
}
target = User.getInstance(targetUUID);
// Cannot ban ops
if (target.isOp() || (target.isOnline() && target.hasPermission(this.getPermissionPrefix() + "admin.noban"))) {
user.sendMessage("commands.island.ban.cannot-ban");
return false;
}
return true;
}
@Override
public boolean canExecute(User user, String label, List<String> args) {
if (args.size() != 1) {
// Show help
showHelp(this, user);
return false;
}
UUID playerUUID = user.getUniqueId();
// Player issuing the command must have an island or be in a team
if (!getIslands().inTeam(getWorld(), user.getUniqueId())
&& !getIslands().hasIsland(getWorld(), user.getUniqueId())) {
user.sendMessage("general.errors.no-island");
return false;
}
// Check rank to use command
Island island = Objects.requireNonNull(getIslands().getIsland(getWorld(), user));
int rank = island.getRank(user);
if (rank < island.getRankCommand(getUsage())) {
user.sendMessage("general.errors.insufficient-rank", TextVariables.RANK,
user.getTranslation(getPlugin().getRanksManager().getRank(rank)));
return false;
}
// Get target player
UUID targetUUID = getPlayers().getUUID(args.get(0));
if (targetUUID == null) {
user.sendMessage("general.errors.unknown-player", TextVariables.NAME, args.get(0));
return false;
}
// Player cannot ban themselves
if (playerUUID.equals(targetUUID)) {
user.sendMessage("commands.island.ban.cannot-ban-yourself");
return false;
}
if (getIslands().getPrimaryIsland(getWorld(), user.getUniqueId()).getMemberSet().contains(targetUUID)) {
user.sendMessage("commands.island.ban.cannot-ban-member");
return false;
}
if (island.isBanned(targetUUID)) {
user.sendMessage("commands.island.ban.player-already-banned");
return false;
}
if (getSettings().getBanCooldown() > 0 && checkCooldown(user, island.getUniqueId(), targetUUID.toString())) {
return false;
}
target = User.getInstance(targetUUID);
// Cannot ban ops
if (target.isOp() || (target.isOnline() && target.hasPermission(this.getPermissionPrefix() + "admin.noban"))) {
user.sendMessage("commands.island.ban.cannot-ban");
return false;
}
return true;
}
@Override
public boolean execute(User user, String label, List<String> args) {
// Finished error checking - start the banning
return ban(user, target);
}
@Override
public boolean execute(User user, String label, List<String> args) {
// Finished error checking - start the banning
return ban(user, target);
}
private boolean ban(@NonNull User issuer, User target) {
Island island = Objects.requireNonNull(getIslands().getIsland(getWorld(), issuer.getUniqueId()));
private boolean ban(@NonNull User issuer, User target) {
Island island = Objects.requireNonNull(getIslands().getIsland(getWorld(), issuer.getUniqueId()));
// Check if player can ban any more players
int banLimit = issuer.getPermissionValue(getPermissionPrefix() + "ban.maxlimit",
getIWM().getBanLimit(getWorld()));
if (banLimit <= -1 || island.getBanned().size() < banLimit) {
// Run the event
IslandBaseEvent banEvent = IslandEvent.builder().island(island).involvedPlayer(target.getUniqueId())
.admin(false).reason(IslandEvent.Reason.BAN).build();
if (banEvent.getNewEvent().map(IslandBaseEvent::isCancelled).orElse(banEvent.isCancelled())) {
// Banning was blocked due to an event cancellation. Fail silently.
return false;
}
// Event is not cancelled
if (island.ban(issuer.getUniqueId(), target.getUniqueId())) {
issuer.sendMessage("commands.island.ban.player-banned", TextVariables.NAME, target.getName(),
TextVariables.DISPLAY_NAME, target.getDisplayName());
target.sendMessage("commands.island.ban.owner-banned-you", TextVariables.NAME, issuer.getName(),
TextVariables.DISPLAY_NAME, issuer.getDisplayName());
// If the player is online, has an island and on the banned island, move them
// home immediately
if (target.isOnline() && getIslands().hasIsland(getWorld(), target.getUniqueId())
&& island.onIsland(target.getLocation())) {
getIslands().homeTeleportAsync(getWorld(), target.getPlayer());
island.getWorld().playSound(target.getLocation(), Sound.ENTITY_GENERIC_EXPLODE, 1F, 1F);
}
return true;
}
} else {
issuer.sendMessage("commands.island.ban.cannot-ban-more-players");
}
// Fail silently.
return false;
}
// Check if player can ban any more players
int banLimit = issuer.getPermissionValue(getPermissionPrefix() + "ban.maxlimit",
getIWM().getBanLimit(getWorld()));
if (banLimit <= -1 || island.getBanned().size() < banLimit) {
// Run the event
IslandBaseEvent banEvent = IslandEvent.builder().island(island).involvedPlayer(target.getUniqueId())
.admin(false).reason(IslandEvent.Reason.BAN).build();
if (banEvent.getNewEvent().map(IslandBaseEvent::isCancelled).orElse(banEvent.isCancelled())) {
// Banning was blocked due to an event cancellation. Fail silently.
return false;
}
// Event is not cancelled
if (island.ban(issuer.getUniqueId(), target.getUniqueId())) {
issuer.sendMessage("commands.island.ban.player-banned", TextVariables.NAME, target.getName(),
TextVariables.DISPLAY_NAME, target.getDisplayName());
target.sendMessage("commands.island.ban.owner-banned-you", TextVariables.NAME, issuer.getName(),
TextVariables.DISPLAY_NAME, issuer.getDisplayName());
// If the player is online, has an island and on the banned island, move them
// home immediately
if (target.isOnline() && getIslands().hasIsland(getWorld(), target.getUniqueId())
&& island.onIsland(target.getLocation())) {
getIslands().homeTeleportAsync(getWorld(), target.getPlayer());
island.getWorld().playSound(target.getLocation(), Sound.ENTITY_GENERIC_EXPLODE, 1F, 1F);
}
return true;
}
} else {
issuer.sendMessage("commands.island.ban.cannot-ban-more-players");
}
// Fail silently.
return false;
}
@Override
public Optional<List<String>> tabComplete(User user, String alias, List<String> args) {
String lastArg = !args.isEmpty() ? args.get(args.size() - 1) : "";
if (lastArg.isEmpty()) {
// Don't show every player on the server. Require at least the first letter
return Optional.empty();
}
Island island = getIslands().getIsland(getWorld(), user.getUniqueId());
if (island != null) {
List<String> options = Bukkit.getOnlinePlayers().stream()
.filter(p -> !p.getUniqueId().equals(user.getUniqueId()))
.filter(p -> !island.isBanned(p.getUniqueId())).filter(p -> user.getPlayer().canSee(p))
.map(Player::getName).toList();
return Optional.of(Util.tabLimit(options, lastArg));
} else {
return Optional.empty();
}
}
@Override
public Optional<List<String>> tabComplete(User user, String alias, List<String> args) {
String lastArg = !args.isEmpty() ? args.get(args.size() - 1) : "";
if (lastArg.isEmpty()) {
// Don't show every player on the server. Require at least the first letter
return Optional.empty();
}
Island island = getIslands().getIsland(getWorld(), user.getUniqueId());
if (island != null) {
List<String> options = Bukkit.getOnlinePlayers().stream()
.filter(p -> !p.getUniqueId().equals(user.getUniqueId()))
.filter(p -> !island.isBanned(p.getUniqueId())).filter(p -> user.getPlayer().canSee(p))
.map(Player::getName).toList();
return Optional.of(Util.tabLimit(options, lastArg));
} else {
return Optional.empty();
}
}
}

View File

@ -32,7 +32,8 @@ public class IslandBanlistCommand extends CompositeCommand {
return false;
}
// Player issuing the command must have an island
if (!getIslands().hasIsland(getWorld(), user.getUniqueId()) && !getIslands().inTeam(getWorld(), user.getUniqueId())) {
if (!getIslands().hasIsland(getWorld(), user.getUniqueId())
&& !getIslands().inTeam(getWorld(), user.getUniqueId())) {
user.sendMessage("general.errors.no-island");
return false;
}
@ -40,7 +41,8 @@ public class IslandBanlistCommand extends CompositeCommand {
island = getIslands().getIsland(getWorld(), user.getUniqueId());
int rank = Objects.requireNonNull(island).getRank(user);
if (rank < island.getRankCommand(getUsage())) {
user.sendMessage("general.errors.insufficient-rank", TextVariables.RANK, user.getTranslation(getPlugin().getRanksManager().getRank(rank)));
user.sendMessage("general.errors.insufficient-rank", TextVariables.RANK,
user.getTranslation(getPlugin().getRanksManager().getRank(rank)));
return false;
}
return true;
@ -59,7 +61,8 @@ public class IslandBanlistCommand extends CompositeCommand {
List<String> names = island.getBanned().stream().map(u -> getPlayers().getName(u)).sorted().toList();
List<String> lines = new ArrayList<>();
StringBuilder line = new StringBuilder();
// Put the names into lines of no more than 40 characters long, separated by commas
// Put the names into lines of no more than 40 characters long, separated by
// commas
names.forEach(n -> {
if (line.length() + n.length() >= 41) {
lines.add(line.toString().trim());
@ -77,9 +80,11 @@ public class IslandBanlistCommand extends CompositeCommand {
// Send the strings
lines.forEach(l -> user.sendMessage("commands.island.banlist.names", "[line]", l));
int banLimit = user.getPermissionValue(getPermissionPrefix() + "ban.maxlimit", getIWM().getBanLimit(getWorld()));
int banLimit = user.getPermissionValue(getPermissionPrefix() + "ban.maxlimit",
getIWM().getBanLimit(getWorld()));
if (banLimit > -1 && island.getBanned().size() < banLimit) {
user.sendMessage("commands.island.banlist.you-can-ban", TextVariables.NUMBER, String.valueOf(banLimit - island.getBanned().size()));
user.sendMessage("commands.island.banlist.you-can-ban", TextVariables.NUMBER,
String.valueOf(banLimit - island.getBanned().size()));
}
return true;
}

View File

@ -22,99 +22,99 @@ import world.bentobox.bentobox.util.Util;
*/
public class IslandCreateCommand extends CompositeCommand {
/**
* Command to create an island
*
* @param islandCommand - parent command
*/
public IslandCreateCommand(CompositeCommand islandCommand) {
super(islandCommand, "create", "new");
}
/**
* Command to create an island
*
* @param islandCommand - parent command
*/
public IslandCreateCommand(CompositeCommand islandCommand) {
super(islandCommand, "create", "new");
}
@Override
public void setup() {
setPermission("island.create");
setOnlyPlayer(true);
setParametersHelp("commands.island.create.parameters");
setDescription("commands.island.create.description");
}
@Override
public void setup() {
setPermission("island.create");
setOnlyPlayer(true);
setParametersHelp("commands.island.create.parameters");
setDescription("commands.island.create.description");
}
@Override
public boolean canExecute(User user, String label, List<String> args) {
// Check if the island is reserved
@Nullable
Island island = getIslands().getPrimaryIsland(getWorld(), user.getUniqueId());
if (island != null) {
// Reserved islands can be made
if (island.isReserved()) {
return true;
}
}
// Check if this player is on a team in this world
if (getIslands().inTeam(getWorld(), user.getUniqueId()) && island != null
&& !user.getUniqueId().equals(island.getOwner())) {
// Team members who are not owners cannot make additional islands
user.sendMessage("commands.island.create.you-cannot-make-team");
return false;
}
// Get how many islands this player has
int num = this.getIslands().getNumberOfConcurrentIslands(user.getUniqueId(), getWorld());
int max = user.getPermissionValue(
this.getIWM().getAddon(getWorld()).map(GameModeAddon::getPermissionPrefix).orElse("") + "island.number",
this.getIWM().getWorldSettings(getWorld()).getConcurrentIslands());
if (num >= max) {
// You cannot make an island
user.sendMessage("commands.island.create.you-cannot-make");
return false;
}
if (getIWM().getMaxIslands(getWorld()) > 0
&& getIslands().getIslandCount(getWorld()) >= getIWM().getMaxIslands(getWorld())) {
// There is too many islands in the world :(
user.sendMessage("commands.island.create.too-many-islands");
return false;
}
return true;
}
@Override
public boolean canExecute(User user, String label, List<String> args) {
// Check if the island is reserved
@Nullable
Island island = getIslands().getPrimaryIsland(getWorld(), user.getUniqueId());
if (island != null) {
// Reserved islands can be made
if (island.isReserved()) {
return true;
}
}
// Check if this player is on a team in this world
if (getIslands().inTeam(getWorld(), user.getUniqueId()) && island != null
&& !user.getUniqueId().equals(island.getOwner())) {
// Team members who are not owners cannot make additional islands
user.sendMessage("commands.island.create.you-cannot-make-team");
return false;
}
// Get how many islands this player has
int num = this.getIslands().getNumberOfConcurrentIslands(user.getUniqueId(), getWorld());
int max = user.getPermissionValue(
this.getIWM().getAddon(getWorld()).map(GameModeAddon::getPermissionPrefix).orElse("") + "island.number",
this.getIWM().getWorldSettings(getWorld()).getConcurrentIslands());
if (num >= max) {
// You cannot make an island
user.sendMessage("commands.island.create.you-cannot-make");
return false;
}
if (getIWM().getMaxIslands(getWorld()) > 0
&& getIslands().getIslandCount(getWorld()) >= getIWM().getMaxIslands(getWorld())) {
// There is too many islands in the world :(
user.sendMessage("commands.island.create.too-many-islands");
return false;
}
return true;
}
@Override
public boolean execute(User user, String label, List<String> args) {
// Permission check if the name is not the default one
if (!args.isEmpty()) {
String name = getPlugin().getBlueprintsManager().validate(getAddon(), Util.sanitizeInput(args.get(0)));
if (name == null) {
// The blueprint name is not valid.
user.sendMessage("commands.island.create.unknown-blueprint");
return false;
}
if (!getPlugin().getBlueprintsManager().checkPerm(getAddon(), user, Util.sanitizeInput(args.get(0)))) {
return false;
}
// Make island
return makeIsland(user, name);
} else {
// Show panel only if there are multiple bundles available
if (getPlugin().getBlueprintsManager().getBlueprintBundles(getAddon()).size() > 1) {
// Show panel
IslandCreationPanel.openPanel(this, user, label);
return true;
}
return makeIsland(user, BlueprintsManager.DEFAULT_BUNDLE_NAME);
}
}
@Override
public boolean execute(User user, String label, List<String> args) {
// Permission check if the name is not the default one
if (!args.isEmpty()) {
String name = getPlugin().getBlueprintsManager().validate(getAddon(), Util.sanitizeInput(args.get(0)));
if (name == null) {
// The blueprint name is not valid.
user.sendMessage("commands.island.create.unknown-blueprint");
return false;
}
if (!getPlugin().getBlueprintsManager().checkPerm(getAddon(), user, Util.sanitizeInput(args.get(0)))) {
return false;
}
// Make island
return makeIsland(user, name);
} else {
// Show panel only if there are multiple bundles available
if (getPlugin().getBlueprintsManager().getBlueprintBundles(getAddon()).size() > 1) {
// Show panel
IslandCreationPanel.openPanel(this, user, label);
return true;
}
return makeIsland(user, BlueprintsManager.DEFAULT_BUNDLE_NAME);
}
}
private boolean makeIsland(User user, String name) {
user.sendMessage("commands.island.create.creating-island");
try {
NewIsland.builder().player(user).addon(getAddon()).reason(Reason.CREATE).name(name).build();
} catch (IOException e) {
getPlugin().logError("Could not create island for player. " + e.getMessage());
user.sendMessage(e.getMessage());
return false;
}
if (getSettings().isResetCooldownOnCreate()) {
getParent().getSubCommand("reset").ifPresent(
resetCommand -> resetCommand.setCooldown(user.getUniqueId(), getSettings().getResetCooldown()));
}
return true;
}
private boolean makeIsland(User user, String name) {
user.sendMessage("commands.island.create.creating-island");
try {
NewIsland.builder().player(user).addon(getAddon()).reason(Reason.CREATE).name(name).build();
} catch (IOException e) {
getPlugin().logError("Could not create island for player. " + e.getMessage());
user.sendMessage(e.getMessage());
return false;
}
if (getSettings().isResetCooldownOnCreate()) {
getParent().getSubCommand("reset").ifPresent(
resetCommand -> resetCommand.setCooldown(user.getUniqueId(), getSettings().getResetCooldown()));
}
return true;
}
}

View File

@ -17,6 +17,7 @@ import world.bentobox.bentobox.util.Util;
/**
* Deletes a home
*
* @author tastybento
*
*/
@ -24,6 +25,7 @@ public class IslandDeletehomeCommand extends ConfirmableCommand {
/**
* Deletes a home
*
* @param islandCommand parent command
*/
public IslandDeletehomeCommand(CompositeCommand islandCommand) {
@ -56,8 +58,8 @@ public class IslandDeletehomeCommand extends ConfirmableCommand {
// check command ranks
int rank = Objects.requireNonNull(island).getRank(user);
if (rank < island.getRankCommand(getUsage())) {
user.sendMessage("general.errors.insufficient-rank",
TextVariables.RANK, user.getTranslation(getPlugin().getRanksManager().getRank(rank)));
user.sendMessage("general.errors.insufficient-rank", TextVariables.RANK,
user.getTranslation(getPlugin().getRanksManager().getRank(rank)));
return false;
}
@ -72,14 +74,14 @@ public class IslandDeletehomeCommand extends ConfirmableCommand {
if (!map.containsKey(name)) {
user.sendMessage("commands.island.go.unknown-home");
user.sendMessage("commands.island.sethome.homes-are");
map.keySet().stream().filter(s -> !s.isEmpty()).forEach(s -> user.sendMessage("commands.island.sethome.home-list-syntax", TextVariables.NAME, s));
map.keySet().stream().filter(s -> !s.isEmpty())
.forEach(s -> user.sendMessage("commands.island.sethome.home-list-syntax", TextVariables.NAME, s));
return false;
}
this.askConfirmation(user, () -> delete(map.get(name), user, name));
return true;
}
private void delete(Island island, User user, String name) {
island.removeHome(name);
user.sendMessage("general.success");
@ -87,7 +89,7 @@ public class IslandDeletehomeCommand extends ConfirmableCommand {
@Override
public Optional<List<String>> tabComplete(User user, String alias, List<String> args) {
String lastArg = !args.isEmpty() ? args.get(args.size()-1) : "";
String lastArg = !args.isEmpty() ? args.get(args.size() - 1) : "";
return Optional.of(Util.tabLimit(new ArrayList<>(getNameIslandMap(user).keySet()), lastArg));

View File

@ -24,139 +24,139 @@ import world.bentobox.bentobox.util.Util;
*/
public class IslandExpelCommand extends CompositeCommand {
private static final String CANNOT_EXPEL = "commands.island.expel.cannot-expel";
private static final String SUCCESS = "commands.island.expel.success";
private static final String CANNOT_EXPEL = "commands.island.expel.cannot-expel";
private static final String SUCCESS = "commands.island.expel.success";
private @Nullable User target;
private @Nullable User target;
public IslandExpelCommand(CompositeCommand islandCommand) {
super(islandCommand, "expel");
}
public IslandExpelCommand(CompositeCommand islandCommand) {
super(islandCommand, "expel");
}
@Override
public void setup() {
setOnlyPlayer(true);
setPermission("island.expel");
setParametersHelp("commands.island.expel.parameters");
setDescription("commands.island.expel.description");
setConfigurableRankCommand();
}
@Override
public void setup() {
setOnlyPlayer(true);
setPermission("island.expel");
setParametersHelp("commands.island.expel.parameters");
setDescription("commands.island.expel.description");
setConfigurableRankCommand();
}
@Override
public boolean canExecute(User user, String label, List<String> args) {
if (args.size() != 1) {
// Show help
showHelp(this, user);
return false;
}
UUID playerUUID = user.getUniqueId();
// Player issuing the command must have an island or be in a team
if (!getIslands().inTeam(getWorld(), user.getUniqueId()) && !getIslands().hasIsland(getWorld(), user)) {
user.sendMessage("general.errors.no-island");
return false;
}
// Check rank to use command
Island island = getIslands().getIsland(getWorld(), user);
int rank = Objects.requireNonNull(island).getRank(user);
if (rank < island.getRankCommand(getUsage())) {
user.sendMessage("general.errors.insufficient-rank", TextVariables.RANK,
user.getTranslation(getPlugin().getRanksManager().getRank(rank)));
return false;
}
// Get target player
UUID targetUUID = getPlayers().getUUID(args.get(0));
if (targetUUID == null) {
user.sendMessage("general.errors.unknown-player", TextVariables.NAME, args.get(0));
return false;
}
// Player cannot expel themselves
if (playerUUID.equals(targetUUID)) {
user.sendMessage("commands.island.expel.cannot-expel-yourself");
return false;
}
// Or team member
if (island.getMemberSet().contains(targetUUID)) {
user.sendMessage("commands.island.expel.cannot-expel-member");
return false;
}
// Cannot expel offline players or invisible players
target = User.getInstance(targetUUID);
if (!target.isOnline() || !user.getPlayer().canSee(Bukkit.getPlayer(targetUUID))) {
user.sendMessage("general.errors.offline-player");
return false;
}
// Not on island
if (!getIslands().locationIsOnIsland(user.getPlayer(), target.getLocation())) {
user.sendMessage("commands.island.expel.not-on-island");
return false;
}
// Cannot ban ops
if (target.isOp() || target.hasPermission(this.getPermissionPrefix() + "admin.noexpel")
|| target.hasPermission(this.getPermissionPrefix() + "mod.bypassexpel")) {
user.sendMessage(CANNOT_EXPEL);
return false;
}
return true;
}
@Override
public boolean canExecute(User user, String label, List<String> args) {
if (args.size() != 1) {
// Show help
showHelp(this, user);
return false;
}
UUID playerUUID = user.getUniqueId();
// Player issuing the command must have an island or be in a team
if (!getIslands().inTeam(getWorld(), user.getUniqueId()) && !getIslands().hasIsland(getWorld(), user)) {
user.sendMessage("general.errors.no-island");
return false;
}
// Check rank to use command
Island island = getIslands().getIsland(getWorld(), user);
int rank = Objects.requireNonNull(island).getRank(user);
if (rank < island.getRankCommand(getUsage())) {
user.sendMessage("general.errors.insufficient-rank", TextVariables.RANK,
user.getTranslation(getPlugin().getRanksManager().getRank(rank)));
return false;
}
// Get target player
UUID targetUUID = getPlayers().getUUID(args.get(0));
if (targetUUID == null) {
user.sendMessage("general.errors.unknown-player", TextVariables.NAME, args.get(0));
return false;
}
// Player cannot expel themselves
if (playerUUID.equals(targetUUID)) {
user.sendMessage("commands.island.expel.cannot-expel-yourself");
return false;
}
// Or team member
if (island.getMemberSet().contains(targetUUID)) {
user.sendMessage("commands.island.expel.cannot-expel-member");
return false;
}
// Cannot expel offline players or invisible players
target = User.getInstance(targetUUID);
if (!target.isOnline() || !user.getPlayer().canSee(Bukkit.getPlayer(targetUUID))) {
user.sendMessage("general.errors.offline-player");
return false;
}
// Not on island
if (!getIslands().locationIsOnIsland(user.getPlayer(), target.getLocation())) {
user.sendMessage("commands.island.expel.not-on-island");
return false;
}
// Cannot ban ops
if (target.isOp() || target.hasPermission(this.getPermissionPrefix() + "admin.noexpel")
|| target.hasPermission(this.getPermissionPrefix() + "mod.bypassexpel")) {
user.sendMessage(CANNOT_EXPEL);
return false;
}
return true;
}
@Override
public boolean execute(User user, String label, List<String> args) {
// Finished error checking - expel player
Island island = getIslands().getIsland(getWorld(), user);
// Fire event
IslandBaseEvent expelEvent = IslandEvent.builder().island(island).involvedPlayer(target.getUniqueId())
.admin(false).reason(IslandEvent.Reason.EXPEL).build();
if (expelEvent.getNewEvent().map(IslandBaseEvent::isCancelled).orElse(expelEvent.isCancelled())) {
user.sendMessage(CANNOT_EXPEL);
return false;
}
@Override
public boolean execute(User user, String label, List<String> args) {
// Finished error checking - expel player
Island island = getIslands().getIsland(getWorld(), user);
// Fire event
IslandBaseEvent expelEvent = IslandEvent.builder().island(island).involvedPlayer(target.getUniqueId())
.admin(false).reason(IslandEvent.Reason.EXPEL).build();
if (expelEvent.getNewEvent().map(IslandBaseEvent::isCancelled).orElse(expelEvent.isCancelled())) {
user.sendMessage(CANNOT_EXPEL);
return false;
}
target.sendMessage("commands.island.expel.player-expelled-you", TextVariables.NAME, user.getName(),
TextVariables.DISPLAY_NAME, user.getDisplayName());
island.getWorld().playSound(target.getLocation(), Sound.ENTITY_GENERIC_EXPLODE, 1F, 1F);
if (getIslands().hasIsland(getWorld(), target) || getIslands().inTeam(getWorld(), target.getUniqueId())) {
// Success
user.sendMessage(SUCCESS, TextVariables.NAME, target.getName(), TextVariables.DISPLAY_NAME,
target.getDisplayName());
// Teleport home
getIslands().homeTeleportAsync(getWorld(), target.getPlayer());
return true;
} else if (getIslands().getSpawn(getWorld()).isPresent()) {
// Success
user.sendMessage(SUCCESS, TextVariables.NAME, target.getName(), TextVariables.DISPLAY_NAME,
target.getDisplayName());
getIslands().spawnTeleport(getWorld(), target.getPlayer());
return true;
} else if (getIWM().getAddon(getWorld())
.map(gm -> gm.getPlayerCommand().map(pc -> pc.getSubCommand("create").isPresent()).orElse(false))
.orElse(false) && target.performCommand(this.getTopLabel() + " create")) {
getAddon().logWarning("Expel: " + target.getName() + " had no island, so one was created");
user.sendMessage(SUCCESS, TextVariables.NAME, target.getName(), TextVariables.DISPLAY_NAME,
target.getDisplayName());
return true;
}
target.sendMessage("commands.island.expel.player-expelled-you", TextVariables.NAME, user.getName(),
TextVariables.DISPLAY_NAME, user.getDisplayName());
island.getWorld().playSound(target.getLocation(), Sound.ENTITY_GENERIC_EXPLODE, 1F, 1F);
if (getIslands().hasIsland(getWorld(), target) || getIslands().inTeam(getWorld(), target.getUniqueId())) {
// Success
user.sendMessage(SUCCESS, TextVariables.NAME, target.getName(), TextVariables.DISPLAY_NAME,
target.getDisplayName());
// Teleport home
getIslands().homeTeleportAsync(getWorld(), target.getPlayer());
return true;
} else if (getIslands().getSpawn(getWorld()).isPresent()) {
// Success
user.sendMessage(SUCCESS, TextVariables.NAME, target.getName(), TextVariables.DISPLAY_NAME,
target.getDisplayName());
getIslands().spawnTeleport(getWorld(), target.getPlayer());
return true;
} else if (getIWM().getAddon(getWorld())
.map(gm -> gm.getPlayerCommand().map(pc -> pc.getSubCommand("create").isPresent()).orElse(false))
.orElse(false) && target.performCommand(this.getTopLabel() + " create")) {
getAddon().logWarning("Expel: " + target.getName() + " had no island, so one was created");
user.sendMessage(SUCCESS, TextVariables.NAME, target.getName(), TextVariables.DISPLAY_NAME,
target.getDisplayName());
return true;
}
getAddon().logError("Expel: " + target.getName() + " had no island, and one could not be created");
user.sendMessage(CANNOT_EXPEL);
return false;
}
getAddon().logError("Expel: " + target.getName() + " had no island, and one could not be created");
user.sendMessage(CANNOT_EXPEL);
return false;
}
@Override
public Optional<List<String>> tabComplete(User user, String alias, List<String> args) {
Island island = getIslands().getIsland(getWorld(), user);
if (island != null) {
List<String> options = island.getPlayersOnIsland().stream().filter(p -> !p.equals(user.getPlayer())) // Not
// self
.filter(p -> user.getPlayer().canSee(p)) // Not invisible
.filter(p -> !p.isOp()) // Not op
.filter(p -> !p.hasPermission(this.getPermissionPrefix() + "admin.noexpel"))
.filter(p -> !p.hasPermission(this.getPermissionPrefix() + "mod.bypassexpel")).map(Player::getName)
.toList();
@Override
public Optional<List<String>> tabComplete(User user, String alias, List<String> args) {
Island island = getIslands().getIsland(getWorld(), user);
if (island != null) {
List<String> options = island.getPlayersOnIsland().stream().filter(p -> !p.equals(user.getPlayer())) // Not
// self
.filter(p -> user.getPlayer().canSee(p)) // Not invisible
.filter(p -> !p.isOp()) // Not op
.filter(p -> !p.hasPermission(this.getPermissionPrefix() + "admin.noexpel"))
.filter(p -> !p.hasPermission(this.getPermissionPrefix() + "mod.bypassexpel")).map(Player::getName)
.toList();
String lastArg = !args.isEmpty() ? args.get(args.size() - 1) : "";
return Optional.of(Util.tabLimit(options, lastArg));
} else {
return Optional.empty();
}
}
String lastArg = !args.isEmpty() ? args.get(args.size() - 1) : "";
return Optional.of(Util.tabLimit(options, lastArg));
} else {
return Optional.empty();
}
}
}

View File

@ -54,7 +54,8 @@ public class IslandGoCommand extends DelayedTeleportCommand {
// Prevent command if player is falling and its not allowed
if ((getIWM().inWorld(user.getWorld()) && Flags.PREVENT_TELEPORT_WHEN_FALLING.isSetForWorld(user.getWorld()))
&& user.getPlayer().getFallDistance() > 0) {
// We're sending the "hint" to the player to tell them they cannot teleport while falling.
// We're sending the "hint" to the player to tell them they cannot teleport
// while falling.
user.sendMessage(Flags.PREVENT_TELEPORT_WHEN_FALLING.getHintReference());
return false;
}
@ -71,23 +72,22 @@ public class IslandGoCommand extends DelayedTeleportCommand {
// Failed home name check
user.sendMessage("commands.island.go.unknown-home");
user.sendMessage("commands.island.sethome.homes-are");
names.keySet().forEach(n -> user.sendMessage("commands.island.sethome.home-list-syntax", TextVariables.NAME, n));
names.keySet().forEach(
n -> user.sendMessage("commands.island.sethome.home-list-syntax", TextVariables.NAME, n));
return false;
} else {
IslandInfo info = names.get(name);
getIslands().setPrimaryIsland(user.getUniqueId(), info.island);
if (info.islandName) {
this.delayCommand(user, () -> new SafeSpotTeleport.Builder(getPlugin())
.entity(user.getPlayer())
.location(getIslands().getHomeLocation(info.island))
.thenRun(() -> user.sendMessage("general.success"))
.build());
this.delayCommand(user,
() -> new SafeSpotTeleport.Builder(getPlugin()).entity(user.getPlayer())
.location(getIslands().getHomeLocation(info.island))
.thenRun(() -> user.sendMessage("general.success")).build());
} else {
this.delayCommand(user, () -> new SafeSpotTeleport.Builder(getPlugin())
.entity(user.getPlayer())
.location(getIslands().getHomeLocation(info.island, name))
.thenRun(() -> user.sendMessage("general.success"))
.build());
this.delayCommand(user,
() -> new SafeSpotTeleport.Builder(getPlugin()).entity(user.getPlayer())
.location(getIslands().getHomeLocation(info.island, name))
.thenRun(() -> user.sendMessage("general.success")).build());
}
}
} else {
@ -100,23 +100,24 @@ public class IslandGoCommand extends DelayedTeleportCommand {
for (Island island : islands) {
if (island.isReserved()) {
// Send player to create an island
getParent().getSubCommand("create").ifPresent(createCmd -> createCmd.call(user, createCmd.getLabel(), Collections.emptyList()));
getParent().getSubCommand("create")
.ifPresent(createCmd -> createCmd.call(user, createCmd.getLabel(), Collections.emptyList()));
return true;
}
}
return false;
}
@Override
public Optional<List<String>> tabComplete(User user, String alias, List<String> args) {
String lastArg = !args.isEmpty() ? args.get(args.size()-1) : "";
String lastArg = !args.isEmpty() ? args.get(args.size() - 1) : "";
return Optional.of(Util.tabLimit(new ArrayList<>(getNameIslandMap(user).keySet()), lastArg));
}
private record IslandInfo(Island island, boolean islandName) {}
private record IslandInfo(Island island, boolean islandName) {
}
private Map<String, IslandInfo> getNameIslandMap(User user) {
Map<String, IslandInfo> islandMap = new HashMap<>();
@ -128,7 +129,8 @@ public class IslandGoCommand extends DelayedTeleportCommand {
islandMap.put(island.getName(), new IslandInfo(island, true));
} else {
// Name has not been set
String text = user.getTranslation("protection.flags.ENTER_EXIT_MESSAGES.island", TextVariables.NAME, user.getName(), TextVariables.DISPLAY_NAME, user.getDisplayName()) + " " + index;
String text = user.getTranslation("protection.flags.ENTER_EXIT_MESSAGES.island", TextVariables.NAME,
user.getName(), TextVariables.DISPLAY_NAME, user.getDisplayName()) + " " + index;
islandMap.put(text, new IslandInfo(island, true));
}
// Add homes. Homes do not need an island specified

View File

@ -41,15 +41,14 @@ public class IslandHomesCommand extends ConfirmableCommand {
@Override
public boolean execute(User user, String label, List<String> args) {
user.sendMessage("commands.island.sethome.homes-are");
islands.forEach(island ->
island.getHomes().keySet().stream().filter(s -> !s.isEmpty())
.forEach(s -> user.sendMessage("commands.island.sethome.home-list-syntax", TextVariables.NAME, s)));
islands.forEach(island -> island.getHomes().keySet().stream().filter(s -> !s.isEmpty())
.forEach(s -> user.sendMessage("commands.island.sethome.home-list-syntax", TextVariables.NAME, s)));
return true;
}
@Override
public Optional<List<String>> tabComplete(User user, String alias, List<String> args) {
String lastArg = !args.isEmpty() ? args.get(args.size()-1) : "";
String lastArg = !args.isEmpty() ? args.get(args.size() - 1) : "";
List<String> result = new ArrayList<>();
for (Island island : getIslands().getIslands(getWorld(), user.getUniqueId())) {
result.addAll(island.getHomes().keySet());

View File

@ -36,9 +36,11 @@ public class IslandInfoCommand extends CompositeCommand {
showHelp(this, user);
return false;
}
// If there are no args, then the player wants info on the island at this location
// If there are no args, then the player wants info on the island at this
// location
if (args.isEmpty()) {
if (!getIslands().getIslandAt(user.getLocation()).map(i -> new IslandInfo(i).showInfo(user)).orElse(false)) {
if (!getIslands().getIslandAt(user.getLocation()).map(i -> new IslandInfo(i).showInfo(user))
.orElse(false)) {
user.sendMessage("commands.admin.info.no-island");
return false;
}
@ -63,7 +65,7 @@ public class IslandInfoCommand extends CompositeCommand {
@Override
public Optional<List<String>> tabComplete(User user, String alias, List<String> args) {
String lastArg = !args.isEmpty() ? args.get(args.size()-1) : "";
String lastArg = !args.isEmpty() ? args.get(args.size() - 1) : "";
if (lastArg.isEmpty()) {
// Don't show every player on the server. Require at least the first letter
return Optional.empty();

View File

@ -54,7 +54,7 @@ public class IslandLanguageCommand extends CompositeCommand {
@Override
public Optional<List<String>> tabComplete(User user, String alias, List<String> args) {
List<String> options = new ArrayList<>();
String lastArg = !args.isEmpty() ? args.get(args.size()-1) : "";
String lastArg = !args.isEmpty() ? args.get(args.size() - 1) : "";
for (Locale locale : getPlugin().getLocalesManager().getAvailableLocales(true)) {
options.add(locale.toLanguageTag());
}

View File

@ -14,12 +14,14 @@ import world.bentobox.bentobox.database.objects.Island;
/**
* Tells the players which islands are near to them
*
* @author tastybento
* @since 1.5.0
*/
public class IslandNearCommand extends CompositeCommand {
private static final List<BlockFace> COMPASS_POINTS = Arrays.asList(BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST);
private static final List<BlockFace> COMPASS_POINTS = Arrays.asList(BlockFace.NORTH, BlockFace.EAST,
BlockFace.SOUTH, BlockFace.WEST);
public IslandNearCommand(CompositeCommand islandCommand) {
super(islandCommand, "near");
@ -57,17 +59,12 @@ public class IslandNearCommand extends CompositeCommand {
int dist = getIWM().getIslandDistance(getWorld()) * 2;
boolean noNeighbors = true;
for (BlockFace face : COMPASS_POINTS) {
String name = getIslands().getIslandAt(
island
.getCenter()
.getBlock()
.getRelative(face, dist)
.getLocation())
String name = getIslands().getIslandAt(island.getCenter().getBlock().getRelative(face, dist).getLocation())
.map(i -> getName(user, i)).orElse("");
if (!name.isEmpty()) {
noNeighbors = false;
user.sendMessage("commands.island.near.syntax",
"[direction]", user.getTranslation("commands.island.near." + face.name().toLowerCase(Locale.ENGLISH)),
user.sendMessage("commands.island.near.syntax", "[direction]",
user.getTranslation("commands.island.near." + face.name().toLowerCase(Locale.ENGLISH)),
TextVariables.NAME, name);
}
}

View File

@ -20,6 +20,7 @@ import world.bentobox.bentobox.util.Util;
/**
* Renames a home
*
* @author tastybento
*
*/
@ -57,7 +58,8 @@ public class IslandRenamehomeCommand extends ConfirmableCommand {
if (!getIslands().isHomeLocation(island, String.join(" ", args))) {
user.sendMessage("commands.island.go.unknown-home");
user.sendMessage("commands.island.sethome.homes-are");
island.getHomes().keySet().stream().filter(s -> !s.isEmpty()).forEach(s -> user.sendMessage("commands.island.sethome.home-list-syntax", TextVariables.NAME, s));
island.getHomes().keySet().stream().filter(s -> !s.isEmpty())
.forEach(s -> user.sendMessage("commands.island.sethome.home-list-syntax", TextVariables.NAME, s));
this.showHelp(this, user);
return false;
}
@ -65,7 +67,8 @@ public class IslandRenamehomeCommand extends ConfirmableCommand {
// check command permission
int rank = Objects.requireNonNull(island).getRank(user);
if (rank < island.getRankCommand(getUsage())) {
user.sendMessage("general.errors.insufficient-rank", TextVariables.RANK, user.getTranslation(getPlugin().getRanksManager().getRank(rank)));
user.sendMessage("general.errors.insufficient-rank", TextVariables.RANK,
user.getTranslation(getPlugin().getRanksManager().getRank(rank)));
return false;
}
@ -74,19 +77,15 @@ public class IslandRenamehomeCommand extends ConfirmableCommand {
@Override
public boolean execute(User user, String label, List<String> args) {
new ConversationFactory(BentoBox.getInstance())
.withModality(true)
.withLocalEcho(false)
.withTimeout(90)
.withFirstPrompt(new NamePrompt(getPlugin(), island, user, String.join(" ", args)))
.buildConversation(user.getPlayer()).begin();
new ConversationFactory(BentoBox.getInstance()).withModality(true).withLocalEcho(false).withTimeout(90)
.withFirstPrompt(new NamePrompt(getPlugin(), island, user, String.join(" ", args)))
.buildConversation(user.getPlayer()).begin();
return true;
}
@Override
public Optional<List<String>> tabComplete(User user, String alias, List<String> args) {
String lastArg = !args.isEmpty() ? args.get(args.size()-1) : "";
String lastArg = !args.isEmpty() ? args.get(args.size() - 1) : "";
Island is = getIslands().getIsland(getWorld(), user.getUniqueId());
if (is != null) {
return Optional.of(Util.tabLimit(new ArrayList<>(is.getHomes().keySet()), lastArg));

View File

@ -24,171 +24,171 @@ import world.bentobox.bentobox.util.Util;
*/
public class IslandResetCommand extends ConfirmableCommand {
private boolean noPaste;
private boolean noPaste;
public IslandResetCommand(CompositeCommand islandCommand) {
super(islandCommand, "reset", "restart");
}
public IslandResetCommand(CompositeCommand islandCommand) {
super(islandCommand, "reset", "restart");
}
/**
* Creates the island reset command
*
* @param islandCommand - parent command
* @param noPaste - true if resetting should not paste a new island
*/
public IslandResetCommand(CompositeCommand islandCommand, boolean noPaste) {
super(islandCommand, "reset", "restart");
this.noPaste = noPaste;
}
/**
* Creates the island reset command
*
* @param islandCommand - parent command
* @param noPaste - true if resetting should not paste a new island
*/
public IslandResetCommand(CompositeCommand islandCommand, boolean noPaste) {
super(islandCommand, "reset", "restart");
this.noPaste = noPaste;
}
@Override
public void setup() {
setPermission("island.reset");
setOnlyPlayer(true);
setParametersHelp("commands.island.reset.parameters");
setDescription("commands.island.reset.description");
}
@Override
public void setup() {
setPermission("island.reset");
setOnlyPlayer(true);
setParametersHelp("commands.island.reset.parameters");
setDescription("commands.island.reset.description");
}
@Override
public boolean canExecute(User user, String label, List<String> args) {
// Check cooldown
if (getSettings().getResetCooldown() > 0 && checkCooldown(user)) {
return false;
}
if (!getIslands().hasIsland(getWorld(), user.getUniqueId())) {
user.sendMessage("general.errors.no-island");
return false;
}
int resetsLeft = getPlayers().getResetsLeft(getWorld(), user.getUniqueId());
if (resetsLeft != -1) {
// Resets are not unlimited here
if (resetsLeft == 0) {
// No resets allowed
user.sendMessage("commands.island.reset.none-left");
return false;
} else {
// Still some resets left
// Notify how many resets are left
user.sendMessage("commands.island.reset.resets-left", TextVariables.NUMBER, String.valueOf(resetsLeft));
}
}
@Override
public boolean canExecute(User user, String label, List<String> args) {
// Check cooldown
if (getSettings().getResetCooldown() > 0 && checkCooldown(user)) {
return false;
}
if (!getIslands().hasIsland(getWorld(), user.getUniqueId())) {
user.sendMessage("general.errors.no-island");
return false;
}
int resetsLeft = getPlayers().getResetsLeft(getWorld(), user.getUniqueId());
if (resetsLeft != -1) {
// Resets are not unlimited here
if (resetsLeft == 0) {
// No resets allowed
user.sendMessage("commands.island.reset.none-left");
return false;
} else {
// Still some resets left
// Notify how many resets are left
user.sendMessage("commands.island.reset.resets-left", TextVariables.NUMBER, String.valueOf(resetsLeft));
}
}
return true;
}
return true;
}
@Override
public boolean execute(User user, String label, List<String> args) {
// Permission check if the name is not the default one
if (!args.isEmpty()) {
String name = getPlugin().getBlueprintsManager().validate(getAddon(), Util.sanitizeInput(args.get(0)));
if (name == null || name.isEmpty()) {
// The blueprint name is not valid.
user.sendMessage("commands.island.create.unknown-blueprint");
return false;
}
if (!getPlugin().getBlueprintsManager().checkPerm(getAddon(), user, Util.sanitizeInput(args.get(0)))) {
return false;
}
return resetIsland(user, name);
} else {
// Show panel after confirmation
if (getPlugin().getSettings().isResetConfirmation()) {
this.askConfirmation(user, user.getTranslation("commands.island.reset.confirmation"),
() -> selectBundle(user, label));
} else {
selectBundle(user, label);
}
return true;
}
}
@Override
public boolean execute(User user, String label, List<String> args) {
// Permission check if the name is not the default one
if (!args.isEmpty()) {
String name = getPlugin().getBlueprintsManager().validate(getAddon(), Util.sanitizeInput(args.get(0)));
if (name == null || name.isEmpty()) {
// The blueprint name is not valid.
user.sendMessage("commands.island.create.unknown-blueprint");
return false;
}
if (!getPlugin().getBlueprintsManager().checkPerm(getAddon(), user, Util.sanitizeInput(args.get(0)))) {
return false;
}
return resetIsland(user, name);
} else {
// Show panel after confirmation
if (getPlugin().getSettings().isResetConfirmation()) {
this.askConfirmation(user, user.getTranslation("commands.island.reset.confirmation"),
() -> selectBundle(user, label));
} else {
selectBundle(user, label);
}
return true;
}
}
/**
* Either selects the bundle to use or asks the user to choose.
*
* @since 1.5.1
*/
private void selectBundle(@NonNull User user, @NonNull String label) {
// Show panel only if there are multiple bundles available
if (getPlugin().getBlueprintsManager().getBlueprintBundles(getAddon()).size() > 1) {
// Show panel - once the player selected a bundle, this will re-run this command
IslandCreationPanel.openPanel(this, user, label);
} else {
resetIsland(user, BlueprintsManager.DEFAULT_BUNDLE_NAME);
}
}
/**
* Either selects the bundle to use or asks the user to choose.
*
* @since 1.5.1
*/
private void selectBundle(@NonNull User user, @NonNull String label) {
// Show panel only if there are multiple bundles available
if (getPlugin().getBlueprintsManager().getBlueprintBundles(getAddon()).size() > 1) {
// Show panel - once the player selected a bundle, this will re-run this command
IslandCreationPanel.openPanel(this, user, label);
} else {
resetIsland(user, BlueprintsManager.DEFAULT_BUNDLE_NAME);
}
}
/**
* Reset island
*
* @param user user
* @param name name of Blueprint Bundle
* @return true if successful
*/
private boolean resetIsland(User user, String name) {
// Get the player's old island
Island oldIsland = getIslands().getIsland(getWorld(), user);
deleteOldIsland(user, oldIsland);
/**
* Reset island
*
* @param user user
* @param name name of Blueprint Bundle
* @return true if successful
*/
private boolean resetIsland(User user, String name) {
// Get the player's old island
Island oldIsland = getIslands().getIsland(getWorld(), user);
deleteOldIsland(user, oldIsland);
user.sendMessage("commands.island.create.creating-island");
// Create new island and then delete the old one
try {
Builder builder = NewIsland.builder().player(user).reason(Reason.RESET).addon(getAddon())
.oldIsland(oldIsland).name(name);
if (noPaste)
builder.noPaste();
builder.build();
} catch (IOException e) {
getPlugin().logError("Could not create island for player. " + e.getMessage());
user.sendMessage(e.getMessage());
return false;
}
setCooldown(user.getUniqueId(), getSettings().getResetCooldown());
return true;
}
user.sendMessage("commands.island.create.creating-island");
// Create new island and then delete the old one
try {
Builder builder = NewIsland.builder().player(user).reason(Reason.RESET).addon(getAddon())
.oldIsland(oldIsland).name(name);
if (noPaste)
builder.noPaste();
builder.build();
} catch (IOException e) {
getPlugin().logError("Could not create island for player. " + e.getMessage());
user.sendMessage(e.getMessage());
return false;
}
setCooldown(user.getUniqueId(), getSettings().getResetCooldown());
return true;
}
private void deleteOldIsland(User user, Island oldIsland) {
// Fire island preclear event
IslandEvent.builder().involvedPlayer(user.getUniqueId()).reason(Reason.PRECLEAR).island(oldIsland)
.oldIsland(oldIsland).location(oldIsland.getCenter()).build();
private void deleteOldIsland(User user, Island oldIsland) {
// Fire island preclear event
IslandEvent.builder().involvedPlayer(user.getUniqueId()).reason(Reason.PRECLEAR).island(oldIsland)
.oldIsland(oldIsland).location(oldIsland.getCenter()).build();
// Reset the island
// Reset the island
// Kick all island members (including the owner)
kickMembers(oldIsland);
// Kick all island members (including the owner)
kickMembers(oldIsland);
// Add a reset
getPlayers().addReset(getWorld(), user.getUniqueId());
}
// Add a reset
getPlayers().addReset(getWorld(), user.getUniqueId());
}
/**
* Kicks the members (incl. owner) of the island.
*
* @since 1.7.0
*/
private void kickMembers(Island island) {
/*
* We cannot assume the island owner can run /[cmd] team kick (it might be
* disabled, or there could be permission restrictions...) Therefore, we need to
* do it manually. Plus, a more specific team event (TeamDeleteEvent) is called
* by this method.
*/
island.getMemberSet().forEach(memberUUID -> {
/**
* Kicks the members (incl. owner) of the island.
*
* @since 1.7.0
*/
private void kickMembers(Island island) {
/*
* We cannot assume the island owner can run /[cmd] team kick (it might be
* disabled, or there could be permission restrictions...) Therefore, we need to
* do it manually. Plus, a more specific team event (TeamDeleteEvent) is called
* by this method.
*/
island.getMemberSet().forEach(memberUUID -> {
User member = User.getInstance(memberUUID);
// Send a "you're kicked" message if the member is not the island owner (send
// before removing!)
if (!memberUUID.equals(island.getOwner())) {
member.sendMessage("commands.island.reset.kicked-from-island", TextVariables.GAMEMODE,
getAddon().getDescription().getName());
}
// Remove player
getIslands().removePlayer(island, memberUUID);
User member = User.getInstance(memberUUID);
// Send a "you're kicked" message if the member is not the island owner (send
// before removing!)
if (!memberUUID.equals(island.getOwner())) {
member.sendMessage("commands.island.reset.kicked-from-island", TextVariables.GAMEMODE,
getAddon().getDescription().getName());
}
// Remove player
getIslands().removePlayer(island, memberUUID);
// Clean player
getPlayers().cleanLeavingPlayer(getWorld(), member, false, island);
// Clean player
getPlayers().cleanLeavingPlayer(getWorld(), member, false, island);
// Fire event
TeamEvent.builder().island(island).reason(TeamEvent.Reason.DELETE).involvedPlayer(memberUUID).build();
});
}
// Fire event
TeamEvent.builder().island(island).reason(TeamEvent.Reason.DELETE).involvedPlayer(memberUUID).build();
});
}
}

View File

@ -8,7 +8,6 @@ import world.bentobox.bentobox.api.localization.TextVariables;
import world.bentobox.bentobox.api.user.User;
import world.bentobox.bentobox.database.objects.Island;
/**
* @author tastybento
*
@ -26,10 +25,8 @@ public class IslandResetnameCommand extends CompositeCommand {
setDescription("commands.island.resetname.description");
}
@Override
public boolean canExecute(User user, String label, List<String> args)
{
public boolean canExecute(User user, String label, List<String> args) {
Island island = getIslands().getIsland(getWorld(), user);
if (island == null) {
@ -40,15 +37,14 @@ public class IslandResetnameCommand extends CompositeCommand {
// Check command rank.
int rank = Objects.requireNonNull(island).getRank(user);
if (rank < island.getRankCommand(getUsage())) {
user.sendMessage("general.errors.insufficient-rank",
TextVariables.RANK, user.getTranslation(getPlugin().getRanksManager().getRank(rank)));
user.sendMessage("general.errors.insufficient-rank", TextVariables.RANK,
user.getTranslation(getPlugin().getRanksManager().getRank(rank)));
return false;
}
return true;
}
@Override
public boolean execute(User user, String label, List<String> args) {

View File

@ -13,7 +13,6 @@ import world.bentobox.bentobox.api.user.User;
import world.bentobox.bentobox.database.objects.Island;
import world.bentobox.bentobox.managers.RanksManager;
public class IslandSethomeCommand extends ConfirmableCommand {
private @Nullable Island island;
@ -46,7 +45,8 @@ public class IslandSethomeCommand extends ConfirmableCommand {
int rank = Objects.requireNonNull(island).getRank(user);
if (rank < island.getRankCommand(getUsage())) {
user.sendMessage("general.errors.insufficient-rank", TextVariables.RANK, user.getTranslation(getPlugin().getRanksManager().getRank(rank)));
user.sendMessage("general.errors.insufficient-rank", TextVariables.RANK,
user.getTranslation(getPlugin().getRanksManager().getRank(rank)));
return false;
}
@ -56,8 +56,9 @@ public class IslandSethomeCommand extends ConfirmableCommand {
if (getIslands().getNumberOfHomesIfAdded(island, String.join(" ", args)) > maxHomes) {
user.sendMessage("commands.island.sethome.too-many-homes", TextVariables.NUMBER, String.valueOf(maxHomes));
user.sendMessage("commands.island.sethome.homes-are");
getIslands().getIslands(getWorld(), user).forEach(is ->
is.getHomes().keySet().stream().filter(s -> !s.isEmpty()).forEach(s -> user.sendMessage("commands.island.sethome.home-list-syntax", TextVariables.NAME, s)));
getIslands().getIslands(getWorld(), user)
.forEach(is -> is.getHomes().keySet().stream().filter(s -> !s.isEmpty()).forEach(
s -> user.sendMessage("commands.island.sethome.home-list-syntax", TextVariables.NAME, s)));
return false;
}
return true;
@ -77,7 +78,8 @@ public class IslandSethomeCommand extends ConfirmableCommand {
// Check if a confirmation is required
if (ws.isRequireConfirmationToSetHomeInNether()) {
askConfirmation(user, user.getTranslation("commands.island.sethome.nether.confirmation"), () -> doSetHome(user, number));
askConfirmation(user, user.getTranslation("commands.island.sethome.nether.confirmation"),
() -> doSetHome(user, number));
} else {
doSetHome(user, number);
}
@ -90,7 +92,8 @@ public class IslandSethomeCommand extends ConfirmableCommand {
// Check if a confirmation is required
if (ws.isRequireConfirmationToSetHomeInTheEnd()) {
askConfirmation(user, user.getTranslation("commands.island.sethome.the-end.confirmation"), () -> doSetHome(user, number));
askConfirmation(user, user.getTranslation("commands.island.sethome.the-end.confirmation"),
() -> doSetHome(user, number));
} else {
doSetHome(user, number);
}
@ -106,10 +109,8 @@ public class IslandSethomeCommand extends ConfirmableCommand {
user.sendMessage("commands.island.sethome.home-set");
if (island.getHomes().size() > 1) {
user.sendMessage("commands.island.sethome.homes-are");
island
.getHomes()
.keySet()
.stream().filter(s -> !s.isEmpty()).forEach(s -> user.sendMessage("commands.island.sethome.home-list-syntax", TextVariables.NAME, s));
island.getHomes().keySet().stream().filter(s -> !s.isEmpty())
.forEach(s -> user.sendMessage("commands.island.sethome.home-list-syntax", TextVariables.NAME, s));
}
}
}

View File

@ -11,7 +11,6 @@ import world.bentobox.bentobox.api.localization.TextVariables;
import world.bentobox.bentobox.api.user.User;
import world.bentobox.bentobox.database.objects.Island;
/**
* @author tastybento
*
@ -31,10 +30,8 @@ public class IslandSetnameCommand extends CompositeCommand {
setConfigurableRankCommand();
}
@Override
public boolean canExecute(User user, String label, List<String> args)
{
public boolean canExecute(User user, String label, List<String> args) {
// Explain command
if (args.isEmpty()) {
showHelp(this, user);
@ -51,7 +48,8 @@ public class IslandSetnameCommand extends CompositeCommand {
// Check command rank.
int rank = Objects.requireNonNull(island).getRank(user);
if (rank < island.getRankCommand(getUsage())) {
user.sendMessage("general.errors.insufficient-rank", TextVariables.RANK, user.getTranslation(getPlugin().getRanksManager().getRank(rank)));
user.sendMessage("general.errors.insufficient-rank", TextVariables.RANK,
user.getTranslation(getPlugin().getRanksManager().getRank(rank)));
return false;
}
@ -60,11 +58,13 @@ public class IslandSetnameCommand extends CompositeCommand {
// Check if the name isn't too short or too long
if (name.length() < getSettings().getNameMinLength() || ChatColor.stripColor(name).isEmpty()) {
user.sendMessage("commands.island.setname.name-too-short", TextVariables.NUMBER, String.valueOf(getSettings().getNameMinLength()));
user.sendMessage("commands.island.setname.name-too-short", TextVariables.NUMBER,
String.valueOf(getSettings().getNameMinLength()));
return false;
}
if (name.length() > getSettings().getNameMaxLength()) {
user.sendMessage("commands.island.setname.name-too-long", TextVariables.NUMBER, String.valueOf(getSettings().getNameMaxLength()));
user.sendMessage("commands.island.setname.name-too-long", TextVariables.NUMBER,
String.valueOf(getSettings().getNameMaxLength()));
return false;
}
@ -82,7 +82,6 @@ public class IslandSetnameCommand extends CompositeCommand {
return true;
}
@Override
public boolean execute(User user, String label, List<String> args) {
// Naming the island - join all the arguments with spaces.
@ -99,13 +98,8 @@ public class IslandSetnameCommand extends CompositeCommand {
island.setName(name);
user.sendMessage("commands.island.setname.success", TextVariables.NAME, name);
// Fire the IslandNameEvent
new IslandEvent.IslandEventBuilder()
.island(island)
.involvedPlayer(user.getUniqueId())
.reason(IslandEvent.Reason.NAME)
.previousName(previousName)
.admin(false)
.build();
new IslandEvent.IslandEventBuilder().island(island).involvedPlayer(user.getUniqueId())
.reason(IslandEvent.Reason.NAME).previousName(previousName).admin(false).build();
return true;
}
}

View File

@ -32,7 +32,8 @@ public class IslandSettingsCommand extends CompositeCommand {
public boolean canExecute(User user, String label, List<String> args) {
if (Util.getWorld(user.getWorld()).equals(getWorld())) {
// Player is in same world
island = getIslands().getIslandAt(user.getLocation()).orElseGet(() -> getIslands().getIsland(user.getWorld(), user.getUniqueId()));
island = getIslands().getIslandAt(user.getLocation())
.orElseGet(() -> getIslands().getIsland(user.getWorld(), user.getUniqueId()));
} else {
island = getIslands().getIsland(getWorld(), user);
}
@ -45,15 +46,10 @@ public class IslandSettingsCommand extends CompositeCommand {
@Override
public boolean execute(User user, String label, List<String> args) {
new TabbedPanelBuilder()
.user(user)
.world(island.getWorld())
.tab(1, new SettingsTab(user, island, Flag.Type.PROTECTION))
.tab(2, new SettingsTab(user, island, Flag.Type.SETTING))
.startingSlot(1)
.size(54)
.hideIfEmpty()
.build().openPanel();
new TabbedPanelBuilder().user(user).world(island.getWorld())
.tab(1, new SettingsTab(user, island, Flag.Type.PROTECTION))
.tab(2, new SettingsTab(user, island, Flag.Type.SETTING)).startingSlot(1).size(54).hideIfEmpty().build()
.openPanel();
return true;
}
}

View File

@ -9,6 +9,7 @@ import world.bentobox.bentobox.lists.Flags;
/**
* Player command to teleport oneself to the world's spawn.
*
* @author Poslovitch
* @since 1.1
*/
@ -29,7 +30,8 @@ public class IslandSpawnCommand extends DelayedTeleportCommand {
public boolean execute(User user, String label, List<String> args) {
if ((getIWM().inWorld(user.getWorld()) && Flags.PREVENT_TELEPORT_WHEN_FALLING.isSetForWorld(user.getWorld()))
&& user.getPlayer().getFallDistance() > 0) {
// We're sending the "hint" to the player to tell them they cannot teleport while falling.
// We're sending the "hint" to the player to tell them they cannot teleport
// while falling.
user.sendMessage(Flags.PREVENT_TELEPORT_WHEN_FALLING.getHintReference());
return false;
}

View File

@ -17,6 +17,7 @@ import world.bentobox.bentobox.util.Util;
/**
* Unban command
*
* @author tastybento
*
*/
@ -46,7 +47,8 @@ public class IslandUnbanCommand extends CompositeCommand {
}
UUID playerUUID = user.getUniqueId();
// Player issuing the command must have an island or be in a team
if (!getIslands().inTeam(getWorld(), user.getUniqueId()) && !getIslands().hasIsland(getWorld(), user.getUniqueId())) {
if (!getIslands().inTeam(getWorld(), user.getUniqueId())
&& !getIslands().hasIsland(getWorld(), user.getUniqueId())) {
user.sendMessage("general.errors.no-island");
return false;
}
@ -54,7 +56,8 @@ public class IslandUnbanCommand extends CompositeCommand {
Island island = getIslands().getIsland(getWorld(), user);
int rank = Objects.requireNonNull(island).getRank(user);
if (rank < island.getRankCommand(getUsage())) {
user.sendMessage("general.errors.insufficient-rank", TextVariables.RANK, user.getTranslation(getPlugin().getRanksManager().getRank(rank)));
user.sendMessage("general.errors.insufficient-rank", TextVariables.RANK,
user.getTranslation(getPlugin().getRanksManager().getRank(rank)));
return false;
}
// Get target player
@ -82,24 +85,22 @@ public class IslandUnbanCommand extends CompositeCommand {
Island island = getIslands().getIsland(getWorld(), user.getUniqueId());
// Run the event
IslandBaseEvent unbanEvent = IslandEvent.builder()
.island(island)
.involvedPlayer(target.getUniqueId())
.admin(false)
.reason(IslandEvent.Reason.UNBAN)
.build();
IslandBaseEvent unbanEvent = IslandEvent.builder().island(island).involvedPlayer(target.getUniqueId())
.admin(false).reason(IslandEvent.Reason.UNBAN).build();
if (unbanEvent.getNewEvent().map(IslandBaseEvent::isCancelled).orElse(unbanEvent.isCancelled())) {
// Unbanning was blocked due to an event cancellation.
return false;
}
// Event is not cancelled
if (island.unban(user.getUniqueId(), target.getUniqueId())) {
user.sendMessage("commands.island.unban.player-unbanned", TextVariables.NAME, target.getName(), TextVariables.DISPLAY_NAME, target.getDisplayName());
target.sendMessage("commands.island.unban.you-are-unbanned", TextVariables.NAME, user.getName(), TextVariables.DISPLAY_NAME, user.getDisplayName());
user.sendMessage("commands.island.unban.player-unbanned", TextVariables.NAME, target.getName(),
TextVariables.DISPLAY_NAME, target.getDisplayName());
target.sendMessage("commands.island.unban.you-are-unbanned", TextVariables.NAME, user.getName(),
TextVariables.DISPLAY_NAME, user.getDisplayName());
// Set cooldown
if (getSettings().getBanCooldown() > 0 && getParent() != null) {
getParent().getSubCommand("ban").ifPresent(subCommand ->
subCommand.setCooldown(island.getUniqueId(), target.getUniqueId().toString(), getSettings().getBanCooldown() * 60));
getParent().getSubCommand("ban").ifPresent(subCommand -> subCommand.setCooldown(island.getUniqueId(),
target.getUniqueId().toString(), getSettings().getBanCooldown() * 60));
}
return true;
}
@ -112,7 +113,7 @@ public class IslandUnbanCommand extends CompositeCommand {
Island island = getIslands().getIsland(getWorld(), user.getUniqueId());
if (island != null) {
List<String> options = island.getBanned().stream().map(getPlayers()::getName).toList();
String lastArg = !args.isEmpty() ? args.get(args.size()-1) : "";
String lastArg = !args.isEmpty() ? args.get(args.size() - 1) : "";
return Optional.of(Util.tabLimit(options, lastArg));
} else {
return Optional.empty();

View File

@ -7,6 +7,7 @@ import world.bentobox.bentobox.database.objects.Island;
/**
* Represents an invite
*
* @author tastybento
* @since 1.8.0
*/
@ -17,9 +18,7 @@ public class Invite {
*
*/
public enum Type {
COOP,
TEAM,
TRUST
COOP, TEAM, TRUST
}
private final Type type;
@ -28,10 +27,10 @@ public class Invite {
private final Island island;
/**
* @param type - invitation type, e.g., coop, team, trust
* @param type - invitation type, e.g., coop, team, trust
* @param inviter - UUID of inviter
* @param invitee - UUID of invitee
* @param island - the island this invite is for
* @param island - the island this invite is for
*/
public Invite(Type type, UUID inviter, UUID invitee, Island island) {
this.type = type;
@ -68,7 +67,9 @@ public class Invite {
return island;
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
@ -76,7 +77,9 @@ public class Invite {
return Objects.hash(invitee, inviter, type);
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override

View File

@ -24,210 +24,211 @@ import world.bentobox.bentobox.util.Util;
public class IslandTeamCommand extends CompositeCommand {
/**
* Invited list. Key is the invited party, value is the invite.
* @since 1.8.0
*/
private final Map<UUID, Invite> inviteMap;
/**
* Invited list. Key is the invited party, value is the invite.
*
* @since 1.8.0
*/
private final Map<UUID, Invite> inviteMap;
public IslandTeamCommand(CompositeCommand parent) {
super(parent, "team");
inviteMap = new HashMap<>();
}
public IslandTeamCommand(CompositeCommand parent) {
super(parent, "team");
inviteMap = new HashMap<>();
}
@Override
public void setup() {
setPermission("island.team");
setOnlyPlayer(true);
setDescription("commands.island.team.description");
// Register commands
new IslandTeamInviteCommand(this);
new IslandTeamLeaveCommand(this);
new IslandTeamSetownerCommand(this);
new IslandTeamKickCommand(this);
new IslandTeamInviteAcceptCommand(this);
new IslandTeamInviteRejectCommand(this);
if (getPlugin().getRanksManager().rankExists(RanksManager.COOP_RANK_REF)) {
new IslandTeamCoopCommand(this);
new IslandTeamUncoopCommand(this);
}
if (getPlugin().getRanksManager().rankExists(RanksManager.TRUSTED_RANK_REF)) {
new IslandTeamTrustCommand(this);
new IslandTeamUntrustCommand(this);
}
new IslandTeamPromoteCommand(this, "promote");
new IslandTeamPromoteCommand(this, "demote");
}
@Override
public void setup() {
setPermission("island.team");
setOnlyPlayer(true);
setDescription("commands.island.team.description");
// Register commands
new IslandTeamInviteCommand(this);
new IslandTeamLeaveCommand(this);
new IslandTeamSetownerCommand(this);
new IslandTeamKickCommand(this);
new IslandTeamInviteAcceptCommand(this);
new IslandTeamInviteRejectCommand(this);
if (getPlugin().getRanksManager().rankExists(RanksManager.COOP_RANK_REF)) {
new IslandTeamCoopCommand(this);
new IslandTeamUncoopCommand(this);
}
if (getPlugin().getRanksManager().rankExists(RanksManager.TRUSTED_RANK_REF)) {
new IslandTeamTrustCommand(this);
new IslandTeamUntrustCommand(this);
}
new IslandTeamPromoteCommand(this, "promote");
new IslandTeamPromoteCommand(this, "demote");
}
@Override
public boolean execute(User user, String label, List<String> args) {
// Player issuing the command must have an island
Island island = getIslands().getPrimaryIsland(getWorld(), user.getUniqueId());
if (island == null) {
user.sendMessage("general.errors.no-island");
return false;
}
@Override
public boolean execute(User user, String label, List<String> args) {
// Player issuing the command must have an island
Island island = getIslands().getPrimaryIsland(getWorld(), user.getUniqueId());
if (island == null) {
user.sendMessage("general.errors.no-island");
return false;
}
UUID playerUUID = user.getUniqueId();
// Fire event so add-ons can run commands, etc.
if (fireEvent(user, island)) {
// Cancelled
return false;
}
Set<UUID> teamMembers = getMembers(getWorld(), user);
if (playerUUID.equals(island.getOwner())) {
int maxSize = getIslands().getMaxMembers(island, RanksManager.MEMBER_RANK);
if (teamMembers.size() < maxSize) {
user.sendMessage("commands.island.team.invite.you-can-invite", TextVariables.NUMBER, String.valueOf(maxSize - teamMembers.size()));
} else {
user.sendMessage("commands.island.team.invite.errors.island-is-full");
}
}
// Show members of island
showMembers(island, user);
return true;
}
UUID playerUUID = user.getUniqueId();
// Fire event so add-ons can run commands, etc.
if (fireEvent(user, island)) {
// Cancelled
return false;
}
Set<UUID> teamMembers = getMembers(getWorld(), user);
if (playerUUID.equals(island.getOwner())) {
int maxSize = getIslands().getMaxMembers(island, RanksManager.MEMBER_RANK);
if (teamMembers.size() < maxSize) {
user.sendMessage("commands.island.team.invite.you-can-invite", TextVariables.NUMBER,
String.valueOf(maxSize - teamMembers.size()));
} else {
user.sendMessage("commands.island.team.invite.errors.island-is-full");
}
}
// Show members of island
showMembers(island, user);
return true;
}
private void showMembers(Island island, User user) {
// Gather online members
long count = island
.getMemberSet(RanksManager.MEMBER_RANK)
.stream()
.filter(uuid -> Util.getOnlinePlayerList(user).contains(Bukkit.getOfflinePlayer(uuid).getName()))
.count();
private void showMembers(Island island, User user) {
// Gather online members
long count = island.getMemberSet(RanksManager.MEMBER_RANK).stream()
.filter(uuid -> Util.getOnlinePlayerList(user).contains(Bukkit.getOfflinePlayer(uuid).getName()))
.count();
// List of ranks that we will loop through
Integer[] ranks = new Integer[]{RanksManager.OWNER_RANK, RanksManager.SUB_OWNER_RANK, RanksManager.MEMBER_RANK, RanksManager.TRUSTED_RANK, RanksManager.COOP_RANK};
// List of ranks that we will loop through
Integer[] ranks = new Integer[] { RanksManager.OWNER_RANK, RanksManager.SUB_OWNER_RANK,
RanksManager.MEMBER_RANK, RanksManager.TRUSTED_RANK, RanksManager.COOP_RANK };
// Show header:
user.sendMessage("commands.island.team.info.header",
"[max]", String.valueOf(getIslands().getMaxMembers(island, RanksManager.MEMBER_RANK)),
"[total]", String.valueOf(island.getMemberSet().size()),
"[online]", String.valueOf(count));
// Show header:
user.sendMessage("commands.island.team.info.header", "[max]",
String.valueOf(getIslands().getMaxMembers(island, RanksManager.MEMBER_RANK)), "[total]",
String.valueOf(island.getMemberSet().size()), "[online]", String.valueOf(count));
// We now need to get all online "members" of the island - incl. Trusted and coop
List<UUID> onlineMembers = island.getMemberSet(RanksManager.COOP_RANK).stream()
.filter(uuid -> Util.getOnlinePlayerList(user).contains(Bukkit.getOfflinePlayer(uuid).getName())).toList();
// We now need to get all online "members" of the island - incl. Trusted and
// coop
List<UUID> onlineMembers = island.getMemberSet(RanksManager.COOP_RANK).stream()
.filter(uuid -> Util.getOnlinePlayerList(user).contains(Bukkit.getOfflinePlayer(uuid).getName()))
.toList();
for (int rank : ranks) {
Set<UUID> players = island.getMemberSet(rank, false);
if (!players.isEmpty()) {
if (rank == RanksManager.OWNER_RANK) {
// Slightly special handling for the owner rank
user.sendMessage("commands.island.team.info.rank-layout.owner",
TextVariables.RANK, user.getTranslation(RanksManager.OWNER_RANK_REF));
} else {
user.sendMessage("commands.island.team.info.rank-layout.generic",
TextVariables.RANK, user.getTranslation(getPlugin().getRanksManager().getRank(rank)),
TextVariables.NUMBER, String.valueOf(island.getMemberSet(rank, false).size()));
}
displayOnOffline(user, rank, island, onlineMembers);
}
}
}
for (int rank : ranks) {
Set<UUID> players = island.getMemberSet(rank, false);
if (!players.isEmpty()) {
if (rank == RanksManager.OWNER_RANK) {
// Slightly special handling for the owner rank
user.sendMessage("commands.island.team.info.rank-layout.owner", TextVariables.RANK,
user.getTranslation(RanksManager.OWNER_RANK_REF));
} else {
user.sendMessage("commands.island.team.info.rank-layout.generic", TextVariables.RANK,
user.getTranslation(getPlugin().getRanksManager().getRank(rank)), TextVariables.NUMBER,
String.valueOf(island.getMemberSet(rank, false).size()));
}
displayOnOffline(user, rank, island, onlineMembers);
}
}
}
private void displayOnOffline(User user, int rank, Island island, List<UUID> onlineMembers) {
for (UUID member : island.getMemberSet(rank, false)) {
OfflinePlayer offlineMember = Bukkit.getOfflinePlayer(member);
if (onlineMembers.contains(member)) {
// the player is online
user.sendMessage("commands.island.team.info.member-layout.online",
TextVariables.NAME, offlineMember.getName());
} else {
// A bit of handling for the last joined date
Instant lastJoined = Instant.ofEpochMilli(offlineMember.getLastPlayed());
Instant now = Instant.now();
private void displayOnOffline(User user, int rank, Island island, List<UUID> onlineMembers) {
for (UUID member : island.getMemberSet(rank, false)) {
OfflinePlayer offlineMember = Bukkit.getOfflinePlayer(member);
if (onlineMembers.contains(member)) {
// the player is online
user.sendMessage("commands.island.team.info.member-layout.online", TextVariables.NAME,
offlineMember.getName());
} else {
// A bit of handling for the last joined date
Instant lastJoined = Instant.ofEpochMilli(offlineMember.getLastPlayed());
Instant now = Instant.now();
Duration duration = Duration.between(lastJoined, now);
String lastSeen;
final String reference = "commands.island.team.info.last-seen.layout";
if (duration.toMinutes() < 60L) {
lastSeen = user.getTranslation(reference,
TextVariables.NUMBER, String.valueOf(duration.toMinutes()),
TextVariables.UNIT, user.getTranslation("commands.island.team.info.last-seen.minutes"));
} else if (duration.toHours() < 24L) {
lastSeen = user.getTranslation(reference,
TextVariables.NUMBER, String.valueOf(duration.toHours()),
TextVariables.UNIT, user.getTranslation("commands.island.team.info.last-seen.hours"));
} else {
lastSeen = user.getTranslation(reference,
TextVariables.NUMBER, String.valueOf(duration.toDays()),
TextVariables.UNIT, user.getTranslation("commands.island.team.info.last-seen.days"));
}
Duration duration = Duration.between(lastJoined, now);
String lastSeen;
final String reference = "commands.island.team.info.last-seen.layout";
if (duration.toMinutes() < 60L) {
lastSeen = user.getTranslation(reference, TextVariables.NUMBER,
String.valueOf(duration.toMinutes()), TextVariables.UNIT,
user.getTranslation("commands.island.team.info.last-seen.minutes"));
} else if (duration.toHours() < 24L) {
lastSeen = user.getTranslation(reference, TextVariables.NUMBER, String.valueOf(duration.toHours()),
TextVariables.UNIT, user.getTranslation("commands.island.team.info.last-seen.hours"));
} else {
lastSeen = user.getTranslation(reference, TextVariables.NUMBER, String.valueOf(duration.toDays()),
TextVariables.UNIT, user.getTranslation("commands.island.team.info.last-seen.days"));
}
if(island.getMemberSet(RanksManager.MEMBER_RANK, true).contains(member)) {
user.sendMessage("commands.island.team.info.member-layout.offline",
TextVariables.NAME, offlineMember.getName(),
"[last_seen]", lastSeen);
} else {
// This will prevent anyone that is trusted or below to not have a last-seen status
user.sendMessage("commands.island.team.info.member-layout.offline-not-last-seen",
TextVariables.NAME, offlineMember.getName());
}
}
}
if (island.getMemberSet(RanksManager.MEMBER_RANK, true).contains(member)) {
user.sendMessage("commands.island.team.info.member-layout.offline", TextVariables.NAME,
offlineMember.getName(), "[last_seen]", lastSeen);
} else {
// This will prevent anyone that is trusted or below to not have a last-seen
// status
user.sendMessage("commands.island.team.info.member-layout.offline-not-last-seen",
TextVariables.NAME, offlineMember.getName());
}
}
}
}
}
private boolean fireEvent(User user, Island island) {
IslandBaseEvent e = TeamEvent.builder()
.island(island)
.reason(TeamEvent.Reason.INFO)
.involvedPlayer(user.getUniqueId())
.build();
return e.getNewEvent().map(IslandBaseEvent::isCancelled)
.orElse(e.isCancelled());
}
private boolean fireEvent(User user, Island island) {
IslandBaseEvent e = TeamEvent.builder().island(island).reason(TeamEvent.Reason.INFO)
.involvedPlayer(user.getUniqueId()).build();
return e.getNewEvent().map(IslandBaseEvent::isCancelled).orElse(e.isCancelled());
}
/**
* Add an invite
* @param type - type of invite
* @param inviter - uuid of inviter
* @param invitee - uuid of invitee
* @since 1.8.0
*/
public void addInvite(Invite.Type type, @NonNull UUID inviter, @NonNull UUID invitee, @NonNull Island island) {
inviteMap.put(invitee, new Invite(type, inviter, invitee, island));
}
/**
* Add an invite
*
* @param type - type of invite
* @param inviter - uuid of inviter
* @param invitee - uuid of invitee
* @since 1.8.0
*/
public void addInvite(Invite.Type type, @NonNull UUID inviter, @NonNull UUID invitee, @NonNull Island island) {
inviteMap.put(invitee, new Invite(type, inviter, invitee, island));
}
/**
* Check if a player has been invited
* @param invitee - UUID of invitee to check
* @return true if invited, false if not
* @since 1.8.0
*/
public boolean isInvited(@NonNull UUID invitee) {
return inviteMap.containsKey(invitee);
}
/**
* Check if a player has been invited
*
* @param invitee - UUID of invitee to check
* @return true if invited, false if not
* @since 1.8.0
*/
public boolean isInvited(@NonNull UUID invitee) {
return inviteMap.containsKey(invitee);
}
/**
* Get whoever invited invitee
* @param invitee - uuid
* @return UUID of inviter, or null if invitee has not been invited
* @since 1.8.0
*/
@Nullable
public UUID getInviter(UUID invitee) {
return isInvited(invitee) ? inviteMap.get(invitee).getInviter() : null;
}
/**
* Get whoever invited invitee
*
* @param invitee - uuid
* @return UUID of inviter, or null if invitee has not been invited
* @since 1.8.0
*/
@Nullable
public UUID getInviter(UUID invitee) {
return isInvited(invitee) ? inviteMap.get(invitee).getInviter() : null;
}
/**
* Gets the invite for an invitee.
* @param invitee - UUID of invitee
* @return invite or null if none
* @since 1.8.0
*/
@Nullable
public Invite getInvite(UUID invitee) {
return inviteMap.get(invitee);
}
/**
* Gets the invite for an invitee.
*
* @param invitee - UUID of invitee
* @return invite or null if none
* @since 1.8.0
*/
@Nullable
public Invite getInvite(UUID invitee) {
return inviteMap.get(invitee);
}
/**
* Removes a pending invite.
* @param invitee - UUID of invited user
* @since 1.8.0
*/
public void removeInvite(@NonNull UUID invitee) {
inviteMap.remove(invitee);
}
/**
* Removes a pending invite.
*
* @param invitee - UUID of invited user
* @since 1.8.0
*/
public void removeInvite(@NonNull UUID invitee) {
inviteMap.remove(invitee);
}
}

View File

@ -23,118 +23,118 @@ import world.bentobox.bentobox.util.Util;
*/
public class IslandTeamCoopCommand extends CompositeCommand {
private final IslandTeamCommand itc;
private @Nullable UUID targetUUID;
private final IslandTeamCommand itc;
private @Nullable UUID targetUUID;
public IslandTeamCoopCommand(IslandTeamCommand parentCommand) {
super(parentCommand, "coop");
this.itc = parentCommand;
}
public IslandTeamCoopCommand(IslandTeamCommand parentCommand) {
super(parentCommand, "coop");
this.itc = parentCommand;
}
@Override
public void setup() {
setPermission("island.team.coop");
setOnlyPlayer(true);
setParametersHelp("commands.island.team.coop.parameters");
setDescription("commands.island.team.coop.description");
setConfigurableRankCommand();
}
@Override
public void setup() {
setPermission("island.team.coop");
setOnlyPlayer(true);
setParametersHelp("commands.island.team.coop.parameters");
setDescription("commands.island.team.coop.description");
setConfigurableRankCommand();
}
@Override
public boolean canExecute(User user, String label, List<String> args) {
if (args.size() != 1) {
// Show help
showHelp(this, user);
return false;
}
// Player issuing the command must have an island or be in a team
if (!getIslands().inTeam(getWorld(), user.getUniqueId())
&& !getIslands().hasIsland(getWorld(), user.getUniqueId())) {
user.sendMessage("general.errors.no-island");
return false;
}
// Check rank to use command
Island island = getIslands().getIsland(getWorld(), user);
int rank = Objects.requireNonNull(island).getRank(user);
if (rank < island.getRankCommand(getUsage())) {
user.sendMessage("general.errors.insufficient-rank", TextVariables.RANK,
user.getTranslation(getPlugin().getRanksManager().getRank(rank)));
return false;
}
// Get target player
targetUUID = getPlayers().getUUID(args.get(0));
if (targetUUID == null) {
user.sendMessage("general.errors.unknown-player", TextVariables.NAME, args.get(0));
return false;
}
// Check cooldown
if (getSettings().getCoopCooldown() > 0 && checkCooldown(user, island.getUniqueId(), targetUUID.toString())) {
return false;
}
// Player cannot coop themselves
if (user.getUniqueId().equals(targetUUID)) {
user.sendMessage("commands.island.team.coop.cannot-coop-yourself");
return false;
}
if (getIslands().getPrimaryIsland(getWorld(), user.getUniqueId()).getMemberSet(RanksManager.COOP_RANK)
.contains(targetUUID)) {
user.sendMessage("commands.island.team.coop.already-has-rank");
return false;
}
if (itc.isInvited(targetUUID) && user.getUniqueId().equals(itc.getInviter(targetUUID))
&& itc.getInvite(targetUUID) != null && itc.getInvite(targetUUID).getType().equals(Type.COOP)) {
// Prevent spam
user.sendMessage("commands.island.team.invite.errors.you-have-already-invited");
return false;
}
return true;
}
@Override
public boolean canExecute(User user, String label, List<String> args) {
if (args.size() != 1) {
// Show help
showHelp(this, user);
return false;
}
// Player issuing the command must have an island or be in a team
if (!getIslands().inTeam(getWorld(), user.getUniqueId())
&& !getIslands().hasIsland(getWorld(), user.getUniqueId())) {
user.sendMessage("general.errors.no-island");
return false;
}
// Check rank to use command
Island island = getIslands().getIsland(getWorld(), user);
int rank = Objects.requireNonNull(island).getRank(user);
if (rank < island.getRankCommand(getUsage())) {
user.sendMessage("general.errors.insufficient-rank", TextVariables.RANK,
user.getTranslation(getPlugin().getRanksManager().getRank(rank)));
return false;
}
// Get target player
targetUUID = getPlayers().getUUID(args.get(0));
if (targetUUID == null) {
user.sendMessage("general.errors.unknown-player", TextVariables.NAME, args.get(0));
return false;
}
// Check cooldown
if (getSettings().getCoopCooldown() > 0 && checkCooldown(user, island.getUniqueId(), targetUUID.toString())) {
return false;
}
// Player cannot coop themselves
if (user.getUniqueId().equals(targetUUID)) {
user.sendMessage("commands.island.team.coop.cannot-coop-yourself");
return false;
}
if (getIslands().getPrimaryIsland(getWorld(), user.getUniqueId()).getMemberSet(RanksManager.COOP_RANK)
.contains(targetUUID)) {
user.sendMessage("commands.island.team.coop.already-has-rank");
return false;
}
if (itc.isInvited(targetUUID) && user.getUniqueId().equals(itc.getInviter(targetUUID))
&& itc.getInvite(targetUUID) != null && itc.getInvite(targetUUID).getType().equals(Type.COOP)) {
// Prevent spam
user.sendMessage("commands.island.team.invite.errors.you-have-already-invited");
return false;
}
return true;
}
@Override
public boolean execute(User user, String label, List<String> args) {
User target = User.getInstance(targetUUID);
Island island = getIslands().getIsland(getWorld(), user.getUniqueId());
if (island != null) {
if (getPlugin().getSettings().isInviteConfirmation()) {
// Put the invited player (key) onto the list with inviter (value)
// If someone else has invited a player, then this invite will overwrite the
// previous invite!
itc.addInvite(Invite.Type.COOP, user.getUniqueId(), target.getUniqueId(), island);
user.sendMessage("commands.island.team.invite.invitation-sent", TextVariables.NAME, target.getName());
// Send message to online player
target.sendMessage("commands.island.team.coop.name-has-invited-you", TextVariables.NAME,
user.getName());
target.sendMessage("commands.island.team.invite.to-accept-or-reject", TextVariables.LABEL,
getTopLabel());
} else {
if (island.getMemberSet(RanksManager.COOP_RANK, false).size() >= getIslands().getMaxMembers(island,
RanksManager.COOP_RANK)) {
user.sendMessage("commands.island.team.coop.is-full");
return false;
}
@Override
public boolean execute(User user, String label, List<String> args) {
User target = User.getInstance(targetUUID);
Island island = getIslands().getIsland(getWorld(), user.getUniqueId());
if (island != null) {
if (getPlugin().getSettings().isInviteConfirmation()) {
// Put the invited player (key) onto the list with inviter (value)
// If someone else has invited a player, then this invite will overwrite the
// previous invite!
itc.addInvite(Invite.Type.COOP, user.getUniqueId(), target.getUniqueId(), island);
user.sendMessage("commands.island.team.invite.invitation-sent", TextVariables.NAME, target.getName());
// Send message to online player
target.sendMessage("commands.island.team.coop.name-has-invited-you", TextVariables.NAME,
user.getName());
target.sendMessage("commands.island.team.invite.to-accept-or-reject", TextVariables.LABEL,
getTopLabel());
} else {
if (island.getMemberSet(RanksManager.COOP_RANK, false).size() >= getIslands().getMaxMembers(island,
RanksManager.COOP_RANK)) {
user.sendMessage("commands.island.team.coop.is-full");
return false;
}
island.setRank(target, RanksManager.COOP_RANK);
user.sendMessage("commands.island.team.coop.success", TextVariables.NAME, target.getName(),
TextVariables.DISPLAY_NAME, target.getDisplayName());
target.sendMessage("commands.island.team.coop.you-are-a-coop-member", TextVariables.NAME,
user.getName(), TextVariables.DISPLAY_NAME, user.getDisplayName());
}
return true;
} else {
// Should not happen
user.sendMessage("general.errors.general");
return false;
}
}
island.setRank(target, RanksManager.COOP_RANK);
user.sendMessage("commands.island.team.coop.success", TextVariables.NAME, target.getName(),
TextVariables.DISPLAY_NAME, target.getDisplayName());
target.sendMessage("commands.island.team.coop.you-are-a-coop-member", TextVariables.NAME,
user.getName(), TextVariables.DISPLAY_NAME, user.getDisplayName());
}
return true;
} else {
// Should not happen
user.sendMessage("general.errors.general");
return false;
}
}
@Override
public Optional<List<String>> tabComplete(User user, String alias, List<String> args) {
String lastArg = !args.isEmpty() ? args.get(args.size() - 1) : "";
if (lastArg.isEmpty()) {
// Don't show every player on the server. Require at least the first letter
return Optional.empty();
}
return Optional.of(Util.tabLimit(Util.getOnlinePlayerList(user), lastArg));
}
@Override
public Optional<List<String>> tabComplete(User user, String alias, List<String> args) {
String lastArg = !args.isEmpty() ? args.get(args.size() - 1) : "";
if (lastArg.isEmpty()) {
// Don't show every player on the server. Require at least the first letter
return Optional.empty();
}
return Optional.of(Util.tabLimit(Util.getOnlinePlayerList(user), lastArg));
}
}

View File

@ -21,205 +21,205 @@ import world.bentobox.bentobox.util.Util;
*/
public class IslandTeamInviteAcceptCommand extends ConfirmableCommand {
private static final String INVALID_INVITE = "commands.island.team.invite.errors.invalid-invite";
private final IslandTeamCommand itc;
private UUID playerUUID;
private static final String INVALID_INVITE = "commands.island.team.invite.errors.invalid-invite";
private final IslandTeamCommand itc;
private UUID playerUUID;
public IslandTeamInviteAcceptCommand(IslandTeamCommand islandTeamCommand) {
super(islandTeamCommand, "accept");
this.itc = islandTeamCommand;
}
public IslandTeamInviteAcceptCommand(IslandTeamCommand islandTeamCommand) {
super(islandTeamCommand, "accept");
this.itc = islandTeamCommand;
}
@Override
public void setup() {
setPermission("island.team.accept");
setOnlyPlayer(true);
setDescription("commands.island.team.invite.accept.description");
}
@Override
public void setup() {
setPermission("island.team.accept");
setOnlyPlayer(true);
setDescription("commands.island.team.invite.accept.description");
}
@Override
public boolean canExecute(User user, String label, List<String> args) {
playerUUID = user.getUniqueId();
// Check if player has been invited
if (!itc.isInvited(playerUUID)) {
user.sendMessage("commands.island.team.invite.errors.none-invited-you");
return false;
}
// Get the island owner
UUID prospectiveOwnerUUID = itc.getInviter(playerUUID);
if (prospectiveOwnerUUID == null) {
user.sendMessage(INVALID_INVITE);
return false;
}
Invite invite = itc.getInvite(playerUUID);
if (invite.getType().equals(Type.TEAM)) {
// Check rank to of inviter
Island island = getIslands().getIsland(getWorld(), prospectiveOwnerUUID);
String inviteUsage = getParent().getSubCommand("invite").map(CompositeCommand::getUsage).orElse("");
if (island == null || island.getRank(prospectiveOwnerUUID) < island.getRankCommand(inviteUsage)) {
user.sendMessage(INVALID_INVITE);
itc.removeInvite(playerUUID);
return false;
}
@Override
public boolean canExecute(User user, String label, List<String> args) {
playerUUID = user.getUniqueId();
// Check if player has been invited
if (!itc.isInvited(playerUUID)) {
user.sendMessage("commands.island.team.invite.errors.none-invited-you");
return false;
}
// Get the island owner
UUID prospectiveOwnerUUID = itc.getInviter(playerUUID);
if (prospectiveOwnerUUID == null) {
user.sendMessage(INVALID_INVITE);
return false;
}
Invite invite = itc.getInvite(playerUUID);
if (invite.getType().equals(Type.TEAM)) {
// Check rank to of inviter
Island island = getIslands().getIsland(getWorld(), prospectiveOwnerUUID);
String inviteUsage = getParent().getSubCommand("invite").map(CompositeCommand::getUsage).orElse("");
if (island == null || island.getRank(prospectiveOwnerUUID) < island.getRankCommand(inviteUsage)) {
user.sendMessage(INVALID_INVITE);
itc.removeInvite(playerUUID);
return false;
}
// Check if player is already in a team
if (getIslands().inTeam(getWorld(), playerUUID)) {
user.sendMessage("commands.island.team.invite.errors.you-already-are-in-team");
return false;
}
// Fire event so add-ons can run commands, etc.
IslandBaseEvent e = TeamEvent.builder().island(getIslands().getIsland(getWorld(), prospectiveOwnerUUID))
.reason(TeamEvent.Reason.JOIN).involvedPlayer(playerUUID).build();
return !e.getNewEvent().map(IslandBaseEvent::isCancelled).orElse(e.isCancelled());
// Check if player is already in a team
if (getIslands().inTeam(getWorld(), playerUUID)) {
user.sendMessage("commands.island.team.invite.errors.you-already-are-in-team");
return false;
}
// Fire event so add-ons can run commands, etc.
IslandBaseEvent e = TeamEvent.builder().island(getIslands().getIsland(getWorld(), prospectiveOwnerUUID))
.reason(TeamEvent.Reason.JOIN).involvedPlayer(playerUUID).build();
return !e.getNewEvent().map(IslandBaseEvent::isCancelled).orElse(e.isCancelled());
}
return true;
}
}
return true;
}
@Override
public boolean execute(User user, String label, List<String> args) {
// Get the invite
Invite invite = itc.getInvite(playerUUID);
switch (invite.getType()) {
case COOP -> askConfirmation(user, () -> acceptCoopInvite(user, invite));
case TRUST -> askConfirmation(user, () -> acceptTrustInvite(user, invite));
default -> askConfirmation(user, user.getTranslation("commands.island.team.invite.accept.confirmation"),
() -> acceptTeamInvite(user, invite));
}
return true;
}
@Override
public boolean execute(User user, String label, List<String> args) {
// Get the invite
Invite invite = itc.getInvite(playerUUID);
switch (invite.getType()) {
case COOP -> askConfirmation(user, () -> acceptCoopInvite(user, invite));
case TRUST -> askConfirmation(user, () -> acceptTrustInvite(user, invite));
default -> askConfirmation(user, user.getTranslation("commands.island.team.invite.accept.confirmation"),
() -> acceptTeamInvite(user, invite));
}
return true;
}
private void acceptTrustInvite(User user, Invite invite) {
// Remove the invite
itc.removeInvite(playerUUID);
User inviter = User.getInstance(invite.getInviter());
Island island = invite.getIsland();
if (island != null) {
if (island.getMemberSet(RanksManager.TRUSTED_RANK, false).size() > getIslands().getMaxMembers(island,
RanksManager.TRUSTED_RANK)) {
user.sendMessage("commands.island.team.trust.is-full");
return;
}
island.setRank(user, RanksManager.TRUSTED_RANK);
IslandEvent.builder().island(island).involvedPlayer(user.getUniqueId()).admin(false)
.reason(IslandEvent.Reason.RANK_CHANGE).rankChange(island.getRank(user), RanksManager.TRUSTED_RANK)
.build();
if (inviter.isOnline()) {
inviter.sendMessage("commands.island.team.trust.success", TextVariables.NAME, user.getName(),
TextVariables.DISPLAY_NAME, user.getDisplayName());
}
if (inviter.isPlayer()) {
user.sendMessage("commands.island.team.trust.you-are-trusted", TextVariables.NAME, inviter.getName(),
TextVariables.DISPLAY_NAME, inviter.getDisplayName());
}
}
}
private void acceptTrustInvite(User user, Invite invite) {
// Remove the invite
itc.removeInvite(playerUUID);
User inviter = User.getInstance(invite.getInviter());
Island island = invite.getIsland();
if (island != null) {
if (island.getMemberSet(RanksManager.TRUSTED_RANK, false).size() > getIslands().getMaxMembers(island,
RanksManager.TRUSTED_RANK)) {
user.sendMessage("commands.island.team.trust.is-full");
return;
}
island.setRank(user, RanksManager.TRUSTED_RANK);
IslandEvent.builder().island(island).involvedPlayer(user.getUniqueId()).admin(false)
.reason(IslandEvent.Reason.RANK_CHANGE).rankChange(island.getRank(user), RanksManager.TRUSTED_RANK)
.build();
if (inviter.isOnline()) {
inviter.sendMessage("commands.island.team.trust.success", TextVariables.NAME, user.getName(),
TextVariables.DISPLAY_NAME, user.getDisplayName());
}
if (inviter.isPlayer()) {
user.sendMessage("commands.island.team.trust.you-are-trusted", TextVariables.NAME, inviter.getName(),
TextVariables.DISPLAY_NAME, inviter.getDisplayName());
}
}
}
private void acceptCoopInvite(User user, Invite invite) {
// Remove the invite
itc.removeInvite(playerUUID);
User inviter = User.getInstance(invite.getInviter());
Island island = invite.getIsland();
if (island != null) {
if (island.getMemberSet(RanksManager.COOP_RANK, false).size() > getIslands().getMaxMembers(island,
RanksManager.COOP_RANK)) {
user.sendMessage("commands.island.team.coop.is-full");
return;
}
island.setRank(user, RanksManager.COOP_RANK);
IslandEvent.builder().island(island).involvedPlayer(user.getUniqueId()).admin(false)
.reason(IslandEvent.Reason.RANK_CHANGE).rankChange(island.getRank(user), RanksManager.COOP_RANK)
.build();
if (inviter.isOnline()) {
inviter.sendMessage("commands.island.team.coop.success", TextVariables.NAME, user.getName(),
TextVariables.DISPLAY_NAME, user.getDisplayName());
}
if (inviter.isPlayer()) {
user.sendMessage("commands.island.team.coop.you-are-a-coop-member", TextVariables.NAME,
inviter.getName(), TextVariables.DISPLAY_NAME, inviter.getDisplayName());
}
}
}
private void acceptCoopInvite(User user, Invite invite) {
// Remove the invite
itc.removeInvite(playerUUID);
User inviter = User.getInstance(invite.getInviter());
Island island = invite.getIsland();
if (island != null) {
if (island.getMemberSet(RanksManager.COOP_RANK, false).size() > getIslands().getMaxMembers(island,
RanksManager.COOP_RANK)) {
user.sendMessage("commands.island.team.coop.is-full");
return;
}
island.setRank(user, RanksManager.COOP_RANK);
IslandEvent.builder().island(island).involvedPlayer(user.getUniqueId()).admin(false)
.reason(IslandEvent.Reason.RANK_CHANGE).rankChange(island.getRank(user), RanksManager.COOP_RANK)
.build();
if (inviter.isOnline()) {
inviter.sendMessage("commands.island.team.coop.success", TextVariables.NAME, user.getName(),
TextVariables.DISPLAY_NAME, user.getDisplayName());
}
if (inviter.isPlayer()) {
user.sendMessage("commands.island.team.coop.you-are-a-coop-member", TextVariables.NAME,
inviter.getName(), TextVariables.DISPLAY_NAME, inviter.getDisplayName());
}
}
}
private void acceptTeamInvite(User user, Invite invite) {
// Remove the invite
itc.removeInvite(playerUUID);
// Get the player's island - may be null if the player has no island
Set<Island> islands = getIslands().getIslands(getWorld(), playerUUID);
// Get the team's island
Island teamIsland = invite.getIsland();
if (teamIsland == null) {
user.sendMessage(INVALID_INVITE);
return;
}
if (teamIsland.getMemberSet(RanksManager.MEMBER_RANK, true).size() >= getIslands().getMaxMembers(teamIsland,
RanksManager.MEMBER_RANK)) {
user.sendMessage("commands.island.team.invite.errors.island-is-full");
return;
}
// Remove player as owner of the old island
getIslands().removePlayer(getWorld(), playerUUID);
// Remove money inventory etc. for leaving
cleanPlayer(user);
// Add the player as a team member of the new island
getIslands().setJoinTeam(teamIsland, playerUUID);
// Move player to team's island
getIslands().homeTeleportAsync(getWorld(), user.getPlayer()).thenRun(() -> {
// Delete the old islands
islands.forEach(island -> getIslands().deleteIsland(island, true, user.getUniqueId()));
private void acceptTeamInvite(User user, Invite invite) {
// Remove the invite
itc.removeInvite(playerUUID);
// Get the player's island - may be null if the player has no island
Set<Island> islands = getIslands().getIslands(getWorld(), playerUUID);
// Get the team's island
Island teamIsland = invite.getIsland();
if (teamIsland == null) {
user.sendMessage(INVALID_INVITE);
return;
}
if (teamIsland.getMemberSet(RanksManager.MEMBER_RANK, true).size() >= getIslands().getMaxMembers(teamIsland,
RanksManager.MEMBER_RANK)) {
user.sendMessage("commands.island.team.invite.errors.island-is-full");
return;
}
// Remove player as owner of the old island
getIslands().removePlayer(getWorld(), playerUUID);
// Remove money inventory etc. for leaving
cleanPlayer(user);
// Add the player as a team member of the new island
getIslands().setJoinTeam(teamIsland, playerUUID);
// Move player to team's island
getIslands().homeTeleportAsync(getWorld(), user.getPlayer()).thenRun(() -> {
// Delete the old islands
islands.forEach(island -> getIslands().deleteIsland(island, true, user.getUniqueId()));
// Put player back into normal mode
user.setGameMode(getIWM().getDefaultGameMode(getWorld()));
// Put player back into normal mode
user.setGameMode(getIWM().getDefaultGameMode(getWorld()));
// Execute commands
String ownerName = this.getPlayers().getName(teamIsland.getOwner());
Util.runCommands(user, ownerName, getIWM().getOnJoinCommands(getWorld()), "join");
// Execute commands
String ownerName = this.getPlayers().getName(teamIsland.getOwner());
Util.runCommands(user, ownerName, getIWM().getOnJoinCommands(getWorld()), "join");
});
// Reset deaths
if (getIWM().isTeamJoinDeathReset(getWorld())) {
getPlayers().setDeaths(getWorld(), playerUUID, 0);
}
user.sendMessage("commands.island.team.invite.accept.you-joined-island", TextVariables.LABEL, getTopLabel());
User inviter = User.getInstance(invite.getInviter());
if (inviter.isOnline()) {
inviter.sendMessage("commands.island.team.invite.accept.name-joined-your-island", TextVariables.NAME,
user.getName(), TextVariables.DISPLAY_NAME, user.getDisplayName());
}
getIslands().save(teamIsland);
// Fire event
TeamEvent.builder().island(teamIsland).reason(TeamEvent.Reason.JOINED).involvedPlayer(playerUUID).build();
IslandEvent.builder().island(teamIsland).involvedPlayer(user.getUniqueId()).admin(false)
.reason(IslandEvent.Reason.RANK_CHANGE).rankChange(teamIsland.getRank(user), RanksManager.MEMBER_RANK)
.build();
}
});
// Reset deaths
if (getIWM().isTeamJoinDeathReset(getWorld())) {
getPlayers().setDeaths(getWorld(), playerUUID, 0);
}
user.sendMessage("commands.island.team.invite.accept.you-joined-island", TextVariables.LABEL, getTopLabel());
User inviter = User.getInstance(invite.getInviter());
if (inviter.isOnline()) {
inviter.sendMessage("commands.island.team.invite.accept.name-joined-your-island", TextVariables.NAME,
user.getName(), TextVariables.DISPLAY_NAME, user.getDisplayName());
}
getIslands().save(teamIsland);
// Fire event
TeamEvent.builder().island(teamIsland).reason(TeamEvent.Reason.JOINED).involvedPlayer(playerUUID).build();
IslandEvent.builder().island(teamIsland).involvedPlayer(user.getUniqueId()).admin(false)
.reason(IslandEvent.Reason.RANK_CHANGE).rankChange(teamIsland.getRank(user), RanksManager.MEMBER_RANK)
.build();
}
private void cleanPlayer(User user) {
if (getIWM().isOnLeaveResetEnderChest(getWorld()) || getIWM().isOnJoinResetEnderChest(getWorld())) {
user.getPlayer().getEnderChest().clear();
}
if (getIWM().isOnLeaveResetInventory(getWorld()) || getIWM().isOnJoinResetInventory(getWorld())) {
user.getPlayer().getInventory().clear();
}
if (getSettings().isUseEconomy()
&& (getIWM().isOnLeaveResetMoney(getWorld()) || getIWM().isOnJoinResetMoney(getWorld()))) {
getPlugin().getVault().ifPresent(vault -> vault.withdraw(user, vault.getBalance(user)));
}
private void cleanPlayer(User user) {
if (getIWM().isOnLeaveResetEnderChest(getWorld()) || getIWM().isOnJoinResetEnderChest(getWorld())) {
user.getPlayer().getEnderChest().clear();
}
if (getIWM().isOnLeaveResetInventory(getWorld()) || getIWM().isOnJoinResetInventory(getWorld())) {
user.getPlayer().getInventory().clear();
}
if (getSettings().isUseEconomy()
&& (getIWM().isOnLeaveResetMoney(getWorld()) || getIWM().isOnJoinResetMoney(getWorld()))) {
getPlugin().getVault().ifPresent(vault -> vault.withdraw(user, vault.getBalance(user)));
}
// Reset the health
if (getIWM().isOnJoinResetHealth(getWorld())) {
Util.resetHealth(user.getPlayer());
}
// Reset the health
if (getIWM().isOnJoinResetHealth(getWorld())) {
Util.resetHealth(user.getPlayer());
}
// Reset the hunger
if (getIWM().isOnJoinResetHunger(getWorld())) {
user.getPlayer().setFoodLevel(20);
}
// Reset the hunger
if (getIWM().isOnJoinResetHunger(getWorld())) {
user.getPlayer().setFoodLevel(20);
}
// Reset the XP
if (getIWM().isOnJoinResetXP(getWorld())) {
user.getPlayer().setTotalExperience(0);
}
// Reset the XP
if (getIWM().isOnJoinResetXP(getWorld())) {
user.getPlayer().setTotalExperience(0);
}
}
}
}

Some files were not shown because too many files have changed in this diff Show More