Compare commits

...
Author SHA1 Message Date
benwoo1110 74089df9a1 Implement new GeneratorManager system. 2021-03-09 19:46:03 +08:00
Ben Woo e3f56f6498 Merge pull request #2586 from Multiverse/reflect-helper
Add ReflectHelper class to better facilitate various reflection actions.
2021-03-09 01:18:29 +08:00
Ben Woo bd0c3cff3f Merge pull request #2587 from Multiverse/player-desination
Player destination
2021-03-09 00:32:20 +08:00
Ben Woo 7c4ab035a0 Merge pull request #2588 from Multiverse/world-name-check
Implement new WorldNameChecker
2021-03-09 00:31:58 +08:00
Ben Woo 2593080f77 Merge pull request #2567 from Multiverse/player-utils
Add support to find players based on name, UUID or selectors.
2021-03-09 00:29:22 +08:00
benwoo1110 0d4595d511 Implement new WorldNameChecker for better preliminary checks of world name. 2021-03-08 18:03:35 +08:00
benwoo1110 bf820c2c27 Add getPlayerAwareDestination to DestinationFactory. 2021-03-08 17:09:03 +08:00
benwoo1110 a12718d354 Add ReflectHelper class to better facilitate various reflection actions. 2021-03-08 16:25:33 +08:00
Ben Woo 7c59dcbcb9 Merge pull request #2494 from benwoo1110/property-fix
Fix cannot remove block currency with mvm set command.
2021-03-04 15:32:34 +08:00
Ben Woo 15cacba7c9 Merge pull request #2573 from Multiverse/java-11
Fix compiling with Java 11+
2021-03-02 09:01:38 +08:00
Ben Woo adbe88daa6 Merge pull request #2565 from Multiverse/fis-respawn-anchor
Add respawn anchor support.
2021-03-02 00:36:43 +08:00
Kermina Awad 5350c012f7 fix compiling on java 15 2021-02-25 17:48:17 -05:00
benwoo1110 a91f377cf5 Fix compile on java 11. 2021-02-24 16:40:21 +08:00
Ben Woo c3ae5ac210 Merge pull request #2539 from Multiverse/disable_buscript
Add a Config Option to Disable Buscript
2021-02-24 14:12:35 +08:00
Ben Woo f4ce740c06 Merge pull request #2568 from Multiverse/fullname-face-direction
Add support for fullname face direction.
2021-02-24 14:09:56 +08:00
Kermina Awad 3ff8d34053 add config option to disable buscript 2021-02-23 14:38:54 -05:00
benwoo1110 f362f09380 Add support for fullname face direction.
So we can do `w:world:north` on top of the current ``w:world:n`.
2021-02-21 17:19:18 +08:00
benwoo1110 62b789dff5 Add support to find players based on name, UUID or selectors. 2021-02-21 16:47:13 +08:00
benwoo1110 84a9db597a Add respawn anchor support. 2021-02-19 00:57:19 +08:00
nicegamer7 89fd700e32 Merge pull request #2489 from benwoo1110/world-UID
Adds world UID and generator details to /mvinfo command
2021-01-17 12:36:27 -05:00
Ben Woo 001a6000f8 Merge pull request #2515 from Multiverse/update_bstats
Update bStats Metrics Class
2020-12-20 12:10:52 +08:00
Kermina Awad bf61069fed update bStats Metrics class 2020-12-19 22:17:04 -05:00
benwoo1110 48601e4215 Fix cannot remove block currency with mvm set command.
Setting currency to 0 is now considered as no currency value.
2020-11-27 21:14:27 +08:00
benwoo1110 ed77cacb1a Adds generator detail to /mvinfo command 2020-10-07 21:00:40 +08:00
benwoo1110 cfae997de4 Adds world UID to /mvinfo command 2020-10-07 00:39:08 +08:00
31 changed files with 1446 additions and 106 deletions

No files matched your search

+12 -6
View File
@@ -215,7 +215,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.1.1</version>
<version>3.2.4</version>
<executions>
<execution>
<phase>package</phase>
@@ -264,13 +264,19 @@
<plugin>
<groupId>se.eris</groupId>
<artifactId>notnull-instrumenter-maven-plugin</artifactId>
<version>0.6.8</version>
<version>1.0.0</version>
<executions>
<execution>
<goals>
<goal>instrument</goal>
<goal>tests-instrument</goal>
</goals>
<configuration>
<notNull>
<param>org.jetbrains.annotations.NotNull</param>
<param>javax.validation.constraints.NotNull</param>
</notNull>
</configuration>
</execution>
</executions>
</plugin>
@@ -319,7 +325,7 @@
<dependency>
<groupId>org.bstats</groupId>
<artifactId>bstats-bukkit</artifactId>
<version>1.7</version>
<version>1.8</version>
<exclusions>
<exclusion>
<groupId>org.bukkit</groupId>
@@ -353,21 +359,21 @@
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>2.0.0</version>
<version>2.0.9</version>
<type>jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-easymock</artifactId>
<version>2.0.0</version>
<version>2.0.9</version>
<type>jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>2.0.0</version>
<version>2.0.9</version>
<type>jar</type>
<scope>test</scope>
</dependency>
@@ -77,6 +77,8 @@ import com.onarandombox.MultiverseCore.destination.PlayerDestination;
import com.onarandombox.MultiverseCore.destination.WorldDestination;
import com.onarandombox.MultiverseCore.event.MVDebugModeEvent;
import com.onarandombox.MultiverseCore.event.MVVersionEvent;
import com.onarandombox.MultiverseCore.generators.GeneratorManager;
import com.onarandombox.MultiverseCore.api.MVGeneratorManager;
import com.onarandombox.MultiverseCore.listeners.MVAsyncPlayerChatListener;
import com.onarandombox.MultiverseCore.listeners.MVChatListener;
import com.onarandombox.MultiverseCore.listeners.MVEntityListener;
@@ -88,6 +90,7 @@ import com.onarandombox.MultiverseCore.listeners.MVWeatherListener;
import com.onarandombox.MultiverseCore.listeners.MVWorldInitListener;
import com.onarandombox.MultiverseCore.listeners.MVWorldListener;
import com.onarandombox.MultiverseCore.utils.AnchorManager;
import com.onarandombox.MultiverseCore.utils.CompatibilityLayer;
import com.onarandombox.MultiverseCore.utils.MVEconomist;
import com.onarandombox.MultiverseCore.utils.MVMessaging;
import com.onarandombox.MultiverseCore.utils.MVPermissions;
@@ -212,6 +215,7 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
// Configurations
private FileConfiguration multiverseConfig = null;
private MVGeneratorManager generatorManager;
private final MVWorldManager worldManager = new WorldManager(this);
// Setup the block/player/entity listener.
@@ -254,6 +258,8 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
// Setup our SafeTTeleporter
this.safeTTeleporter = new SimpleSafeTTeleporter(this);
this.unsafeCallWrapper = new UnsafeCallWrapper(this);
// Setup our CompatibilityLayer
CompatibilityLayer.init();
}
@@ -277,7 +283,7 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
this.messaging = new MVMessaging();
this.economist = new MVEconomist(this);
// Load the defaultWorldGenerators
this.worldManager.getDefaultWorldGenerators();
this.generatorManager = new GeneratorManager(this);
this.registerEvents();
// Setup Permissions, we'll do an initial check for the Permissions plugin then fall back on isOP().
@@ -353,13 +359,16 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
* Initializes the buscript javascript library.
*/
private void initializeBuscript() {
try {
buscript = new Buscript(this);
// Add global variable "multiverse" to javascript environment
buscript.setScriptVariable("multiverse", this);
} catch (NullPointerException e) {
buscript = null;
Logging.warning("Buscript failed to load! The script command will be disabled!");
buscript = null;
if (this.getMVConfig().getEnableBuscript()) {
try {
buscript = new Buscript(this);
// Add global variable "multiverse" to javascript environment
buscript.setScriptVariable("multiverse", this);
} catch (NullPointerException e) {
Logging.warning("Buscript failed to load! The script command will be disabled!");
}
}
}
@@ -1008,6 +1017,14 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
this.serverFolder = newServerFolder;
}
/**
* {@inheritDoc}
*/
@Override
public MVGeneratorManager getMVGeneratorManager() {
return generatorManager;
}
/**
* {@inheritDoc}
*/
@@ -56,6 +56,8 @@ public class MultiverseCoreConfiguration extends SerializationConfig implements
@Property
private volatile boolean displaypermerrors;
@Property
private volatile boolean enablebuscript;
@Property
private volatile int globaldebug;
@Property
private volatile boolean silentstart;
@@ -99,6 +101,7 @@ public class MultiverseCoreConfiguration extends SerializationConfig implements
teleportintercept = true;
firstspawnoverride = true;
displaypermerrors = true;
enablebuscript = true;
globaldebug = 0;
messagecooldown = 5000;
teleportcooldown = 1000;
@@ -213,6 +216,22 @@ public class MultiverseCoreConfiguration extends SerializationConfig implements
return this.displaypermerrors;
}
/**
* {@inheritDoc}
*/
@Override
public boolean getEnableBuscript() {
return this.enablebuscript;
}
/**
* {@inheritDoc}
*/
@Override
public void setEnableBuscript(boolean enableBuscript) {
this.enablebuscript = enableBuscript;
}
/**
* {@inheritDoc}
*/
@@ -94,6 +94,13 @@ public interface Core {
*/
DestinationFactory getDestFactory();
/**
* Gets the class responsible for managing world generators plugins installed on the server.
*
* @return A valid {@link MVGeneratorManager}.
*/
MVGeneratorManager getMVGeneratorManager();
/**
* Gets the primary class responsible for managing Multiverse Worlds.
*
@@ -0,0 +1,101 @@
package com.onarandombox.MultiverseCore.api;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
/**
* <p>A generator API for Multiverse.</p>
*
* <p>Any generator plugin can register themselves to Multiverse. This will provide Multiverse with addition
* information about your generator plugin such as generator id suggestions, example usages and link to more
* info on your generator plugin.</p>
*
* <p>To register your plugin, implement this class and see {@link MVGeneratorManager#register(GeneratorPlugin)}.</p>
*/
public interface GeneratorPlugin {
/**
* <p>Suggest possible generator ids. To be used in command tab-completion.</p>
*
* <p>These suggestions can be static without relying on currentIdInput, or dynamically changed based
* on the currentIdInput.</p>
*
* @param currentIdInput The current state user input. This may be null or empty if user has not started
* any input for generator id.
* @return Collection of suggested generator ids.
*/
@NotNull
Collection<String> suggestIds(@Nullable String currentIdInput);
/**
* <p>Gets a default or any valid {@link ChunkGenerator}.</p>
*
* <p>This is used on {@link MVGeneratorManager#register(GeneratorPlugin)} to prove to Multiverse that
* you are a valid generator plugin. If this returns null or throw an exception, your generator plugin
* will not be registered.</p>
*
* @return A {@link ChunkGenerator} if possible, else null.
* @throws Exception When an error occurs in getting {@link ChunkGenerator}.
*/
@Nullable
ChunkGenerator getDefaultChunkGenerator() throws Exception;
/**
* <p>Gets a chunk generator based on a world name and id specified.</p>
*
* <p>If this returns null or throw an exception, it will indicate to Multiverse that there is either an issue
* with your plugin, or the generator id given is invalid.</p>
*
* @param id Target generator id.
* @param worldName Target world name to use generator on.
* @return A {@link ChunkGenerator} if possible, else null.
* @throws Exception When an error occurs in getting a {@link ChunkGenerator}.
*/
@Nullable
ChunkGenerator getChunkGenerator(String id, String worldName) throws Exception;
/**
* <p>Gets command usages that users can try to generate a world with your generator plugin. Returning null means
* you do not wish to show any usage examples for your generator plugin.</p>
*
* <p>An example command: '/mv create myworld normal -g CoolGen:FunWorld'</p>
*
* <p>Notes on usage of this method:</p>
* <ul>
* <li>Feel free to have colors in your command usage, but not Multiverse won't parse color codes for you.</li>
* <li>Please include the starting slash '/' in your usage examples.</li>
* <li>We suggest keeping the usage to at most 5 examples.</li>
* <li>This should not be a full explanation on all your generator plugin, just basics usages to get people
* started. For full guide, you can use {@link #getInfoLink()} to direct users.</li>
* </ul>
*
* @return A collection of command usage examples.
*/
@Nullable
Collection<String> getExampleUsages();
/**
* <p>Gets a link with more information on your generator plugin. Returning null means you do not wish to link
* users to any website related to your generator plugin.</p>
*
* <p>An example info: 'Click on https://www.amazinggenerator.io ;)'</p>
*
* <p>Some suggested places you can link to are: spigot resource page, github repo or your own plugin site.</p>
*
* @return Link to more info on your generator plugin.
*/
@Nullable
String getInfoLink();
/**
* Gets the java plugin for this generator. In short, return your own generator plugin instance.
*
* @return The associated plugin for this generator.
*/
@NotNull
Plugin getPlugin();
}
@@ -0,0 +1,134 @@
package com.onarandombox.MultiverseCore.api;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.Map;
/**
* API for handling generator plugins installed on the user's server.
*/
public interface MVGeneratorManager {
/**
* Register a generator plugin.
*
* @param generatorPlugin The {@link GeneratorPlugin} to register.
* @return True if successfully registered, else false.
*/
boolean register(@NotNull GeneratorPlugin generatorPlugin);
/**
* Check if a given generator string is valid.
*
* @param genString The generator string to check on.
* @param worldName The target world name to generate on.
* @return True if valid, else false.
*/
boolean isValidGenerator(@NotNull String genString, @NotNull String worldName);
/**
* Check if a given generator string is valid with reason of failure with {@link TestResult}.
*
* @param genString The generator string to check on.
* @param worldName The target world name to generate on.
* @return Result of the validation.
*/
@NotNull
TestResult validateGenerator(@NotNull String genString, @NotNull String worldName);
/**
* Checks if a plugin is a registered generator plugin.
*
* @param genPlugin The plugin to check on.
* @return True if is valid, else false.
*/
boolean isGeneratorPlugin(@NotNull Plugin genPlugin);
/**
* Checks if a plugin is a registered generator plugin.
*
* @param pluginName The plugin name to check on.
* @return True if is valid, else false.
*/
boolean isGeneratorPlugin(@NotNull String pluginName);
/**
* Gets the {@link GeneratorPlugin} for a given plugin if present.
*
* @param genPlugin The plugin that is associated to a {@link GeneratorPlugin}.
* @return The {@link GeneratorPlugin} if present, else null.
*/
@Nullable
GeneratorPlugin getGeneratorPlugin(@NotNull Plugin genPlugin);
/**
* Gets the {@link GeneratorPlugin} for a given plugin if present.
*
* @param pluginName The plugin name that is associated to a {@link GeneratorPlugin}.
* @return The {@link GeneratorPlugin} if present, else null.
*/
@Nullable
GeneratorPlugin getGeneratorPlugin(@NotNull String pluginName);
/**
* Gets all registered {@link GeneratorPlugin}.
*
* @return A collection of registered generator plugins.
*/
@NotNull
Collection<GeneratorPlugin> getGeneratorPlugins();
/**
* Gets all registered plugin names associate with {@link GeneratorPlugin}.
*
* @return A collection of registered generator plugin names.
*/
@NotNull
Collection<String> getGeneratorPluginNames();
/**
* Gets the default world generator string defined in 'bukkit.yml' for a given world.
*
* @param worldName The world to get default generator of.
* @return The generator string if present, else null.
*/
@Nullable
String getDefaultWorldGen(String worldName);
/**
* Gets all the world generator strings defined in 'bukkit.yml'.
*
* @return Map if world names and its respective default world generator strings.
*/
@NotNull
Map<String, String> getDefaultWorldGens();
/**
* Results from validating a generator.
*/
enum TestResult {
/**
* Successfully got {@link ChunkGenerator} from the world generator plugin.
*/
VALID,
/**
* Exceptions thrown while trying to get {@link ChunkGenerator} from the world generator plugin.
*/
ERRORS,
/**
* Plugin is present on the server, but doesnt look like a world generator.
*/
INVALID_GENERATOR,
/**
* Plugin not installed on the server.
*/
PLUGIN_DOES_NOT_EXIST
}
}
@@ -7,6 +7,7 @@
package com.onarandombox.MultiverseCore.api;
import com.onarandombox.MultiverseCore.generators.GeneratorManager;
import com.onarandombox.MultiverseCore.utils.PurgeWorlds;
import com.onarandombox.MultiverseCore.utils.SimpleWorldPurger;
import org.bukkit.World;
@@ -154,7 +155,9 @@ public interface MVWorldManager {
* @param generatorID The generator id.
* @param worldName The worldName to use as the default.
* @return A {@link ChunkGenerator} or null
* @deprecated Use {@link MVGeneratorManager#validateGenerator(String, String)}
*/
@Deprecated
ChunkGenerator getChunkGenerator(String generator, String generatorID, String worldName);
/**
@@ -249,7 +252,9 @@ public interface MVWorldManager {
/**
* This method populates an internal list and needs to be called after multiverse initialization.
* @deprecated This is now done by {@link GeneratorManager}.
*/
@Deprecated
void getDefaultWorldGenerators();
/**
@@ -86,6 +86,18 @@ public interface MultiverseCoreConfig extends ConfigurationSerializable {
*/
boolean getDisplayPermErrors();
/**
* Sets enableBuscript.
* @param enableBuscript The new value.
*/
void setEnableBuscript(boolean enableBuscript);
/**
* Gets enableBuscript.
* @return enableBuscript.
*/
boolean getEnableBuscript();
/**
* Sets firstSpawnOverride.
* @param firstSpawnOverride The new value.
@@ -11,6 +11,7 @@ import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVDestination;
import com.onarandombox.MultiverseCore.destination.InvalidDestination;
import com.onarandombox.MultiverseCore.utils.MVPermissions;
import com.onarandombox.MultiverseCore.utils.PlayerFinder;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@@ -37,7 +38,7 @@ public class CheckCommand extends MultiverseCommand {
@Override
public void runCommand(CommandSender sender, List<String> args) {
Player p = this.plugin.getServer().getPlayerExact(args.get(0));
Player p = PlayerFinder.get(args.get(0), sender);
if (p == null) {
sender.sendMessage("Could not find player " + ChatColor.GREEN + args.get(0));
sender.sendMessage("Are they online?");
@@ -9,6 +9,7 @@ package com.onarandombox.MultiverseCore.commands;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.api.MVGeneratorManager;
import com.pneumaticraft.commandhandler.CommandHandler;
import org.bukkit.ChatColor;
import org.bukkit.World.Environment;
@@ -18,8 +19,6 @@ import org.bukkit.command.CommandSender;
import org.bukkit.permissions.PermissionDefault;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
@@ -98,14 +97,26 @@ public class CreateCommand extends MultiverseCommand {
}
// Determine if the generator is valid. #918
if (generator != null) {
List<String> genarray = new ArrayList<String>(Arrays.asList(generator.split(":")));
if (genarray.size() < 2) {
// If there was only one arg specified, pad with another empty one.
genarray.add("");
}
if (this.worldManager.getChunkGenerator(genarray.get(0), genarray.get(1), "test") == null) {
MVGeneratorManager.TestResult result = this.plugin.getMVGeneratorManager().validateGenerator(generator, worldName);
if (result != MVGeneratorManager.TestResult.VALID) {
// We have an invalid generator.
sender.sendMessage("Invalid generator! '" + generator + "'. " + ChatColor.RED + "Aborting world creation.");
switch (result) {
case ERRORS:
sender.sendMessage("An issue occurred while validating generator string '" + generator +
"'! This may indicate an issue with your generator plugin or an invalid generator id. Check console for errors!");
break;
case INVALID_GENERATOR:
sender.sendMessage("Invalid generator string '" + generator +
"'! The generator id you use is probably not supported by your generator plugin.");
break;
case PLUGIN_DOES_NOT_EXIST:
sender.sendMessage("That generator plugin is not installed on your server!");
break;
default:
sender.sendMessage("Invalid generator string '" + generator + "'!");
break;
}
sender.sendMessage(ChatColor.RED + "Aborting world creation...");
return;
}
}
@@ -9,12 +9,19 @@ package com.onarandombox.MultiverseCore.commands;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.GeneratorPlugin;
import com.onarandombox.MultiverseCore.generators.SimpleGeneratorPlugin;
import net.milkbowl.vault.chat.Chat;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.permissions.PermissionDefault;
import org.bukkit.plugin.Plugin;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
@@ -25,36 +32,70 @@ public class GeneratorCommand extends MultiverseCommand {
public GeneratorCommand(MultiverseCore plugin) {
super(plugin);
this.setName("World Information");
this.setCommandUsage("/mv generators");
this.setArgRange(0, 0);
this.setCommandUsage("/mv generators [plugin]");
this.setArgRange(0, 1);
this.addKey("mv generators");
this.addKey("mvgenerators");
this.addKey("mv gens");
this.addKey("mvgens");
this.addCommandExample("/mv generators");
this.setPermission("multiverse.core.generator", "Returns a list of Loaded Generator Plugins.", PermissionDefault.OP);
this.addCommandExample("/mv generators VoidGenerator");
this.setPermission("multiverse.core.generator", "Returns info of Loaded Generator Plugins.", PermissionDefault.OP);
}
@Override
public void runCommand(CommandSender sender, List<String> args) {
Logging.info("PLEASE IGNORE the 'Plugin X does not contain any generators' message below!");
Plugin[] plugins = this.plugin.getServer().getPluginManager().getPlugins();
List<String> generators = new ArrayList<String>();
for (Plugin p : plugins) {
if (p.isEnabled() && p.getDefaultWorldGenerator("world", "") != null) {
generators.add(p.getDescription().getName());
}
if (args.size() == 0) {
listKnownGenerators(sender);
return;
}
showGeneratorDetails(sender, args.get(0));
}
private void listKnownGenerators(CommandSender sender) {
sender.sendMessage(ChatColor.AQUA + "--- Loaded Generator Plugins ---");
String loadedGens = "";
StringBuilder loadedGens = new StringBuilder();
boolean altColor = false;
for (String s : generators) {
loadedGens += (altColor ? ChatColor.YELLOW : ChatColor.WHITE) + s + " ";
for (String s : this.plugin.getMVGeneratorManager().getGeneratorPluginNames()) {
loadedGens.append(altColor ? ChatColor.YELLOW : ChatColor.WHITE).append(s).append(' ');
altColor = !altColor;
}
if (loadedGens.length() == 0) {
loadedGens = ChatColor.RED + "No Generator Plugins found.";
loadedGens.append(ChatColor.RED).append("No Generator Plugins found.");
}
sender.sendMessage(loadedGens.toString());
}
private void showGeneratorDetails(CommandSender sender, String pluginName) {
Plugin genPlugin = Bukkit.getPluginManager().getPlugin(pluginName);
if (genPlugin == null) {
sender.sendMessage(ChatColor.RED + "You do not have a plugin named '"+ pluginName + "' on your server.");
return;
}
GeneratorPlugin generatorPlugin = this.plugin.getMVGeneratorManager().getGeneratorPlugin(genPlugin);
if (generatorPlugin == null) {
sender.sendMessage(ChatColor.RED + "'" + pluginName + "' does not look like a generator plugin.");
return;
}
sender.sendMessage(ChatColor.AQUA + "--- Info on " + generatorPlugin.getPlugin().getName() + " ---");
boolean hasAddInfo = false;
Collection<String> exampleUsages = generatorPlugin.getExampleUsages();
if (exampleUsages != null && exampleUsages.size() > 0) {
hasAddInfo = true;
sender.sendMessage("Usages:");
exampleUsages.forEach(sender::sendMessage);
}
String infoLink = generatorPlugin.getInfoLink();
if (infoLink != null) {
hasAddInfo = true;
sender.sendMessage("More Info: " + infoLink);
}
if (!hasAddInfo) {
sender.sendMessage(ChatColor.RED + "'" + pluginName + "' did not provide additional info to Multiverse.");
}
sender.sendMessage(loadedGens);
}
}
@@ -10,6 +10,7 @@ package com.onarandombox.MultiverseCore.commands;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.utils.WorldNameChecker;
import com.pneumaticraft.commandhandler.CommandHandler;
import org.bukkit.ChatColor;
import org.bukkit.World.Environment;
@@ -45,28 +46,6 @@ public class ImportCommand extends MultiverseCommand {
this.worldManager = this.plugin.getMVWorldManager();
}
/**
* A very basic check to see if a folder has a level.dat file.
* If it does, we can safely assume it's a world folder.
*
* @param worldFolder The File that may be a world.
* @return True if it looks like a world, false if not.
*/
private static boolean checkIfIsWorld(File worldFolder) {
if (worldFolder.isDirectory()) {
File[] files = worldFolder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File file, String name) {
return name.toLowerCase().endsWith(".dat");
}
});
if (files != null && files.length > 0) {
return true;
}
}
return false;
}
private String getPotentialWorlds() {
File worldFolder = this.plugin.getServer().getWorldContainer();
if (worldFolder == null) {
@@ -84,7 +63,7 @@ public class ImportCommand extends MultiverseCommand {
}
ChatColor currColor = ChatColor.WHITE;
for (File file : files) {
if (file.isDirectory() && checkIfIsWorld(file) && !worldStrings.contains(file.getName())) {
if (file.isDirectory() && WorldNameChecker.isValidWorldFolder(file) && !worldStrings.contains(file.getName())) {
worldList += currColor + file.getName() + " ";
if (currColor == ChatColor.WHITE) {
currColor = ChatColor.YELLOW;
@@ -152,7 +131,7 @@ public class ImportCommand extends MultiverseCommand {
String worldList = this.getPotentialWorlds();
sender.sendMessage("That world folder does not exist. These look like worlds to me:");
sender.sendMessage(worldList);
} else if (!checkIfIsWorld(worldFile)) {
} else if (!WorldNameChecker.isValidWorldFolder(worldFile)) {
sender.sendMessage(ChatColor.RED + "FAILED.");
sender.sendMessage(String.format("'%s' does not appear to be a world. It is lacking a .dat file.",
worldName));
@@ -115,6 +115,7 @@ public class InfoCommand extends MultiverseCommand {
FancyColorScheme colors = new FancyColorScheme(ChatColor.AQUA, ChatColor.AQUA, ChatColor.GOLD, ChatColor.WHITE);
message.add(new FancyHeader("General Info", colors));
message.add(new FancyMessage("World Name: ", world.getName(), colors));
message.add(new FancyMessage("World UID: ", world.getCBWorld().getUID().toString(), colors));
message.add(new FancyMessage("World Alias: ", world.getColoredWorldString(), colors));
message.add(new FancyMessage("Game Mode: ", world.getGameMode().toString(), colors));
message.add(new FancyMessage("Difficulty: ", world.getDifficulty().toString(), colors));
@@ -151,6 +152,7 @@ public class InfoCommand extends MultiverseCommand {
message = new ArrayList<FancyText>();
message.add(new FancyHeader("More World Settings", colors));
message.add(new FancyMessage("World Type: ", world.getWorldType().toString(), colors));
message.add(new FancyMessage("Generator: ", world.getGenerator(), colors));
message.add(new FancyMessage("Structures: ", world.getCBWorld().canGenerateStructures() + "", colors));
message.add(new FancyMessage("Weather: ", world.isWeatherEnabled() + "", colors));
message.add(new FancyMessage("Players will get hungry: ", world.getHunger() + "", colors));
@@ -9,6 +9,7 @@ package com.onarandombox.MultiverseCore.commands;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.utils.PlayerFinder;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
@@ -50,7 +51,7 @@ public class SpawnCommand extends MultiverseCommand {
sender.sendMessage("You don't have permission to teleport another player to spawn. (multiverse.core.spawn.other)");
return;
}
Player target = this.plugin.getServer().getPlayerExact(args.get(0));
Player target = PlayerFinder.get(args.get(0), sender);
if (target != null) {
target.sendMessage("Teleporting to this world's spawn...");
spawnAccurately(target);
@@ -18,6 +18,7 @@ import com.onarandombox.MultiverseCore.destination.WorldDestination;
import com.onarandombox.MultiverseCore.enums.TeleportResult;
import com.onarandombox.MultiverseCore.event.MVTeleportEvent;
import com.onarandombox.MultiverseCore.api.SafeTTeleporter;
import com.onarandombox.MultiverseCore.utils.PlayerFinder;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
@@ -28,7 +29,6 @@ import org.bukkit.permissions.PermissionDefault;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
/**
* Used to teleport players.
@@ -59,7 +59,7 @@ public class TeleportCommand extends MultiverseCommand {
String destinationName;
if (args.size() == 2) {
teleportee = this.plugin.getServer().getPlayerExact(args.get(0));
teleportee = PlayerFinder.get(args.get(0), sender);
if (teleportee == null) {
this.messaging.sendMessage(sender, String.format("Sorry, I couldn't find player: %s%s",
ChatColor.GOLD, args.get(0)), false);
@@ -75,22 +75,9 @@ public class TeleportCommand extends MultiverseCommand {
}
teleportee = (Player) sender;
}
// Special case for cannons:
if (destinationName.matches("(?i)cannon-[\\d]+(\\.[\\d]+)?")) {
String[] cannonSpeed = destinationName.split("-");
try {
double speed = Double.parseDouble(cannonSpeed[1]);
destinationName = "ca:" + teleportee.getWorld().getName() + ":" + teleportee.getLocation().getX()
+ "," + teleportee.getLocation().getY() + "," + teleportee.getLocation().getZ() + ":"
+ teleportee.getLocation().getPitch() + ":" + teleportee.getLocation().getYaw() + ":" + speed;
} catch (Exception e) {
destinationName = "i:invalid";
}
}
DestinationFactory df = this.plugin.getDestFactory();
MVDestination d = df.getDestination(destinationName);
MVDestination d = df.getPlayerAwareDestination(teleportee, destinationName);
MVTeleportEvent teleportEvent = new MVTeleportEvent(d, teleportee, teleporter, true);
this.plugin.getServer().getPluginManager().callEvent(teleportEvent);
@@ -64,6 +64,7 @@ public class VersionCommand extends MultiverseCommand {
+ "[Multiverse-Core] teleportintercept: " + plugin.getMVConfig().getTeleportIntercept() + '\n'
+ "[Multiverse-Core] firstspawnoverride: " + plugin.getMVConfig().getFirstSpawnOverride() + '\n'
+ "[Multiverse-Core] displaypermerrors: " + plugin.getMVConfig().getDisplayPermErrors() + '\n'
+ "[Multiverse-Core] enablebuscript: " + plugin.getMVConfig().getEnableBuscript() + '\n'
+ "[Multiverse-Core] globaldebug: " + plugin.getMVConfig().getGlobalDebug() + '\n'
+ "[Multiverse-Core] silentstart: " + plugin.getMVConfig().getSilentStart() + '\n'
+ "[Multiverse-Core] messagecooldown: " + plugin.getMessaging().getCooldown() + '\n'
@@ -22,6 +22,8 @@ public class EntryFee extends SerializationConfig {
@Nullable
private Material currency;
private final Material DISABLED_MATERIAL = Material.AIR;
public EntryFee() {
super();
}
@@ -51,6 +53,9 @@ public class EntryFee extends SerializationConfig {
*/
@Nullable
public Material getCurrency() {
if (currency == null || currency.equals(DISABLED_MATERIAL)) {
return null;
}
return currency;
}
@@ -11,16 +11,26 @@ import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVDestination;
import com.onarandombox.MultiverseCore.commands.TeleportCommand;
import com.onarandombox.MultiverseCore.utils.PermissionTools;
import com.onarandombox.MultiverseCore.utils.PlayerFinder;
import com.pneumaticraft.commandhandler.Command;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionDefault;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/** A factory class that will create destinations from specific strings. */
public class DestinationFactory {
private static final Pattern CANNON_PATTERN = Pattern.compile("(?i)cannon-[\\d]+(\\.[\\d]+)?");
private MultiverseCore plugin;
private Map<String, Class<? extends MVDestination>> destList;
private Command teleportCommand;
@@ -36,6 +46,59 @@ public class DestinationFactory {
}
}
/**
* Parse a destination that has relation to sender, such as a cannon or player destination.
*
* @param teleportee The player that is going to be teleported.
* @param destinationName The destination to parse.
* @return A non-null MVDestination
*/
@NotNull
public MVDestination getPlayerAwareDestination(@NotNull Player teleportee,
@NotNull String destinationName) {
// Prioritise world, in the event that a world is named after a player online.
if (Bukkit.getWorld(destinationName) != null) {
return getDestination(destinationName);
}
Player targetPlayer = PlayerFinder.get(destinationName, teleportee);
if (targetPlayer != null) {
return getDestination("pl:" + targetPlayer.getName());
}
if (CANNON_PATTERN.matcher(destinationName).matches()) {
return getDestination(parseCannonDest(teleportee, destinationName));
}
return getDestination(destinationName);
}
/**
* Parses a cannon destination.
*
* @param teleportee The player that is going to be teleported.
* @param destinationName The destination to parse.
* @return A destination string.
*/
@NotNull
private String parseCannonDest(@NotNull Player teleportee,
@NotNull String destinationName) {
String[] cannonSpeed = destinationName.split("-");
try {
double speed = Double.parseDouble(cannonSpeed[1]);
destinationName = "ca:" + teleportee.getWorld().getName() + ":" + teleportee.getLocation().getX()
+ "," + teleportee.getLocation().getY() + "," + teleportee.getLocation().getZ() + ":"
+ teleportee.getLocation().getPitch() + ":" + teleportee.getLocation().getYaw() + ":" + speed;
}
catch (Exception e) {
destinationName = "i:invalid";
}
return destinationName;
}
/**
* Gets a new destination from a string.
* Returns a new InvalidDestination if the string could not be parsed.
@@ -0,0 +1,7 @@
package com.onarandombox.MultiverseCore.enums;
public enum RespawnType {
BED,
ANCHOR,
OTHER
}
@@ -0,0 +1,311 @@
package com.onarandombox.MultiverseCore.generators;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.GeneratorPlugin;
import com.onarandombox.MultiverseCore.api.MVGeneratorManager;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
/**
* Default implementation of {@link MVGeneratorManager} to facilitate the detection and management of generator
* plugins installed on user's server.
*/
public class GeneratorManager implements MVGeneratorManager {
private final MultiverseCore plugin;
private final Map<String, String> defaultGens;
private Map<String, GeneratorPlugin> generatorPluginMap;
public GeneratorManager(MultiverseCore plugin) {
this.plugin = plugin;
this.defaultGens = new HashMap<>();
loadDefaultWorldGenerators();
findAndRegisterAllGeneratorPlugins();
Bukkit.getPluginManager().registerEvents(new GeneratorListener(), this.plugin);
}
/**
* Loads default generator strings defined in 'bukkit.yml'.
*/
private void loadDefaultWorldGenerators() {
this.generatorPluginMap = new HashMap<>();
File[] files = this.plugin.getServerFolder().listFiles((file, s) -> s.equalsIgnoreCase("bukkit.yml"));
if (files == null || files.length != 1) {
Logging.fine("Could not read 'bukkit.yml'. Any Default worldgenerators will not be loaded!");
return;
}
FileConfiguration bukkitConfig = YamlConfiguration.loadConfiguration(files[0]);
if (!bukkitConfig.isConfigurationSection("worlds")) {
Logging.fine("'bukkit.yml' missing worlds config section. No default generators found!");
return;
}
Set<String> keys = bukkitConfig.getConfigurationSection("worlds").getKeys(false);
for (String key : keys) {
this.defaultGens.put(key, bukkitConfig.getString("worlds." + key + ".generator", ""));
}
this.generatorPluginMap = Collections.unmodifiableMap(this.generatorPluginMap);
}
/**
* Register all generator plugins detected.
*/
private void findAndRegisterAllGeneratorPlugins() {
Arrays.stream(Bukkit.getPluginManager().getPlugins()).forEach(this::register);
}
/**
* Attempts to register a plugin as {@link SimpleGeneratorPlugin}.
*
* @param genPlugin The plugin to register.
* @return True if registered successfully, else false.
*/
private boolean register(@NotNull Plugin genPlugin) {
return this.register(genPlugin, SimpleGeneratorPlugin.DEFAULT_TEST_ID);
}
/**
* Attempts to register a plugin as {@link SimpleGeneratorPlugin}.
*
* @param genPlugin The plugin to register.
* @param id Generator Id to test for valid chunk generator.
* @return True if registered successfully, else false.
*/
private boolean register(@NotNull Plugin genPlugin, String id) {
Logging.finer("Attempting to register %s as a generator...", genPlugin.getName());
if (this.isGeneratorPlugin(genPlugin)) {
return false;
}
if (!simpleTestGen(genPlugin, id)) {
Logging.finer("%s is probably not a generator plugin!", genPlugin.getName());
return false;
}
this.generatorPluginMap.put(genPlugin.getName(), new SimpleGeneratorPlugin(genPlugin));
Logging.finer("Registered %s as a simple generator plugin.", genPlugin.getName());
return true;
}
/**
* Basic test to see if plugin is a valid generator.
*
* @param generator The potential generator plugin.
* @param id Generator Id to test for valid chunk generator.
* @return True if plugin is a valid generator, else false.
*/
private boolean simpleTestGen(@Nullable Plugin generator, String id) {
if (generator == null) {
return false;
}
// Since we are unsure if the plugin is even suppose to be a generator, we assume any error means its
// not a generator plugin.
try {
return generator.getDefaultWorldGenerator(SimpleGeneratorPlugin.TEST_WORLDNAME, id) != null;
} catch (Exception ignore) {
return false;
}
}
/**
* Unregisters a plugin.
*
* @param genPlugin The plugin to unregister.
* @return True if the plugin was present and now unregistered, else false.
*/
private boolean unregister(@NotNull Plugin genPlugin) {
return this.generatorPluginMap.remove(genPlugin.getName()) != null;
}
/**
* {@inheritDoc}
*/
@Override
public boolean register(@NotNull GeneratorPlugin generatorPlugin) {
Plugin genPlugin = generatorPlugin.getPlugin();
// Make sure not registered before.
GeneratorPlugin registeredGeneratorPlugin = this.getGeneratorPlugin(genPlugin);
if (registeredGeneratorPlugin != null) {
if (!(registeredGeneratorPlugin instanceof SimpleGeneratorPlugin)) {
throw new IllegalStateException("You cannot register plugin for '" + genPlugin.getName() + "' twice!");
}
// If it's auto registration by MV, we can remove in favour of the custom one.
this.unregister(genPlugin);
}
if (this.safelyTestGenerator(genPlugin, generatorPlugin::getDefaultChunkGenerator) != TestResult.VALID) {
return false;
}
this.generatorPluginMap.put(genPlugin.getName(), generatorPlugin);
Logging.fine("Registered %s as a simple generator plugin.", genPlugin.getName());
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isValidGenerator(@NotNull String genString, @NotNull String worldName) {
return validateGenerator(genString, worldName) == TestResult.VALID;
}
/**
* {@inheritDoc}
*/
@Override
@NotNull
public TestResult validateGenerator(@NotNull String genString, @NotNull String worldName) {
String[] genArray = genString.split(":", 2);
String pluginName = genArray[0];
String id = (genArray.length == 1) ? "" : genArray[1];
Plugin genPlugin = Bukkit.getPluginManager().getPlugin(pluginName);
if (genPlugin == null) {
return TestResult.PLUGIN_DOES_NOT_EXIST;
}
if (!this.isGeneratorPlugin(genPlugin)) {
// Tries to register again with specific Id defined.
if (!this.register(genPlugin, id)) {
return TestResult.INVALID_GENERATOR;
}
}
GeneratorPlugin generatorPlugin = this.getGeneratorPlugin(genPlugin);
if (generatorPlugin == null) {
return TestResult.INVALID_GENERATOR;
}
TestResult testResult = safelyTestGenerator(generatorPlugin.getPlugin(), () -> generatorPlugin.getChunkGenerator(id, worldName));
if (testResult == TestResult.VALID && generatorPlugin instanceof SimpleGeneratorPlugin) {
((SimpleGeneratorPlugin) generatorPlugin).addKnownWorkingId(id);
}
return testResult;
}
/**
* Tries to get chunk generator with wrapper to catch any exceptions that may occur.
*
* @param genPlugin The generator plugin.
* @param genGetter Logic to get the chunk generator.
* @return VALID if successfully got a not-null chunk generator, INVALID_GENERATOR if null,
* ERRORS if exception is thrown.
*/
@NotNull
private TestResult safelyTestGenerator(Plugin genPlugin, Callable<ChunkGenerator> genGetter) {
TestResult result = this.plugin.getUnsafeCallWrapper().wrap(
() -> genGetter.call() == null ? TestResult.INVALID_GENERATOR : TestResult.VALID,
genPlugin.getName(),
"Failed to get the chunk generator: %s"
);
return (result == null) ? TestResult.ERRORS : result;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isGeneratorPlugin(@NotNull Plugin genPlugin) {
return this.isGeneratorPlugin(genPlugin.getName());
}
/**
* {@inheritDoc}
*/
@Override
public boolean isGeneratorPlugin(@NotNull String pluginName) {
return this.generatorPluginMap.containsKey(pluginName);
}
/**
* {@inheritDoc}
*/
@Override
@Nullable
public GeneratorPlugin getGeneratorPlugin(@NotNull Plugin genPlugin) {
return this.getGeneratorPlugin(genPlugin.getName());
}
/**
* {@inheritDoc}
*/
@Override
@Nullable
public GeneratorPlugin getGeneratorPlugin(@NotNull String pluginName) {
return this.generatorPluginMap.get(pluginName);
}
/**
* {@inheritDoc}
*/
@Override
@NotNull
public Collection<GeneratorPlugin> getGeneratorPlugins() {
return this.generatorPluginMap.values();
}
/**
* {@inheritDoc}
*/
@Override
@NotNull
public Collection<String> getGeneratorPluginNames() {
return this.generatorPluginMap.keySet();
}
/**
* {@inheritDoc}
*/
@Override
@Nullable
public String getDefaultWorldGen(String worldName) {
return this.defaultGens.get(worldName);
}
/**
* {@inheritDoc}
*/
@Override
@NotNull
public Map<String, String> getDefaultWorldGens() {
return this.defaultGens;
}
/**
* Listen to when a plugin enables/disable to register and unregister accordingly.
*/
private class GeneratorListener implements Listener {
@EventHandler
public void onEnable(PluginEnableEvent event) {
register(event.getPlugin());
}
@EventHandler
public void onDisable(PluginDisableEvent event) {
unregister(event.getPlugin());
}
}
}
@@ -0,0 +1,94 @@
package com.onarandombox.MultiverseCore.generators;
import com.onarandombox.MultiverseCore.api.GeneratorPlugin;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* A default implementation of {@link GeneratorPlugin} for those generator plugins that do not provide their own
* custom {@link GeneratorPlugin} implementation to Multiverse.
*/
public class SimpleGeneratorPlugin implements GeneratorPlugin {
public static String TEST_WORLDNAME = "test";
public static String DEFAULT_TEST_ID = "";
private final Plugin plugin;
private final List<String> workingIds;
SimpleGeneratorPlugin(Plugin plugin) {
this(plugin, DEFAULT_TEST_ID);
}
SimpleGeneratorPlugin(Plugin plugin, String testedId) {
this.plugin = plugin;
this.workingIds = new ArrayList<>();
this.workingIds.add(testedId);
}
/**
* Adds a known generator id that was tested to be working.
*
* @param id The known working generator id.
*/
void addKnownWorkingId(String id) {
if (!this.workingIds.contains(id)) {
this.workingIds.add(id);
}
}
/**
* {@inheritDoc}
*/
@Override
public @NotNull Collection<String> suggestIds(@Nullable String currentIdInput) {
return this.workingIds;
}
/**
* {@inheritDoc}
*/
@Override
public @Nullable ChunkGenerator getDefaultChunkGenerator() throws Exception {
return this.plugin.getDefaultWorldGenerator(TEST_WORLDNAME, this.workingIds.get(0));
}
/**
* {@inheritDoc}
*/
@Override
public @Nullable ChunkGenerator getChunkGenerator(String id, String worldName) throws Exception {
return this.plugin.getDefaultWorldGenerator(worldName, id);
}
/**
* {@inheritDoc}
*/
@Override
public @Nullable Collection<String> getExampleUsages() {
return null;
}
/**
* {@inheritDoc}
* @return
*/
@Override
public @Nullable String getInfoLink() {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public @NotNull Plugin getPlugin() {
return this.plugin;
}
}
@@ -15,7 +15,9 @@ import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.enums.RespawnType;
import com.onarandombox.MultiverseCore.event.MVRespawnEvent;
import com.onarandombox.MultiverseCore.utils.CompatibilityLayer;
import com.onarandombox.MultiverseCore.utils.PermissionTools;
import org.bukkit.GameMode;
import org.bukkit.Location;
@@ -69,9 +71,16 @@ public class MVPlayerListener implements Listener {
return;
}
RespawnType respawnType = RespawnType.OTHER;
if (event.isBedSpawn()) {
respawnType = RespawnType.BED;
}
if (CompatibilityLayer.isAnchorSpawn(event)) {
respawnType = RespawnType.ANCHOR;
}
if (mvWorld.getBedRespawn() && event.isBedSpawn()) {
Logging.fine("Spawning " + event.getPlayer().getName() + " at their bed");
if (mvWorld.getBedRespawn() && (respawnType == RespawnType.BED || respawnType == RespawnType.ANCHOR)) {
Logging.fine("Spawning %s at their %s", event.getPlayer().getName(), respawnType);
return;
}
@@ -0,0 +1,46 @@
package com.onarandombox.MultiverseCore.utils;
import com.dumptruckman.minecraft.util.Logging;
import org.bukkit.Bukkit;
import org.bukkit.event.player.PlayerRespawnEvent;
import java.lang.reflect.Method;
/**
* A utility class to enable version specific minecraft features.
*/
public class CompatibilityLayer {
private static Method checkAnchorSpawn;
/**
* Initialise the reflection methods.
*/
public static void init() {
try {
checkAnchorSpawn = PlayerRespawnEvent.class.getDeclaredMethod("isAnchorSpawn");
} catch (NoSuchMethodException e) {
Logging.fine("%s does not support respawn anchors.", Bukkit.getVersion());
}
}
/**
* Check if the respawn point is of respawn anchor type.
* Introduced in minecraft 1.16
*
* @param event A player respawn event.
* @return If the respawn location is an anchor point.
*/
public static boolean isAnchorSpawn(PlayerRespawnEvent event) {
if (checkAnchorSpawn == null) {
return false;
}
try {
return (boolean) checkAnchorSpawn.invoke(event);
} catch (Exception e) {
Logging.warning("Error checking for: %s", checkAnchorSpawn);
e.printStackTrace();
}
return false;
}
}
@@ -0,0 +1,176 @@
package com.onarandombox.MultiverseCore.utils;
import com.dumptruckman.minecraft.util.Logging;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* Helper class to get {@link Player} from name, UUID or Selectors.
*/
public class PlayerFinder {
private static final Pattern UUID_REGEX = Pattern.compile("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[34][0-9a-fA-F]{3}-[89ab][0-9a-fA-F]{3}-[0-9a-fA-F]{12}");
private static final Pattern COMMA_SPLIT = Pattern.compile(",");
/**
* Get a {@link Player} based on an identifier of name UUID or selector.
*
* @param playerIdentifier An identifier of name UUID or selector.
* @param sender Target sender for selector.
* @return The player if found, else null.
*/
@Nullable
public static Player get(@NotNull String playerIdentifier,
@NotNull CommandSender sender) {
Player targetPlayer = getByName(playerIdentifier);
if (targetPlayer != null) {
return targetPlayer;
}
targetPlayer = getByUuid(playerIdentifier);
if (targetPlayer != null) {
return targetPlayer;
}
return getBySelector(playerIdentifier, sender);
}
/**
* Get multiple {@link Player} based on many identifiers of name UUID or selector.
*
* @param playerIdentifiers An identifier of multiple names, UUIDs or selectors, separated by comma.
* @param sender Target sender for selector.
* @return A list of all the {@link Player} found.
*/
@Nullable
public static List<Player> getMulti(@NotNull String playerIdentifiers,
@NotNull CommandSender sender) {
String[] playerIdentifierArray = COMMA_SPLIT.split(playerIdentifiers);
if (playerIdentifierArray == null || playerIdentifierArray.length == 0) {
return null;
}
List<Player> playerResults = new ArrayList<>();
for (String playerIdentifier : playerIdentifierArray) {
Player targetPlayer = getByName(playerIdentifier);
if (targetPlayer != null) {
playerResults.add(targetPlayer);
continue;
}
targetPlayer = getByUuid(playerIdentifier);
if (targetPlayer != null) {
playerResults.add(targetPlayer);
continue;
}
List<Player> targetPlayers = getMultiBySelector(playerIdentifier, sender);
if (targetPlayers != null) {
playerResults.addAll(targetPlayers);
}
}
return playerResults;
}
/**
* Get a {@link Player} based on player name.
*
* @param playerName Name of a {@link Player}.
* @return The player if found, else null.
*/
@Nullable
public static Player getByName(@NotNull String playerName) {
return Bukkit.getPlayerExact(playerName);
}
/**
* Get a {@link Player} based on player UUID.
*
* @param playerUuid UUID of a player.
* @return The player if found, else null.
*/
@Nullable
public static Player getByUuid(@NotNull String playerUuid) {
if (!UUID_REGEX.matcher(playerUuid).matches()) {
return null;
}
UUID uuid;
try {
uuid = UUID.fromString(playerUuid);
} catch (Exception e) {
return null;
}
return getByUuid(uuid);
}
/**
* Get a {@link Player} based on playerUUID.
*
* @param playerUuid UUID of a player.
* @return The player if found, else null.
*/
@Nullable
public static Player getByUuid(@NotNull UUID playerUuid) {
return Bukkit.getPlayer(playerUuid);
}
/**
* Get a {@link Player} based on vanilla selectors.
* https://minecraft.gamepedia.com/Commands#Target_selectors
*
* @param playerSelector A target selector, usually starts with an '@'.
* @param sender Target sender for selector.
* @return The player if only one found, else null.
*/
@Nullable
public static Player getBySelector(@NotNull String playerSelector,
@NotNull CommandSender sender) {
List<Player> matchedPlayers = getMultiBySelector(playerSelector, sender);
if (matchedPlayers == null || matchedPlayers.isEmpty()) {
Logging.warning("No player found with selector '%s' for %s.", playerSelector, sender.getName());
return null;
}
if (matchedPlayers.size() > 1) {
Logging.warning("Ambiguous selector result '%s' for %s (more than one player matched) - %s",
playerSelector, sender.getName(), matchedPlayers.toString());
return null;
}
return matchedPlayers.get(0);
}
/**
* Get multiple {@link Player} based on selector.
* https://minecraft.gamepedia.com/Commands#Target_selectors
*
* @param playerSelector A target selector, usually starts with an '@'.
* @param sender Target sender for selector.
* @return A list of all the {@link Player} found.
*/
@Nullable
public static List<Player> getMultiBySelector(@NotNull String playerSelector,
@NotNull CommandSender sender) {
if (playerSelector.charAt(0) != '@') {
return null;
}
try {
return Bukkit.selectEntities(sender, playerSelector).stream()
.filter(e -> e instanceof Player)
.map(e -> ((Player) e))
.collect(Collectors.toList());
} catch (IllegalArgumentException e) {
Logging.warning("An error occurred while parsing selector '%s' for %s. Is it is the correct format?",
playerSelector, sender.getName());
e.printStackTrace();
return null;
}
}
}
@@ -0,0 +1,140 @@
package com.onarandombox.MultiverseCore.utils;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* Utility class used to help in doing various reflection actions.
*/
public class ReflectHelper {
/**
* Try to get the {@link Class} based on its classpath.
*
* @param classPath The target classpath.
* @return A {@link Class} if found, else null.
*/
@Nullable
public static Class<?> getClass(String classPath) {
try {
return Class.forName(classPath);
} catch (ClassNotFoundException e) {
return null;
}
}
/**
* Check if the {@link Class} for a give classpath is present/valid.
*
* @param classPath Target classpath.
* @return True if class path is a valid class, else false.
*/
public static boolean hasClass(String classPath) {
return getClass(classPath) != null;
}
/**
* Try to get a {@link Method} from a given class.
*
* @param clazz The class to search the method on.
* @param methodName Name of the method to get.
* @param parameterTypes Parameters present for that method.
* @param <C> The class type.
* @return A {@link Method} if found, else null.
*/
@Nullable
public static <C> Method getMethod(Class<C> clazz, String methodName, Class<?>... parameterTypes) {
try {
Method method = clazz.getDeclaredMethod(methodName, parameterTypes);
method.setAccessible(true);
return method;
} catch (NoSuchMethodException e) {
return null;
}
}
/**
* Try to get a {@link Method} from a given class.
*
* @param classInstance Instance of the class to search the method on.
* @param methodName Name of the method to get.
* @param parameterTypes Parameters present for that method.
* @param <C> The class type.
* @return A {@link Method} if found, else null.
*/
@Nullable
public static <C> Method getMethod(C classInstance, String methodName, Class<?>... parameterTypes) {
return getMethod(classInstance.getClass(), methodName, parameterTypes);
}
/**
* Calls a {@link Method}.
*
* @param classInstance Instance of the class responsible for the method.
* @param method The method to call.
* @param parameters Parameters needed when calling the method.
* @param <C> The class type.
* @param <R> The return type.
* @return Return value of the method call if any, else null.
*/
@Nullable
public static <C, R> R invokeMethod(C classInstance, Method method, Object...parameters) {
try {
return (R) method.invoke(classInstance, parameters);
} catch (Exception e) {
return null;
}
}
/**
* Try to get a {@link Field} from a given class.
*
* @param clazz The class to search the field on.
* @param fieldName Name of the field to get.
* @param <C> The class type.
* @return A {@link Field} if found, else null.
*/
@Nullable
public static <C> Field getField(Class<C> clazz, String fieldName) {
try {
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
return field;
} catch (NoSuchFieldException e) {
return null;
}
}
/**
* Try to get a {@link Field} from a given class.
*
* @param classInstance Instance of the class to search the field on.
* @param fieldName Name of the field to get.
* @param <C> The class type.
* @return A {@link Field} if found, else null.
*/
@Nullable
public static <C> Field getField(C classInstance, String fieldName) {
return getField(classInstance.getClass(), fieldName);
}
/**
* Gets the value of an {@link Field} from an instance of the class responsible.
*
* @param classInstance Instance of the class to get the field value from.
* @param field The field to get value from.
* @param <C> The class type.
* @param <V> The field value type.
* @return The field value if any, else null.
*/
@Nullable
public static <C, V> V getFieldValue(C classInstance, Field field) {
try {
return (V) field.get(classInstance);
} catch (IllegalAccessException e) {
return null;
}
}
}
@@ -40,6 +40,15 @@ public class SimpleLocationManipulation implements LocationManipulation {
orientationInts.put("w", 90);
orientationInts.put("nw", 135);
orientationInts.put("north", 180);
orientationInts.put("northeast", 225);
orientationInts.put("east", 270);
orientationInts.put("southeast", 315);
orientationInts.put("south", 0);
orientationInts.put("southwest", 45);
orientationInts.put("west", 90);
orientationInts.put("northwest", 135);
// "freeze" the map:
ORIENTATION_INTS = Collections.unmodifiableMap(orientationInts);
// END CHECKSTYLE-SUPPRESSION: MagicNumberCheck
@@ -74,6 +74,7 @@ public class WorldManager implements MVWorldManager {
* {@inheritDoc}
*/
@Override
@Deprecated
public void getDefaultWorldGenerators() {
this.defaultGens = new HashMap<String, String>();
File[] files = this.plugin.getServerFolder().listFiles(new FilenameFilter() {
@@ -130,7 +131,7 @@ public class WorldManager implements MVWorldManager {
}
// Check for valid world name
if (!(isValidWorldName(oldName) && isValidWorldName(newName))) {
if (!(WorldNameChecker.isValidWorldName(oldName) && WorldNameChecker.isValidWorldName(oldName))) {
return false;
}
@@ -238,7 +239,9 @@ public class WorldManager implements MVWorldManager {
return false;
}
if (!isValidWorldName(name)) {
if (!WorldNameChecker.isValidWorldName(name)) {
Logging.warning("Invalid world name '" + name + "'");
Logging.warning("World name should not contain spaces or special characters!");
return false;
}
@@ -299,6 +302,7 @@ public class WorldManager implements MVWorldManager {
* {@inheritDoc}
*/
@Override
@Deprecated
public ChunkGenerator getChunkGenerator(String generator, final String generatorID, final String worldName) {
if (generator == null) {
return null;
@@ -424,21 +428,6 @@ public class WorldManager implements MVWorldManager {
}
}
/**
* Check if the world name is allowed
*
* @param name Name of the world
* @return True if the world world name is valid based on regex
*/
private boolean isValidWorldName(String name) {
if (!worldNamePattern.matcher(name).matches()) {
Logging.warning("Invalid world name '" + name + "'");
Logging.warning("World name should not contain spaces or special characters!");
return false;
}
return true;
}
private void brokenWorld(String name) {
Logging.severe("The world '" + name + "' could NOT be loaded because it contains errors and is probably corrupt!");
Logging.severe("Try using Minecraft Region Fixer to repair your world! '" + name + "'");
@@ -707,10 +696,7 @@ public class WorldManager implements MVWorldManager {
for (World w : myWorlds) {
String name = w.getName();
if (!worldsFromTheConfig.containsKey(name)) {
String generator = null;
if (this.defaultGens.containsKey(name)) {
generator = this.defaultGens.get(name);
}
String generator = this.plugin.getMVGeneratorManager().getDefaultWorldGen(name);
this.addWorld(name, w.getEnvironment(), String.valueOf(w.getSeed()), w.getWorldType(), w.canGenerateStructures(), generator);
}
}
@@ -0,0 +1,159 @@
package com.onarandombox.MultiverseCore.utils;
import org.bukkit.Bukkit;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;
/**
* <p>Utility class in helping to check the status of a world name and it's associated world folder.</p>
*
* <p>Note this is for preliminary checks and better command output. A valid result will suggest but not
* 100% determine that a world name can be created, loaded or imported.</p>
*/
public class WorldNameChecker {
private static final Pattern WORLD_NAME_PATTERN = Pattern.compile("[a-zA-Z0-9/._-]+");
private static final Set<String> BLACKLIST_NAMES = Collections.unmodifiableSet(new HashSet<String>() {{
add("plugins");
add("logs");
add("cache");
add("crash-reports");
}});
/**
* Checks if a world name is valid.
*
* @param worldName The world name to check on.
* @return True if check result is valid, else false.
*/
public static boolean isValidWorldName(@Nullable String worldName) {
return checkName(worldName) == NameStatus.VALID;
}
/**
* Checks the current validity status of a world name.
*
* @param worldName The world name to check on.
* @return The resulting name status.
*/
@NotNull
public static NameStatus checkName(@Nullable String worldName) {
if (BLACKLIST_NAMES.contains(worldName)) {
return NameStatus.BLACKLISTED;
}
if (worldName == null || !WORLD_NAME_PATTERN.matcher(worldName).matches()) {
return NameStatus.INVALID_CHARS;
}
return NameStatus.VALID;
}
/**
* Checks if a world name has a valid world folder.
*
* @param worldName The world name to check on.
* @return True if check result is valid, else false.
*/
public static boolean isValidWorldFolder(@Nullable String worldName) {
return checkFolder(worldName) == FolderStatus.VALID;
}
/**
* Checks if a world folder is valid.
*
* @param worldFolder The world folder to check on.
* @return True if check result is valid, else false.
*/
public static boolean isValidWorldFolder(@Nullable File worldFolder) {
return checkFolder(worldFolder) == FolderStatus.VALID;
}
/**
* Checks the current folder status for a world name.
*
* @param worldName The world name to check on.
* @return The resulting folder status.
*/
@NotNull
public static FolderStatus checkFolder(@Nullable String worldName) {
if (worldName == null) {
return FolderStatus.DOES_NOT_EXIST;
}
File worldFolder = new File(Bukkit.getWorldContainer(), worldName);
return checkFolder(worldFolder);
}
/**
* Checks the current folder status.
*
* @param worldFolder The world folder to check on.
* @return The resulting folder status.
*/
@NotNull
public static FolderStatus checkFolder(@Nullable File worldFolder) {
if (worldFolder == null || !worldFolder.exists() || !worldFolder.isDirectory()) {
return FolderStatus.DOES_NOT_EXIST;
}
if (!folderHasDat(worldFolder)) {
return FolderStatus.NOT_A_WORLD;
}
return FolderStatus.VALID;
}
/**
* A very basic check to see if a folder has a level.dat file. If it does, we can safely assume
* it's a world folder.
*
* @param worldFolder The File that may be a world.
* @return True if it looks like a world, else false.
*/
private static boolean folderHasDat(@NotNull File worldFolder) {
File[] files = worldFolder.listFiles((file, name) -> name.toLowerCase().endsWith(".dat"));
return files != null && files.length > 0;
}
/**
* Result after checking validity of world name.
*/
public enum NameStatus {
/**
* Name is valid.
*/
VALID,
/**
* Name not valid as it contains invalid characters.
*/
INVALID_CHARS,
/**
* Name not valid as it is deemed blacklisted.
*/
BLACKLISTED
}
/**
* Result after checking validity of world folder.
*/
public enum FolderStatus {
/**
* Folder is valid.
*/
VALID,
/**
* Folder exist, but contents in it doesnt look like a world.
*/
NOT_A_WORLD,
/**
* Folder does not exist.
*/
DOES_NOT_EXIST
}
}
@@ -50,6 +50,10 @@ public class TestEntryFeeConversion {
WorldProperties props = new WorldProperties(config);
assertNull(props.entryfee.getCurrency());
entryFee.put("currency", 0);
props = new WorldProperties(config);
assertNull(props.entryfee.getCurrency());
entryFee.put("currency", 1);
props = new WorldProperties(config);
assertEquals(Material.STONE, props.entryfee.getCurrency());
@@ -207,7 +207,7 @@ public class TestWorldStuff {
assertEquals(0, creator.getCore().getMVWorldManager().getMVWorlds().size());
// Verify
verify(mockCommandSender).sendMessage("Invalid generator! 'BogusGen'. " + ChatColor.RED + "Aborting world creation.");
verify(mockCommandSender).sendMessage("That generator plugin is not installed on your server!");
}
@Test
@@ -214,11 +214,18 @@ public class TestInstanceCreator {
serverfield.set(core, mockServer);
// Set buscript
Buscript buscript = PowerMockito.spy(new Buscript(core));
Buscript buscript;
Field buscriptfield = MultiverseCore.class.getDeclaredField("buscript");
buscriptfield.setAccessible(true);
try {
buscript = PowerMockito.spy(new Buscript(core));
when(buscript.getPlugin()).thenReturn(core);
} catch (NullPointerException e) {
buscript = null;
}
buscriptfield.set(core, buscript);
when(buscript.getPlugin()).thenReturn(core);
// Set worldManager
WorldManager wm = PowerMockito.spy(new WorldManager(core));