Compare commits

..
46 changed files with 419 additions and 1528 deletions

No files matched your search

-22
View File
@@ -1,22 +0,0 @@
name: Maven CI/CD
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build_and_test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up JDK 8
uses: actions/setup-java@v1
with:
java-version: 1.8
- name: Build with Maven
run: mvn -B package --file pom.xml
+6
View File
@@ -0,0 +1,6 @@
language: java
jdk:
- oraclejdk8
notifications:
email: false
dist: trusty
-6
View File
@@ -1,6 +0,0 @@
Copyright (c) 2011, The Multiverse Team All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the The Multiverse Team nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+4 -35
View File
@@ -1,43 +1,11 @@
![Multiverse 2](config/multiverse2-long.png)
[![Maven CI/CD](https://github.com/Multiverse/Multiverse-Core/actions/workflows/build.yml/badge.svg)](https://github.com/Multiverse/Multiverse-Core/actions/workflows/build.yml)
[![Release](https://img.shields.io/nexus/r/com.onarandombox.multiversecore/Multiverse-Core?label=release&server=https%3A%2F%2Frepo.onarandombox.com%2F)](https://dev.bukkit.org/projects/multiverse-core)
[![Dev builds](https://img.shields.io/nexus/s/com.onarandombox.multiversecore/Multiverse-Core?label=dev%20builds&server=http%3A%2F%2Frepo.onarandombox.com%2F)](https://ci.onarandombox.com/job/Multiverse-Core/)
[![Discord](https://img.shields.io/discord/325459248047980545?label=discord&logo=discord)](https://discord.gg/NZtfKky)
[![Support me on Patreon](https://img.shields.io/endpoint.svg?url=https%3A%2F%2Fshieldsio-patreon.vercel.app%2Fapi%3Fusername%3Ddumptruckman%26type%3Dpatrons&style=flat)](https://patreon.com/dumptruckman)
About
========
[Multiverse](https://dev.bukkit.org/projects/multiverse-core) was created at the dawn of Bukkit multiworld support. It has since then grown into a **complete world management solution!** Multiverse provides the easiest to use world management solution for your Minecraft server, big or small, and with great addons like [Portals](https://dev.bukkit.org/projects/multiverse-portals) and [NetherPortals](https://dev.bukkit.org/projects/multiverse-netherportals/), what's not to love!
<br><br>
Now it's time to create your very own Multiverse server, do check out our [Wiki](https://github.com/Multiverse/Multiverse-Core/wiki) and [Usage Guide](https://github.com/Multiverse/Multiverse-Core/wiki/Basics) to get started. Feel free to hop onto our [Discord](https://discord.gg/NZtfKky) if you have any question or just want to have a chat with us!
### Amazing sub-modules available:
* [Multiverse-NetherPortals](https://github.com/Multiverse/Multiverse-NetherPortals) -> Have separate nether and end worlds for each of your overworlds!
* [Multiverse-Portals](https://github.com/Multiverse/Multiverse-Portals) -> Make custom portals to go to any destination!
* [Multiverse-Inventories](https://github.com/Multiverse/Multiverse-Inventories) -> Have separated players stats and inventories per world or per group of worlds.
* [Multiverse-SignPortals](https://github.com/Multiverse/Multiverse-SignPortals) -> Signs as teleprompters!
Building
========
Simply build the source with maven:
```
$ mvn install
```
$ mvn install
More details are available on the [build instructions wiki page](https://github.com/Multiverse/Multiverse-Core/wiki/Building).
Contributing
=======
**Want to help improve Multiverse?** There are several ways you can support and contribute to the project.
* Take a look at our "Bug: Unconfirmed" issues, where you can find issues that need extra testing and investigation.
* Want others to love Multiverse too? You can join the [Multiverse Discord community](https://discord.gg/NZtfKky) and help others with issues and setup!
* A Multiverse guru? You can update our [Wiki](https://github.com/Multiverse/Multiverse-Core/wiki) with your latest tip, tricks and guides! The wiki open for all to edit and improve.
* Love coding? You could look at ["State: Open to PR"](https://github.com/Multiverse/Multiverse-Core/labels/State%3A%20Open%20to%20PR) and ["Resolution: Accepted"](https://github.com/Multiverse/Multiverse-Core/labels/Resolution%3A%20Accepted) issues. We're always happy to receive bug fixes and feature additions as [pull requests](https://www.freecodecamp.org/news/how-to-make-your-first-pull-request-on-github-3/).
* If you'd like to make a financial contribution to the project, do consider joining our [patreon](https://www.patreon.com/dumptruckman) or make a one-time donation [here](https://paypal.me/dumptruckman)!
Additionally, we would like to give a big thanks to everyone that has supported Multiverse over the years, as well as those in the years to come. Thank you!
License
=======
Copyright (c) 2011, The Multiverse Team All rights reserved.
@@ -45,3 +13,4 @@ Copyright (c) 2011, The Multiverse Team All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the The Multiverse Team nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+46 -14
View File
@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.onarandombox.multiversecore</groupId>
<artifactId>Multiverse-Core</artifactId>
<version>4.3.1</version>
<version>4.2.3-SNAPSHOT</version>
<name>Multiverse-Core</name>
<description>World Management Plugin</description>
<properties>
@@ -20,27 +20,31 @@
</repository>
<repository>
<id>onarandombox</id>
<url>https://repo.onarandombox.com/content/groups/public</url>
<url>http://repo.onarandombox.com/content/groups/public</url>
</repository>
<repository>
<id>spigot</id>
<url>https://hub.spigotmc.org/nexus/content/groups/public/</url>
</repository>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
<id>vault-repo</id>
<url>http://nexus.hc.to/content/repositories/pub_releases</url>
</repository>
<repository>
<id>minebench-repo</id>
<url>https://repo.minebench.de/</url>
</repository>
<repository>
<id>CodeMC</id>
<url>https://repo.codemc.org/repository/maven-public</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>doodleproject-repo</id>
<name>DoodleProject Maven 2 Repository</name>
<url>https://doodleproject.sourceforge.net/maven2/release</url>
<url>http://doodleproject.sourceforge.net/maven2/release</url>
<releases>
<enabled>true</enabled>
</releases>
@@ -49,7 +53,7 @@
<ciManagement>
<system>jenkins</system>
<url>https://ci.onarandombox.com</url>
<url>http://ci.onarandombox.com</url>
</ciManagement>
<!-- Profiles are used to detect whether this is a local or Jenkins build
@@ -154,6 +158,8 @@
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M3</version>
<configuration>
<parallel>methods</parallel>
<threadCount>10</threadCount>
<excludes>
<exclude>**/TestCommandSender.java</exclude>
<exclude>**/TestInstanceCreator.java</exclude>
@@ -217,7 +223,6 @@
<goal>shade</goal>
</goals>
<configuration>
<minimizeJar>true</minimizeJar>
<relocations>
<relocation>
<pattern>me.main__.util</pattern>
@@ -300,7 +305,7 @@
<!-- End of SerializationConfig Dependency -->
<!-- Start of Economy Dependency -->
<dependency>
<groupId>com.github.MilkBowl</groupId>
<groupId>net.milkbowl.vault</groupId>
<artifactId>VaultAPI</artifactId>
<version>1.7</version>
<scope>provided</scope>
@@ -320,7 +325,13 @@
<dependency>
<groupId>org.bstats</groupId>
<artifactId>bstats-bukkit</artifactId>
<version>2.2.1</version>
<version>1.8</version>
<exclusions>
<exclusion>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.dumptruckman.minecraft</groupId>
@@ -346,9 +357,30 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.11.2</version>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<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.9</version>
<type>jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>2.0.9</version>
<type>jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
<version>4.0.2</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -361,11 +393,11 @@
<distributionManagement>
<repository>
<id>OnARandomBox</id>
<url>https://repo.onarandombox.com/content/repositories/multiverse</url>
<url>http://repo.onarandombox.com/content/repositories/multiverse</url>
</repository>
<snapshotRepository>
<id>OnARandomBox</id>
<url>https://repo.onarandombox.com/content/repositories/multiverse-snapshots/</url>
<url>http://repo.onarandombox.com/content/repositories/multiverse-snapshots/</url>
</snapshotRepository>
</distributionManagement>
</project>
@@ -68,7 +68,6 @@ import com.onarandombox.MultiverseCore.commands.TeleportCommand;
import com.onarandombox.MultiverseCore.commands.UnloadCommand;
import com.onarandombox.MultiverseCore.commands.VersionCommand;
import com.onarandombox.MultiverseCore.commands.WhoCommand;
import com.onarandombox.MultiverseCore.commandtools.queue.CommandQueueManager;
import com.onarandombox.MultiverseCore.destination.AnchorDestination;
import com.onarandombox.MultiverseCore.destination.BedDestination;
import com.onarandombox.MultiverseCore.destination.CannonDestination;
@@ -205,7 +204,6 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
// Setup our Map for our Commands using the CommandHandler.
private CommandHandler commandHandler;
private CommandQueueManager commandQueueManager;
private static final String LOG_TAG = "[Multiverse-Core]";
@@ -290,7 +288,6 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
// Setup the command manager
this.commandHandler = new CommandHandler(this, this.ph);
this.commandQueueManager = new CommandQueueManager(this);
// Call the Function to assign all the Commands to their Class.
this.registerCommands();
@@ -367,9 +364,7 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
// 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! " +
"If you would like not to see this message, " +
"use `/mv conf enablebuscript false` to disable Buscript from loading.");
Logging.warning("Buscript failed to load! The script command will be disabled!");
}
}
}
@@ -922,15 +917,6 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
return this.commandHandler;
}
/**
* {@inheritDoc}
*/
@Override
@Deprecated
public CommandQueueManager getCommandQueueManager() {
return commandQueueManager;
}
/**
* Gets the log-tag.
*
@@ -1131,22 +1117,12 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
/**
* {@inheritDoc}
* @deprecated This is deprecated! Do not use!
* @deprecated This is deprecated!
*/
@Override
@Deprecated
public Boolean regenWorld(String name, Boolean useNewSeed, Boolean randomSeed, String seed) {
return this.worldManager.regenWorld(name, useNewSeed, randomSeed, seed, false);
}
/**
* {@inheritDoc}
* @deprecated This is deprecated! Do not use!
*/
@Override
@Deprecated
public Boolean regenWorld(String name, Boolean useNewSeed, Boolean randomSeed, String seed, Boolean keepGameRules) {
return this.worldManager.regenWorld(name, useNewSeed, randomSeed, seed, keepGameRules);
return this.worldManager.regenWorld(name, useNewSeed, randomSeed, seed);
}
/**
@@ -96,7 +96,7 @@ public class MultiverseCoreConfiguration extends SerializationConfig implements
// BEGIN CHECKSTYLE-SUPPRESSION: MagicNumberCheck
enforceaccess = false;
useasyncchat = true;
prefixchat = false;
prefixchat = true;
prefixchatformat = "[%world%]%chat%";
teleportintercept = true;
firstspawnoverride = true;
@@ -107,7 +107,7 @@ public class MultiverseCoreConfiguration extends SerializationConfig implements
teleportcooldown = 1000;
this.version = 2.9;
silentstart = false;
defaultportalsearch = true;
defaultportalsearch = false;
portalsearchradius = 128;
autopurge = true;
idonotwanttodonate = false;
@@ -8,7 +8,6 @@
package com.onarandombox.MultiverseCore.api;
import buscript.Buscript;
import com.onarandombox.MultiverseCore.commandtools.queue.CommandQueueManager;
import com.onarandombox.MultiverseCore.destination.DestinationFactory;
import com.onarandombox.MultiverseCore.utils.AnchorManager;
import com.onarandombox.MultiverseCore.utils.MVEconomist;
@@ -87,15 +86,6 @@ public interface Core {
*/
CommandHandler getCommandHandler();
/**
* Manager for command that requires /mv confirm before execution.
*
* @return A non-null {@link CommandQueueManager}.
* @deprecated To be moved to new command manager in 5.0.0
*/
@Deprecated
CommandQueueManager getCommandQueueManager();
/**
* Gets the factory class responsible for loading many different destinations
* on demand.
@@ -126,38 +116,20 @@ public interface Core {
AnchorManager getAnchorManager();
/**
* Previously used by queued commands to regenerate a world on a delay.
* Do not use api method for any other purpose.
* Used by queued commands to regenerate a world on a delay.
*
* @param name Name of the world to regenerate
* @param useNewSeed If a new seed should be used
* @param randomSeed If the new seed should be random
* @param seed The seed of the world.
* @param name Name of the world to regenerate
* @param useNewSeed If a new seed should be used
* @param randomSeed IF the new seed should be random
* @param seed The seed of the world.
*
* @return True if success, false if fail.
*
* @deprecated Use {@link MVWorldManager#regenWorld(String, boolean, boolean, String, boolean)} instead.
* @deprecated Use {@link MVWorldManager#regenWorld(String, boolean, boolean, String)} instead.
*/
@Deprecated
Boolean regenWorld(String name, Boolean useNewSeed, Boolean randomSeed, String seed);
/**
* Used by queued commands to regenerate a world on a delay.
* Do not use api method for any other purpose.
*
* @param name Name of the world to regenerate
* @param useNewSeed If a new seed should be used
* @param randomSeed If the new seed should be random
* @param seed The seed of the world.
* @param keepGameRules If GameRules should be kept on world regen.
*
* @return True if success, false if fail.
*
* @deprecated Use {@link MVWorldManager#regenWorld(String, boolean, boolean, String, boolean)} instead.
*/
@Deprecated
Boolean regenWorld(String name, Boolean useNewSeed, Boolean randomSeed, String seed, Boolean keepGameRules);
/**
* Decrements the number of plugins that have specifically hooked into core.
*/
@@ -174,16 +174,6 @@ public interface MVWorldManager {
*/
MultiverseWorld getMVWorld(String name);
/**
* Returns a {@link MultiverseWorld} if the world with name given exists, and null if it does not.
* This will search optionally for alias names.
*
* @param name The name or optionally the alias of the world to get.
* @param checkAliases Indicates whether to check for world alias name.
* @return A {@link MultiverseWorld} or null.
*/
MultiverseWorld getMVWorld(String name, boolean checkAliases);
/**
* Returns a {@link MultiverseWorld} if it exists, and null if it does not.
*
@@ -193,24 +183,13 @@ public interface MVWorldManager {
MultiverseWorld getMVWorld(World world);
/**
* Checks to see if the given name is a valid {@link MultiverseWorld}
* Searches based on world name AND alias.
* Checks to see if the given name is a valid {@link MultiverseWorld}.
*
* @param name The name or alias of the world to check.
* @return True if the world exists, false if not.
*/
boolean isMVWorld(String name);
/**
* Checks to see if the given name is a valid {@link MultiverseWorld}.
* Optionally searches by alias is specified.
*
* @param name The name or alias of the world to check.
* @param checkAliases Indicates whether to check for world alias name.
* @return True if the world exists, false if not.
*/
boolean isMVWorld(String name, boolean checkAliases);
/**
* Checks to see if the given world is a valid {@link MultiverseWorld}.
*
@@ -313,28 +292,15 @@ public interface MVWorldManager {
/**
* Regenerates a world.
*
* @param name Name of the world to regenerate
* @param useNewSeed If a new seed should be used
* @param randomSeed If the new seed should be random
* @param seed The seed of the world.
* @param name Name of the world to regenerate
* @param useNewSeed If a new seed should be used
* @param randomSeed IF the new seed should be random
* @param seed The seed of the world.
*
* @return True if success, false if fail.
*/
boolean regenWorld(String name, boolean useNewSeed, boolean randomSeed, String seed);
/**
* Regenerates a world.
*
* @param name Name of the world to regenerate
* @param useNewSeed If a new seed should be used
* @param randomSeed If the new seed should be random
* @param seed The seed of the world.
* @param keepGameRules If GameRules should be kept on world regen.
*
* @return True if success, false if fail.
*/
boolean regenWorld(String name, boolean useNewSeed, boolean randomSeed, String seed, boolean keepGameRules);
boolean isKeepingSpawnInMemory(World world);
/**
@@ -348,11 +314,4 @@ public interface MVWorldManager {
* does not exist. {@code includeLoaded} if the world exists and is loaded.
*/
boolean hasUnloadedWorld(String name, boolean includeLoaded);
/**
* Get all the possible worlds that Multiverse has detected to be importable.
*
* @return A collection of world names that are deemed importable.
*/
Collection<String> getPotentialWorlds();
}
@@ -11,7 +11,6 @@ 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;
@@ -38,7 +37,7 @@ public class CheckCommand extends MultiverseCommand {
@Override
public void runCommand(CommandSender sender, List<String> args) {
Player p = PlayerFinder.get(args.get(0), sender);
Player p = this.plugin.getServer().getPlayerExact(args.get(0));
if (p == null) {
sender.sendMessage("Could not find player " + ChatColor.GREEN + args.get(0));
sender.sendMessage("Are they online?");
@@ -33,7 +33,7 @@ public class ConfirmCommand extends MultiverseCommand {
@Override
public void runCommand(CommandSender sender, List<String> args) {
this.plugin.getCommandQueueManager().runQueuedCommand(sender);
this.plugin.getCommandHandler().confirmQueuedCommand(sender);
}
}
@@ -46,15 +46,10 @@ public class CreateCommand extends MultiverseCommand {
this.addCommandExample("/mv create " + ChatColor.GOLD + "moonworld" + ChatColor.GREEN + " normal" + ChatColor.DARK_AQUA + " -g BukkitFullOfMoon");
this.worldManager = this.plugin.getMVWorldManager();
}
private String trimWorldName(String userInput) {
// Removes relative paths.
return userInput.replaceAll("^[./\\\\]+", "");
}
@Override
public void runCommand(CommandSender sender, List<String> args) {
String worldName = trimWorldName(args.get(0));
String worldName = args.get(0);
File worldFile = new File(this.plugin.getServer().getWorldContainer(), worldName);
String env = args.get(1);
String seed = CommandHandler.getFlag("-s", args);
@@ -71,13 +66,7 @@ public class CreateCommand extends MultiverseCommand {
useSpawnAdjust = false;
}
}
// Make sure the world name doesn't contain the words 'plugins' and '.dat'
if(worldName.contains("plugins")||worldName.contains(".dat")){
sender.sendMessage(ChatColor.RED + "Multiverse cannot create a world that contains 'plugins' or '.dat'");
return;
}
if (this.worldManager.isMVWorld(worldName)) {
sender.sendMessage(ChatColor.RED + "Multiverse cannot create " + ChatColor.GOLD + ChatColor.UNDERLINE
+ "another" + ChatColor.RESET + ChatColor.RED + " world named " + worldName);
@@ -128,4 +117,4 @@ public class CreateCommand extends MultiverseCommand {
Command.broadcastCommandMessage(sender, "FAILED.");
}
}
}
}
@@ -8,11 +8,9 @@
package com.onarandombox.MultiverseCore.commands;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.commandtools.queue.QueuedCommand;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.PermissionDefault;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
@@ -37,24 +35,11 @@ public class DeleteCommand extends MultiverseCommand {
public void runCommand(CommandSender sender, List<String> args) {
String worldName = args.get(0);
this.plugin.getCommandQueueManager().addToQueue(new QueuedCommand(
sender,
deleteRunnable(sender, worldName),
String.format("Are you sure you want to delete world '%s'? You cannot undo this action.", worldName)
));
}
private Runnable deleteRunnable(@NotNull CommandSender sender,
@NotNull String worldName) {
return () -> {
sender.sendMessage(String.format("Deleting world '%s'...", worldName));
if (this.plugin.getMVWorldManager().deleteWorld(worldName)) {
sender.sendMessage(String.format("%sWorld %s was deleted!", ChatColor.GREEN, worldName));
return;
}
sender.sendMessage(String.format("%sThere was an issue deleting '%s'! Please check console for errors.",
ChatColor.RED, worldName));
};
Class<?>[] paramTypes = {String.class};
List<Object> objectArgs = new ArrayList<Object>(args);
this.plugin.getCommandHandler()
.queueCommand(sender, "mvdelete", "deleteWorld", objectArgs,
paramTypes, ChatColor.GREEN + "World '" + worldName + "' Deleted!",
ChatColor.RED + "World '" + worldName + "' could NOT be deleted!");
}
}
@@ -40,16 +40,24 @@ public class HelpCommand extends PaginatedCoreCommand<Command> {
@Override
protected List<Command> getFilteredItems(List<Command> availableItems, String filter) {
String expression = "(?i).*" + cleanFilter(filter) + ".*";
List<Command> filtered = new ArrayList<Command>();
for (Command c : availableItems) {
if (stitchThisString(c.getKeyStrings()).matches(expression)
|| c.getCommandName().matches(expression)
|| c.getCommandDesc().matches(expression)
|| c.getCommandUsage().matches(expression)
|| c.getCommandExamples().stream().anyMatch(eg -> eg.matches(expression))) {
if (stitchThisString(c.getKeyStrings()).matches("(?i).*" + filter + ".*")) {
filtered.add(c);
} else if (c.getCommandName().matches("(?i).*" + filter + ".*")) {
filtered.add(c);
} else if (c.getCommandDesc().matches("(?i).*" + filter + ".*")) {
filtered.add(c);
} else if (c.getCommandUsage().matches("(?i).*" + filter + ".*")) {
filtered.add(c);
} else {
for (String example : c.getCommandExamples()) {
if (example.matches("(?i).*" + filter + ".*")) {
filtered.add(c);
break;
}
}
}
}
return filtered;
@@ -9,7 +9,7 @@ package com.onarandombox.MultiverseCore.commands;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.utils.WorldNameChecker;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.pneumaticraft.commandhandler.CommandHandler;
import org.bukkit.ChatColor;
import org.bukkit.World.Environment;
@@ -18,6 +18,8 @@ import org.bukkit.command.CommandSender;
import org.bukkit.permissions.PermissionDefault;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@@ -43,17 +45,55 @@ public class ImportCommand extends MultiverseCommand {
this.worldManager = this.plugin.getMVWorldManager();
}
private String getPotentialWorldStrings() {
final Collection<String> potentialWorlds = this.worldManager.getPotentialWorlds();
StringBuilder worldList = new StringBuilder();
ChatColor currColor = ChatColor.WHITE;
for (String world : potentialWorlds) {
worldList.append(currColor).append(world).append(' ');
currColor = currColor == ChatColor.WHITE ? ChatColor.YELLOW : ChatColor.WHITE;
/**
* 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;
}
return worldList.toString();
private String getPotentialWorlds() {
File worldFolder = this.plugin.getServer().getWorldContainer();
if (worldFolder == null) {
return "";
}
File[] files = worldFolder.listFiles();
String worldList = "";
Collection<MultiverseWorld> worlds = this.worldManager.getMVWorlds();
List<String> worldStrings = new ArrayList<String>();
for (MultiverseWorld world : worlds) {
worldStrings.add(world.getName());
}
for (String world : this.worldManager.getUnloadedWorlds()) {
worldStrings.add(world);
}
ChatColor currColor = ChatColor.WHITE;
for (File file : files) {
if (file.isDirectory() && checkIfIsWorld(file) && !worldStrings.contains(file.getName())) {
worldList += currColor + file.getName() + " ";
if (currColor == ChatColor.WHITE) {
currColor = ChatColor.YELLOW;
} else {
currColor = ChatColor.WHITE;
}
}
}
return worldList;
}
private String trimWorldName(String userInput) {
@@ -66,7 +106,7 @@ public class ImportCommand extends MultiverseCommand {
String worldName = trimWorldName(args.get(0));
if (worldName.toLowerCase().equals("--list") || worldName.toLowerCase().equals("-l")) {
String worldList = this.getPotentialWorldStrings();
String worldList = this.getPotentialWorlds();
if (worldList.length() > 2) {
sender.sendMessage(ChatColor.AQUA + "====[ These look like worlds ]====");
sender.sendMessage(worldList);
@@ -81,12 +121,6 @@ public class ImportCommand extends MultiverseCommand {
this.showHelp(sender);
return;
}
// Make sure the world name doesn't contain the words 'plugins' and '.dat'
if(worldName.contains("plugins")||worldName.contains(".dat")){
sender.sendMessage(ChatColor.RED + "Multiverse cannot create a world that contains 'plugins' or '.dat'");
return;
}
// Make sure we don't already know about this world.
if (this.worldManager.isMVWorld(worldName)) {
@@ -115,10 +149,10 @@ public class ImportCommand extends MultiverseCommand {
if (!worldFile.exists()) {
sender.sendMessage(ChatColor.RED + "FAILED.");
String worldList = this.getPotentialWorldStrings();
String worldList = this.getPotentialWorlds();
sender.sendMessage("That world folder does not exist. These look like worlds to me:");
sender.sendMessage(worldList);
} else if (!WorldNameChecker.isValidWorldFolder(worldFile)) {
} else if (!checkIfIsWorld(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));
@@ -134,4 +168,4 @@ public class ImportCommand extends MultiverseCommand {
Command.broadcastCommandMessage(sender, ChatColor.RED + "Failed!");
}
}
}
}
@@ -13,14 +13,12 @@ import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.List;
import java.util.regex.Pattern;
/**
* A generic paginated command.
* @param <T> The type of items on the page.
*/
public abstract class PaginatedCommand<T> extends Command {
private final Pattern REGEX_SPECIAL_CHARS = Pattern.compile("[.+*?\\[^\\]$(){}=!<>|:-\\\\]");
private static final int DEFAULT_ITEMS_PER_PAGE = 9;
/**
* The number of items per page.
@@ -42,23 +40,12 @@ public abstract class PaginatedCommand<T> extends Command {
/**
* Gets filtered items.
*
* @param availableItems All available items.
* @param filter The filter-{@link String}.
* @return A list of items that match the filter.
*/
protected abstract List<T> getFilteredItems(List<T> availableItems, String filter);
/**
* Escape regex special characters from filter
*
* @param filter The filter-{@link String}.
* @return String with regex characters escaped
*/
protected String cleanFilter(String filter) {
return REGEX_SPECIAL_CHARS.matcher(filter).replaceAll("\\\\$0");
}
/**
* Constructs a single string from a list of strings.
*
@@ -8,13 +8,11 @@
package com.onarandombox.MultiverseCore.commands;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.commandtools.queue.QueuedCommand;
import com.pneumaticraft.commandhandler.CommandHandler;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.PermissionDefault;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
/**
@@ -25,8 +23,8 @@ public class RegenCommand extends MultiverseCommand {
public RegenCommand(MultiverseCore plugin) {
super(plugin);
this.setName("Regenerates a World");
this.setCommandUsage("/mv regen" + ChatColor.GREEN + " {WORLD}" + ChatColor.GOLD + " [-s [SEED]] [--keep-gamerules]");
this.setArgRange(1, 4);
this.setCommandUsage("/mv regen" + ChatColor.GREEN + " {WORLD}" + ChatColor.GOLD + " [-s [SEED]]");
this.setArgRange(1, 3);
this.addKey("mvregen");
this.addKey("mv regen");
this.addCommandExample("You can use the -s with no args to get a new seed:");
@@ -39,31 +37,17 @@ public class RegenCommand extends MultiverseCommand {
@Override
public void runCommand(CommandSender sender, List<String> args) {
String worldName = args.get(0);
boolean useseed = (!(args.size() == 1));
boolean randomseed = (args.size() == 2 && args.get(1).equalsIgnoreCase("-s"));
Boolean useseed = (!(args.size() == 1));
Boolean randomseed = (args.size() == 2 && args.get(1).equalsIgnoreCase("-s"));
String seed = (args.size() == 3) ? args.get(2) : "";
boolean keepGamerules = CommandHandler.hasFlag("--keep-gamerules", args);
this.plugin.getCommandQueueManager().addToQueue(new QueuedCommand(
sender,
doWorldRegen(sender, worldName, useseed, randomseed, seed, keepGamerules),
String.format("Are you sure you want to regen '%s'? You cannot undo this action.", worldName)
));
}
private Runnable doWorldRegen(@NotNull CommandSender sender,
@NotNull String worldName,
boolean useSeed,
boolean randomSeed,
@NotNull String seed,
boolean keepGamerules) {
return () -> {
if (this.plugin.getMVWorldManager().regenWorld(worldName, useSeed, randomSeed, seed, keepGamerules)) {
sender.sendMessage(ChatColor.GREEN + "World Regenerated!");
return;
}
sender.sendMessage(ChatColor.RED + "World could NOT be regenerated!");
};
Class<?>[] paramTypes = {String.class, Boolean.class, Boolean.class, String.class};
List<Object> objectArgs = new ArrayList<Object>();
objectArgs.add(args.get(0));
objectArgs.add(useseed);
objectArgs.add(randomseed);
objectArgs.add(seed);
this.plugin.getCommandHandler().queueCommand(sender, "mvregen", "regenWorld", objectArgs,
paramTypes, ChatColor.GREEN + "World Regenerated!", ChatColor.RED + "World could NOT be regenerated!");
}
}
@@ -9,7 +9,6 @@ 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;
@@ -51,7 +50,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 = PlayerFinder.get(args.get(0), sender);
Player target = this.plugin.getServer().getPlayerExact(args.get(0));
if (target != null) {
target.sendMessage("Teleporting to this world's spawn...");
spawnAccurately(target);
@@ -11,7 +11,6 @@ import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.Teleporter;
import com.onarandombox.MultiverseCore.api.MVDestination;
import com.onarandombox.MultiverseCore.commandtools.queue.QueuedCommand;
import com.onarandombox.MultiverseCore.destination.CustomTeleporterDestination;
import com.onarandombox.MultiverseCore.destination.DestinationFactory;
import com.onarandombox.MultiverseCore.destination.InvalidDestination;
@@ -19,7 +18,6 @@ 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;
@@ -30,6 +28,7 @@ import org.bukkit.permissions.PermissionDefault;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
/**
* Used to teleport players.
@@ -60,7 +59,7 @@ public class TeleportCommand extends MultiverseCommand {
String destinationName;
if (args.size() == 2) {
teleportee = PlayerFinder.get(args.get(0), sender);
teleportee = this.plugin.getServer().getPlayerExact(args.get(0));
if (teleportee == null) {
this.messaging.sendMessage(sender, String.format("Sorry, I couldn't find player: %s%s",
ChatColor.GOLD, args.get(0)), false);
@@ -76,9 +75,22 @@ 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.getPlayerAwareDestination(teleportee, destinationName);
MVDestination d = df.getDestination(destinationName);
MVTeleportEvent teleportEvent = new MVTeleportEvent(d, teleportee, teleporter, true);
this.plugin.getServer().getPluginManager().callEvent(teleportEvent);
@@ -153,27 +165,24 @@ public class TeleportCommand extends MultiverseCommand {
if (result == TeleportResult.FAIL_UNSAFE) {
Logging.fine("Could not teleport " + teleportee.getName()
+ " to " + plugin.getLocationManipulation().strCoordsRaw(d.getLocation(teleportee)));
Logging.fine("Queueing Command");
Class<?>[] paramTypes = { CommandSender.class, Player.class, Location.class };
List<Object> items = new ArrayList<Object>();
items.add(teleporter);
items.add(teleportee);
items.add(d.getLocation(teleportee));
String player = "you";
if (!teleportee.equals(teleporter)) {
player = teleportee.getName();
}
this.plugin.getCommandQueueManager().addToQueue(new QueuedCommand(
sender,
doUnsafeTeleport(teleporter, teleportee, d.getLocation(teleportee)),
String.format("%sMultiverse %sdid not teleport %s%s %sto %s%s %sbecause it was unsafe. Would you like to try anyway?",
ChatColor.GREEN, ChatColor.WHITE, ChatColor.AQUA, player, ChatColor.WHITE, ChatColor.DARK_AQUA, d.getName(), ChatColor.WHITE),
UNSAFE_TELEPORT_EXPIRE_DELAY
));
String message = String.format("%sMultiverse %sdid not teleport %s%s %sto %s%s %sbecause it was unsafe.",
ChatColor.GREEN, ChatColor.WHITE, ChatColor.AQUA, player, ChatColor.WHITE, ChatColor.DARK_AQUA, d.getName(), ChatColor.WHITE);
this.plugin.getCommandHandler().queueCommand(sender, "mvteleport", "teleportPlayer", items,
paramTypes, message, "Would you like to try anyway?", "", "", UNSAFE_TELEPORT_EXPIRE_DELAY);
}
// else: Player was teleported successfully (or the tp event was fired I should say)
}
private Runnable doUnsafeTeleport(CommandSender teleporter, Player player, Location location) {
return () -> this.plugin.getSafeTTeleporter().safelyTeleport(teleporter, player, location, false);
}
private boolean checkSendPermissions(CommandSender teleporter, Player teleportee, MVDestination destination) {
if (teleporter.equals(teleportee)) {
if (!this.plugin.getMVPerms().hasPermission(teleporter, "multiverse.teleport.self." + destination.getIdentifier(), true)) {
@@ -45,11 +45,8 @@ public class VersionCommand extends MultiverseCommand {
this.addKey("mvver");
this.addKey("mvv");
this.addKey("mvversion");
this.setPermission(
"multiverse.core.version",
"Dumps version info to the console, optionally to pastebin.com with -b, to hastebin.com using -h, or to paste.gg with -p.",
PermissionDefault.OP)
;
this.setPermission("multiverse.core.version",
"Dumps version info to the console, optionally to pastebin.com with -b, to hastebin.com using -h, or to paste.gg with -p.", PermissionDefault.TRUE);
}
private String getLegacyString() {
@@ -1,161 +0,0 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2020. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.commandtools.queue;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.MultiverseCore;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.block.data.type.CommandBlock;
import org.bukkit.command.BlockCommandSender;
import org.bukkit.command.CommandSender;
import org.bukkit.scheduler.BukkitTask;
import org.jetbrains.annotations.NotNull;
import java.util.Map;
import java.util.WeakHashMap;
/**
* <p>Manages the queuing of dangerous commands that require {@code /mv confirm} before executing.</p>
*
* <p>Each sender can only have one command in queue at any given time. When a queued command is added
* for a sender that already has a command in queue, it will replace the old queued command.</p>
*/
public class CommandQueueManager {
private static final long TICKS_PER_SECOND = 20;
private static final DummyCommandBlockSender COMMAND_BLOCK = new DummyCommandBlockSender();
private final MultiverseCore plugin;
private final Map<CommandSender, QueuedCommand> queuedCommandMap;
public CommandQueueManager(@NotNull MultiverseCore plugin) {
this.plugin = plugin;
this.queuedCommandMap = new WeakHashMap<>();
}
/**
* Adds a {@link QueuedCommand} into queue.
*
* @param queuedCommand The queued command to add.
*/
public void addToQueue(QueuedCommand queuedCommand) {
CommandSender targetSender = parseSender(queuedCommand.getSender());
// Since only one command is stored in queue per sender, we remove the old one.
this.removeFromQueue(targetSender);
Logging.finer("Add new command to queue for sender %s.", targetSender);
this.queuedCommandMap.put(targetSender, queuedCommand);
queuedCommand.setExpireTask(runExpireLater(queuedCommand));
queuedCommand.getSender().sendMessage(queuedCommand.getPrompt());
queuedCommand.getSender().sendMessage(String.format("Run %s/mv confirm %sto continue. This will expire in %s seconds.",
ChatColor.GREEN, ChatColor.WHITE, queuedCommand.getValidDuration()));
}
/**
* Expire task that removes a {@link QueuedCommand} from queue after valid duration defined.
*
* @param queuedCommand Command to run the expire task on.
* @return The expire {@link BukkitTask}.
*/
@NotNull
private BukkitTask runExpireLater(@NotNull QueuedCommand queuedCommand) {
return Bukkit.getScheduler().runTaskLater(
this.plugin,
expireRunnable(queuedCommand),
queuedCommand.getValidDuration() * TICKS_PER_SECOND
);
}
/**
* Runnable responsible for expiring the queued command.
*
* @param queuedCommand Command to create the expire task on.
* @return The expire runnable.
*/
@NotNull
private Runnable expireRunnable(@NotNull QueuedCommand queuedCommand) {
return () -> {
CommandSender targetSender = parseSender(queuedCommand.getSender());
QueuedCommand matchingQueuedCommand = this.queuedCommandMap.get(targetSender);
if (!queuedCommand.equals(matchingQueuedCommand) || queuedCommand.getExpireTask().isCancelled()) {
// To be safe, but this shouldn't happen since we cancel old commands before add new once.
Logging.finer("This is an old queue command already.");
return;
}
queuedCommand.getSender().sendMessage("Your queued command has expired.");
this.queuedCommandMap.remove(queuedCommand.getSender());
};
}
/**
* Runs the command in queue for the given sender, if any.
*
* @param sender {@link CommandSender} that confirmed the command.
* @return True if queued command ran successfully, else false.
*/
public boolean runQueuedCommand(@NotNull CommandSender sender) {
CommandSender targetSender = parseSender(sender);
QueuedCommand queuedCommand = this.queuedCommandMap.get(targetSender);
if (queuedCommand == null) {
sender.sendMessage(ChatColor.RED + "You do not have any commands in queue.");
return false;
}
Logging.finer("Running queued command...");
queuedCommand.getAction().run();
return removeFromQueue(targetSender);
}
/**
* Since only one command is stored in queue per sender, we remove the old one.
*
* @param sender The {@link CommandSender} that executed the command.
* @return True if queue command is removed from sender successfully, else false.
*/
public boolean removeFromQueue(@NotNull CommandSender sender) {
CommandSender targetSender = parseSender(sender);
QueuedCommand previousCommand = this.queuedCommandMap.remove(targetSender);
if (previousCommand == null) {
Logging.finer("No queue command to remove for sender %s.", targetSender.getName());
return false;
}
previousCommand.getExpireTask().cancel();
Logging.finer("Removed queue command for sender %s.", targetSender.getName());
return true;
}
/**
* To allow all CommandBlocks to be a common sender with use of {@link DummyCommandBlockSender}.
* So confirm command can be used for a queued command on another command block.
*
* @param sender The sender to parse.
* @return The sender, or if its a command block, a {@link DummyCommandBlockSender}.
*/
@NotNull
private CommandSender parseSender(@NotNull CommandSender sender) {
Logging.fine(sender.getClass().getName());
if (isCommandBlock(sender)) {
Logging.finer("Is command block.");
return COMMAND_BLOCK;
}
return sender;
}
/**
* Checks if the sender is a command block.
*
* @param sender The sender to check.
* @return True if sender is a command block, else false.
*/
private boolean isCommandBlock(@NotNull CommandSender sender) {
return sender instanceof BlockCommandSender
&& ((BlockCommandSender) sender).getBlock().getBlockData() instanceof CommandBlock;
}
}
@@ -1,104 +0,0 @@
package com.onarandombox.MultiverseCore.commandtools.queue;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionAttachment;
import org.bukkit.permissions.PermissionAttachmentInfo;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Set;
/**
* Used by {@link CommandQueueManager}, so different commands block can be recognised as one.
*/
class DummyCommandBlockSender implements CommandSender {
@Override
public void sendMessage(@NotNull String message) {
throw new UnsupportedOperationException();
}
@Override
public void sendMessage(@NotNull String[] messages) {
throw new UnsupportedOperationException();
}
@Override
public @NotNull Server getServer() {
return Bukkit.getServer();
}
@Override
public @NotNull String getName() {
return "DummyCommandBlockSender";
}
@Override
public boolean isPermissionSet(@NotNull String name) {
throw new UnsupportedOperationException();
}
@Override
public boolean isPermissionSet(@NotNull Permission perm) {
throw new UnsupportedOperationException();
}
@Override
public boolean hasPermission(@NotNull String name) {
throw new UnsupportedOperationException();
}
@Override
public boolean hasPermission(@NotNull Permission perm) {
throw new UnsupportedOperationException();
}
@Override
public @NotNull PermissionAttachment addAttachment(@NotNull Plugin plugin, @NotNull String name, boolean value) {
throw new UnsupportedOperationException();
}
@Override
public @NotNull PermissionAttachment addAttachment(@NotNull Plugin plugin) {
throw new UnsupportedOperationException();
}
@Override
public @Nullable PermissionAttachment addAttachment(@NotNull Plugin plugin, @NotNull String name, boolean value, int ticks) {
throw new UnsupportedOperationException();
}
@Override
public @Nullable PermissionAttachment addAttachment(@NotNull Plugin plugin, int ticks) {
throw new UnsupportedOperationException();
}
@Override
public void removeAttachment(@NotNull PermissionAttachment attachment) {
throw new UnsupportedOperationException();
}
@Override
public void recalculatePermissions() {
throw new UnsupportedOperationException();
}
@Override
public @NotNull Set<PermissionAttachmentInfo> getEffectivePermissions() {
throw new UnsupportedOperationException();
}
@Override
public boolean isOp() {
throw new UnsupportedOperationException();
}
@Override
public void setOp(boolean value) {
throw new UnsupportedOperationException();
}
}
@@ -1,86 +0,0 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2020. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.commandtools.queue;
import org.bukkit.command.CommandSender;
import org.bukkit.scheduler.BukkitTask;
import org.jetbrains.annotations.NotNull;
/**
* Represents a single command used in {@link CommandQueueManager} for confirming before running potentially
* dangerous action.
*/
public class QueuedCommand {
private static final String DEFAULT_PROMPT_MESSAGE = "The command you are trying to run is deemed dangerous.";
private static final int DEFAULT_VALID_TIME = 10;
private final CommandSender sender;
private final Runnable action;
private final String prompt;
private final int validDuration;
private BukkitTask expireTask;
public QueuedCommand(CommandSender sender, Runnable action) {
this(sender, action, DEFAULT_PROMPT_MESSAGE, DEFAULT_VALID_TIME);
}
public QueuedCommand(CommandSender sender, Runnable action, String prompt) {
this(sender, action, prompt, DEFAULT_VALID_TIME);
}
public QueuedCommand(CommandSender sender, Runnable action, int validDuration) {
this(sender, action, DEFAULT_PROMPT_MESSAGE, validDuration);
}
/**
* Creates a new queue command, to be registered at {@link CommandQueueManager#addToQueue(QueuedCommand)}.
*
* @param sender The sender that ran the command needed for confirmation.
* @param action The logic to execute upon confirming.
* @param prompt Question to ask sender to confirm.
* @param validDuration Duration in which the command is valid for confirm in seconds.
*/
public QueuedCommand(CommandSender sender, Runnable action, String prompt, int validDuration) {
this.sender = sender;
this.action = action;
this.prompt = prompt;
this.validDuration = validDuration;
}
@NotNull
CommandSender getSender() {
return sender;
}
@NotNull
String getPrompt() {
return prompt;
}
int getValidDuration() {
return validDuration;
}
@NotNull
Runnable getAction() {
return action;
}
@NotNull
BukkitTask getExpireTask() {
return expireTask;
}
void setExpireTask(@NotNull BukkitTask expireTask) {
if (this.expireTask != null) {
throw new IllegalStateException("This queue command already has an expire task. You can't register twice!");
}
this.expireTask = expireTask;
}
}
@@ -1,4 +0,0 @@
/**
* Manager queuing of dangerous commands in need of confirmation.
*/
package com.onarandombox.MultiverseCore.commandtools.queue;
@@ -11,29 +11,16 @@ 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.Collection;
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.
*/
/** 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;
@@ -49,59 +36,6 @@ 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.
@@ -167,13 +101,4 @@ public class DestinationFactory {
this.teleportCommand.addAdditonalPermission(other);
return true;
}
/**
* Gets all the {@link MVDestination} identifiers registered.
*
* @return A collection of destination identifiers.
*/
public Collection<String> getRegisteredIdentifiers() {
return this.destList.keySet();
}
}
@@ -11,7 +11,6 @@ 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.utils.CompatibilityLayer;
import org.bukkit.World;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
@@ -19,7 +18,6 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.event.entity.EntityPortalEvent;
import org.bukkit.event.entity.EntityRegainHealthEvent;
import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason;
import org.bukkit.event.entity.FoodLevelChangeEvent;
@@ -109,17 +107,4 @@ public class MVEntityListener implements Listener {
event.setCancelled(this.plugin.getMVWorldManager().getTheWorldPurger().shouldWeKillThisCreature(mvworld, event.getEntity()));
}
/**
* Handles portal search radius adjustment.
* @param event The Event that was fired.
*/
@EventHandler
public void entityPortal(EntityPortalEvent event) {
if (event.isCancelled() || event.getTo() == null) {
return;
}
if (!this.plugin.getMVConfig().isUsingDefaultPortalSearch()) {
CompatibilityLayer.setPortalSearchRadius(event, this.plugin.getMVConfig().getPortalSearchRadius());
}
}
}
@@ -7,6 +7,10 @@
package com.onarandombox.MultiverseCore.listeners;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
@@ -31,9 +35,6 @@ import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Multiverse's {@link Listener} for players.
*/
@@ -312,8 +313,16 @@ public class MVPlayerListener implements Listener {
+ "' was allowed to go to '" + event.getTo().getWorld().getName()
+ "' because enforceaccess is off.");
}
if (!this.plugin.getMVConfig().isUsingDefaultPortalSearch()) {
CompatibilityLayer.setPortalSearchRadius(event, this.plugin.getMVConfig().getPortalSearchRadius());
if (!plugin.getMVConfig().isUsingDefaultPortalSearch()) {
try {
Class.forName("org.bukkit.TravelAgent");
if (event.getPortalTravelAgent() != null) {
event.getPortalTravelAgent().setSearchRadius(plugin.getMVConfig().getPortalSearchRadius());
}
} catch (ClassNotFoundException ignore) {
Logging.fine("TravelAgent not available for PlayerPortalEvent for " + event.getPlayer().getName());
}
}
}
@@ -1,35 +1,32 @@
package com.onarandombox.MultiverseCore.utils;
import com.dumptruckman.minecraft.util.Logging;
import org.bukkit.event.entity.EntityPortalEvent;
import org.bukkit.event.player.PlayerPortalEvent;
import org.bukkit.Bukkit;
import org.bukkit.event.player.PlayerRespawnEvent;
import java.lang.reflect.Method;
/**
* Utility class to enable version specific minecraft features.
* A utility class to enable version specific minecraft features.
*/
public class CompatibilityLayer {
private static Method checkAnchorSpawn;
private static boolean useTravelAgent;
private static Method playerPortalSearchRadius;
private static Method entityPortalSearchRadius;
/**
* Initialise the reflection class, methods and fields.
* Initialise the reflection methods.
*/
public static void init() {
checkAnchorSpawn = ReflectHelper.getMethod(PlayerRespawnEvent.class, "isAnchorSpawn");
useTravelAgent = ReflectHelper.hasClass("org.bukkit.TravelAgent");
playerPortalSearchRadius = ReflectHelper.getMethod(PlayerPortalEvent.class, "setSearchRadius", int.class);
entityPortalSearchRadius = ReflectHelper.getMethod(EntityPortalEvent.class, "setSearchRadius", int.class);
try {
checkAnchorSpawn = PlayerRespawnEvent.class.getDeclaredMethod("isAnchorSpawn");
} catch (NoSuchMethodException e) {
Logging.fine("%s does not support respawn anchors.", Bukkit.getVersion());
}
}
/**
* <p>Check if the respawn point is of respawn anchor type.</p>
* <p>Introduced in minecraft 1.16</p>
* 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.
@@ -38,69 +35,12 @@ public class CompatibilityLayer {
if (checkAnchorSpawn == null) {
return false;
}
Boolean result = ReflectHelper.invokeMethod(event, checkAnchorSpawn);
if (result == null) {
Logging.warning("Unable to check if spawning at respawn anchor!");
return false;
try {
return (boolean) checkAnchorSpawn.invoke(event);
} catch (Exception e) {
Logging.warning("Error checking for: %s", checkAnchorSpawn);
e.printStackTrace();
}
return result;
return false;
}
/**
* <p>Gets if Travel Agent is supported on the server's minecraft version.</p>
* <p>Removed in minecraft 1.14</p>
*
* @return True if Travel Agent is supported, else false.
*/
public static boolean isUseTravelAgent() {
return useTravelAgent;
}
/**
* <p>Sets search radius for a PlayerPortalEvent.</p>
*
* <p>Use travel agent if available, else using new PlayerPortalEvent.setSearchRadius(int) method
* introduced in minecraft 1.15</p>
*
* @param event A Player Portal Event.
* @param searchRadius Target search radius to set to.
*/
public static void setPortalSearchRadius(PlayerPortalEvent event, int searchRadius) {
if (useTravelAgent) {
event.getPortalTravelAgent().setSearchRadius(searchRadius);
event.useTravelAgent(true);
Logging.finer("Used travel agent to set player portal search radius.");
return;
}
if (playerPortalSearchRadius == null) {
Logging.warning("Unable to set player portal search radius!");
return;
}
ReflectHelper.invokeMethod(event, playerPortalSearchRadius, searchRadius);
Logging.finer("Used new method to set player portal search radius.");
}
/**
* <p>Sets search radius for a EntityPortalEvent.</p>
*
* <p>Use travel agent if available, else using new EntityPortalEvent.setSearchRadius(int) method
* introduced in minecraft 1.15</p>
*
* @param event A Entity Portal Event.
* @param searchRadius Target search radius to set to.
*/
public static void setPortalSearchRadius(EntityPortalEvent event, int searchRadius) {
if (useTravelAgent) {
event.getPortalTravelAgent().setSearchRadius(searchRadius);
event.useTravelAgent(true);
Logging.finer("Used travel agent to set entity portal search radius.");
return;
}
if (entityPortalSearchRadius == null) {
Logging.warning("Unable to set entity portal search radius!");
return;
}
ReflectHelper.invokeMethod(event, entityPortalSearchRadius, searchRadius);
Logging.finer("Used new method to set entity portal search radius.");
}
}
}
@@ -1,176 +0,0 @@
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}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[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.fine("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;
}
}
}
@@ -1,140 +0,0 @@
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;
}
}
}
@@ -18,7 +18,6 @@ import com.onarandombox.MultiverseCore.api.SafeTTeleporter;
import com.onarandombox.MultiverseCore.api.WorldPurger;
import com.onarandombox.MultiverseCore.event.MVWorldDeleteEvent;
import org.bukkit.Bukkit;
import org.bukkit.GameRule;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.World.Environment;
@@ -37,25 +36,26 @@ import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Stack;
import java.util.Arrays;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* Public facing API to add/remove Multiverse worlds.
*/
public class WorldManager implements MVWorldManager {
private final MultiverseCore plugin;
private final Pattern worldNamePattern = Pattern.compile("[a-zA-Z0-9/._-]+");
private final WorldPurger worldPurger;
private final Map<String, MultiverseWorld> worlds;
private Map<String, WorldProperties> worldsFromTheConfig;
@@ -130,7 +130,7 @@ public class WorldManager implements MVWorldManager {
}
// Check for valid world name
if (!(WorldNameChecker.isValidWorldName(oldName) && WorldNameChecker.isValidWorldName(newName))) {
if (!(isValidWorldName(oldName) && isValidWorldName(newName))) {
return false;
}
@@ -238,9 +238,7 @@ public class WorldManager implements MVWorldManager {
return false;
}
if (!WorldNameChecker.isValidWorldName(name)) {
Logging.warning("Invalid world name '" + name + "'");
Logging.warning("World name should not contain spaces or special characters!");
if (!isValidWorldName(name)) {
return false;
}
@@ -387,14 +385,14 @@ public class WorldManager implements MVWorldManager {
this.worldsFromTheConfig.get(name).cacheVirtualProperties();
if (unloadBukkit && this.unloadWorldFromBukkit(name, true)) {
this.worlds.remove(name);
Logging.info("World '%s' was unloaded from Bukkit.", name);
Logging.info("World '%s' was unloaded from memory.", name);
return true;
} else if (!unloadBukkit){
this.worlds.remove(name);
Logging.info("World '%s' was unloaded from Multiverse.", name);
Logging.info("World '%s' was unloaded from memory.", name);
return true;
} else {
Logging.warning("World '%s' could not be unloaded from Bukkit. Is it a default world?", name);
Logging.warning("World '%s' could not be unloaded. Is it a default world?", name);
}
} else if (this.plugin.getServer().getWorld(name) != null) {
Logging.warning("Hmm Multiverse does not know about this world but it's loaded in memory.");
@@ -426,6 +424,21 @@ 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 + "'");
@@ -617,14 +630,6 @@ public class WorldManager implements MVWorldManager {
*/
@Override
public MultiverseWorld getMVWorld(String name) {
return this.getMVWorld(name, true);
}
/**
* {@inheritDoc}
*/
@Override
public MultiverseWorld getMVWorld(String name, boolean checkAliases) {
if (name == null) {
return null;
}
@@ -632,7 +637,7 @@ public class WorldManager implements MVWorldManager {
if (world != null) {
return world;
}
return (checkAliases) ? this.getMVWorldByAlias(name) : null;
return this.getMVWorldByAlias(name);
}
/**
@@ -641,7 +646,7 @@ public class WorldManager implements MVWorldManager {
@Override
public MultiverseWorld getMVWorld(World world) {
if (world != null) {
return this.getMVWorld(world.getName(), false);
return this.getMVWorld(world.getName());
}
return null;
}
@@ -666,15 +671,7 @@ public class WorldManager implements MVWorldManager {
*/
@Override
public boolean isMVWorld(final String name) {
return this.isMVWorld(name, true);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isMVWorld(final String name, boolean checkAliases) {
return this.worlds.containsKey(name) || (checkAliases && this.isMVWorldAlias(name));
return (this.worlds.containsKey(name) || isMVWorldAlias(name));
}
/**
@@ -897,23 +894,12 @@ public class WorldManager implements MVWorldManager {
*/
@Override
public boolean regenWorld(String name, boolean useNewSeed, boolean randomSeed, String seed) {
return regenWorld(name, useNewSeed, randomSeed, seed, false);
}
/**
* {@inheritDoc}
*/
@Override
public boolean regenWorld(String name, boolean useNewSeed, boolean randomSeed, String seed, boolean keepGameRules) {
MultiverseWorld world = this.getMVWorld(name);
if (world == null) {
Logging.warning("Unable to regen a world that does not exist!");
if (world == null)
return false;
}
List<Player> ps = world.getCBWorld().getPlayers();
// Apply new seed if needed.
if (useNewSeed) {
long theSeed;
@@ -929,64 +915,19 @@ public class WorldManager implements MVWorldManager {
world.setSeed(theSeed);
}
WorldType type = world.getWorldType();
// Save current GameRules if needed.
Map<GameRule<?>, Object> gameRuleMap = null;
if (keepGameRules) {
gameRuleMap = new HashMap<>(GameRule.values().length);
World CBWorld = world.getCBWorld();
for (GameRule<?> gameRule : GameRule.values()) {
// Only save if not default value.
Object value = CBWorld.getGameRuleValue(gameRule);
if (value != CBWorld.getGameRuleDefault(gameRule)) {
gameRuleMap.put(gameRule, value);
}
if (this.deleteWorld(name, false, false)) {
this.doLoad(name, true, type);
SafeTTeleporter teleporter = this.plugin.getSafeTTeleporter();
Location newSpawn = world.getSpawnLocation();
// Send all players that were in the old world, BACK to it!
for (Player p : ps) {
teleporter.safelyTeleport(null, p, newSpawn, true);
}
return true;
}
// Do the regen.
if (!this.deleteWorld(name, false, false)) {
Logging.severe("Unable to regen world as world cannot be deleted.");
return false;
}
if (!this.doLoad(name, true, type)) {
Logging.severe("Unable to regen world as world cannot be loaded.");
return false;
}
// Get new MultiverseWorld reference.
world = this.getMVWorld(name);
// Load back GameRules if needed.
if (keepGameRules) {
Logging.fine("Restoring previous world's GameRules...");
World CBWorld = world.getCBWorld();
for (Map.Entry<GameRule<?>, Object> gameRuleEntry : gameRuleMap.entrySet()) {
if (!setGameRuleValue(CBWorld, gameRuleEntry.getKey(), gameRuleEntry.getValue())) {
Logging.warning("Unable to set GameRule '%s' to '%s' on regen world.",
gameRuleEntry.getKey().getName(), gameRuleEntry.getValue());
}
}
}
// Send all players that were in the old world, BACK to it!
SafeTTeleporter teleporter = this.plugin.getSafeTTeleporter();
Location newSpawn = world.getSpawnLocation();
for (Player p : ps) {
teleporter.safelyTeleport(null, p, newSpawn, true);
}
return true;
}
private <T> boolean setGameRuleValue(World world, GameRule<T> gameRule, Object value) {
try {
return world.setGameRule(gameRule, (T) value);
} catch (Exception e) {
return false;
}
return false;
}
/**
@@ -1012,21 +953,4 @@ public class WorldManager implements MVWorldManager {
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
public Collection<String> getPotentialWorlds() {
File worldContainer = this.plugin.getServer().getWorldContainer();
if (worldContainer == null) {
return Collections.emptyList();
}
return Arrays.stream(worldContainer.listFiles())
.filter(File::isDirectory)
.filter(folder -> !this.isMVWorld(folder.getName(), false))
.filter(WorldNameChecker::isValidWorldFolder)
.map(File::getName)
.collect(Collectors.toList());
}
}
@@ -1,159 +0,0 @@
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
}
}
@@ -1,12 +1,11 @@
package com.onarandombox.MultiverseCore.utils.metrics;
import org.bstats.charts.AdvancedPie;
import org.bstats.charts.MultiLineChart;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import org.bstats.bukkit.Metrics;
enum MetricsHelper {
;
@@ -18,16 +17,16 @@ enum MetricsHelper {
map.put(key, count + 1);
}
static AdvancedPie createAdvancedPieChart(String chartId, Consumer<Map<String, Integer>> metricsFunc) {
static Metrics.AdvancedPie createAdvancedPieChart(String chartId, Consumer<Map<String, Integer>> metricsFunc) {
Map<String, Integer> map = new HashMap<>();
metricsFunc.accept(map);
return new AdvancedPie(chartId, () -> map);
return new Metrics.AdvancedPie(chartId, () -> map);
}
static MultiLineChart createMultiLineChart(String chartId, Consumer<Map<String, Integer>> metricsFunc) {
static Metrics.MultiLineChart createMultiLineChart(String chartId, Consumer<Map<String, Integer>> metricsFunc) {
Map<String, Integer> map = new HashMap<>();
metricsFunc.accept(map);
return new MultiLineChart(chartId, () -> map);
return new Metrics.MultiLineChart(chartId, () -> map);
}
}
@@ -14,9 +14,15 @@ import org.bukkit.Server;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPluginLoader;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.io.File;
@@ -25,6 +31,9 @@ import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ MultiverseCore.class, PluginDescriptionFile.class, JavaPluginLoader.class})
@PowerMockIgnore("javax.script.*")
public class TestDebugMode {
TestInstanceCreator creator;
Server mockServer;
@@ -7,29 +7,35 @@ import com.onarandombox.MultiverseCore.utils.MockWorldFactory;
import com.onarandombox.MultiverseCore.utils.TestInstanceCreator;
import org.bukkit.World;
import org.bukkit.WorldType;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Sheep;
import org.bukkit.entity.Zombie;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPluginLoader;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.anyBoolean;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.*;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ MultiverseCore.class, PluginDescriptionFile.class, JavaPluginLoader.class})
@PowerMockIgnore("javax.script.*")
public class TestEntitySpawnRules {
TestInstanceCreator creator;
MultiverseCore core;
@@ -151,6 +157,6 @@ public class TestEntitySpawnRules {
when(zombie.getType()).thenReturn(EntityType.ZOMBIE);
when(zombie.getWorld()).thenReturn(this.cbworld);
when(cbworld.getEntities()).thenReturn(Arrays.asList(sheep, zombie));
when(cbworld.getEntities()).thenReturn(Arrays.asList((Entity) sheep, (Entity) zombie));
}
}
@@ -2,17 +2,24 @@ package com.onarandombox.MultiverseCore;
import com.onarandombox.MultiverseCore.utils.TestInstanceCreator;
import org.bukkit.Material;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPluginLoader;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.*;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ MultiverseCore.class, PluginDescriptionFile.class, JavaPluginLoader.class})
@PowerMockIgnore("javax.script.*")
public class TestEntryFeeConversion {
private TestInstanceCreator creator;
@@ -6,16 +6,24 @@ import org.bukkit.Server;
import org.bukkit.World.Environment;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPluginLoader;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ MultiverseCore.class, PluginDescriptionFile.class, JavaPluginLoader.class })
@PowerMockIgnore("javax.script.*")
public class TestModifyCommand {
TestInstanceCreator creator;
Server mockServer;
@@ -13,6 +13,8 @@ import com.onarandombox.MultiverseCore.configuration.SpawnLocation;
import com.onarandombox.MultiverseCore.listeners.MVAsyncPlayerChatListener;
import com.onarandombox.MultiverseCore.utils.MockWorldFactory;
import com.onarandombox.MultiverseCore.utils.TestInstanceCreator;
import com.onarandombox.MultiverseCore.utils.WorldManager;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Difficulty;
import org.bukkit.GameMode;
@@ -34,26 +36,33 @@ import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.weather.ThunderChangeEvent;
import org.bukkit.event.weather.WeatherChangeEvent;
import org.bukkit.permissions.Permission;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPluginLoader;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.internal.verification.VerificationModeFactory;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.io.File;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ PluginManager.class, MultiverseCore.class, Permission.class, Bukkit.class,
WeatherChangeEvent.class, ThunderChangeEvent.class, AsyncPlayerChatEvent.class,
PlayerJoinEvent.class, PlayerRespawnEvent.class, EntityRegainHealthEvent.class,
FoodLevelChangeEvent.class, WorldManager.class, PluginDescriptionFile.class, JavaPluginLoader.class })
@PowerMockIgnore("javax.script.*")
public class TestWorldProperties {
private TestInstanceCreator creator;
private MultiverseCore core;
@@ -113,7 +122,7 @@ public class TestWorldProperties {
String[] netherArgs = new String[] { "import", "world_nether", "nether" };
core.onCommand(mockCommandSender, mockCommand, "", netherArgs);
verify(mockCommandSender).sendMessage("Starting import of world 'world_nether'...");
verify(mockCommandSender, times(2)).sendMessage(
verify(mockCommandSender, VerificationModeFactory.times(2)).sendMessage(
ChatColor.GREEN + "Complete!");
assertEquals(core.getServer().getWorlds().size(), 2);
@@ -213,7 +222,7 @@ public class TestWorldProperties {
assertTrue(mvWorld.setColor("BLACK"));
assertFalse(mvWorld.setColor("INVALID COLOR"));
assertEquals(ChatColor.BLACK, mvWorld.getColor());
assertEquals(ChatColor.BLACK + "alias" + ChatColor.WHITE, mvWorld.getColoredWorldString());
assertEquals(ChatColor.BLACK.toString() + "alias" + ChatColor.WHITE.toString(), mvWorld.getColoredWorldString());
mvWorld.setPVPMode(false);
assertEquals(false, mvWorld.isPVPEnabled());
assertTrue(mvWorld.setScaling(2D));
@@ -320,7 +329,7 @@ public class TestWorldProperties {
assertEquals(true, mvWorld.isHidden());
assertEquals("alias", mvWorld.getAlias());
assertEquals(ChatColor.GREEN, mvWorld.getColor());
assertEquals(ChatColor.GREEN + "alias" + ChatColor.WHITE, mvWorld.getColoredWorldString());
assertEquals(ChatColor.GREEN.toString() + "alias" + ChatColor.WHITE.toString(), mvWorld.getColoredWorldString());
assertEquals(false, mvWorld.isPVPEnabled());
assertEquals(2D, mvWorld.getScaling(), 0);
assertSame(worldManager.getMVWorld("world_nether").getCBWorld(),
@@ -357,36 +366,36 @@ public class TestWorldProperties {
when(mockPlayer.hasPlayedBefore()).thenReturn(true);
when(mockPlayer.hasPermission("multiverse.access.world")).thenReturn(true);
when(mockPlayer.getName()).thenReturn("MultiverseMan");
playerChatEvent = mock(AsyncPlayerChatEvent.class);
playerChatEvent = PowerMockito.mock(AsyncPlayerChatEvent.class);
when(playerChatEvent.getPlayer()).thenReturn(mockPlayer);
when(playerChatEvent.getFormat()).thenReturn("format");
// player join
mockNewPlayer = mock(Player.class);
when(mockNewPlayer.hasPlayedBefore()).thenReturn(false);
playerJoinEvent = mock(PlayerJoinEvent.class);
playerJoinEvent = PowerMockito.mock(PlayerJoinEvent.class);
when(playerJoinEvent.getPlayer()).thenReturn(mockPlayer);
playerNewJoinEvent = mock(PlayerJoinEvent.class);
playerNewJoinEvent = PowerMockito.mock(PlayerJoinEvent.class);
when(playerNewJoinEvent.getPlayer()).thenReturn(mockNewPlayer);
// player respawn
playerRespawnBed = mock(PlayerRespawnEvent.class);
playerRespawnBed = PowerMockito.mock(PlayerRespawnEvent.class);
when(playerRespawnBed.getPlayer()).thenReturn(mockPlayer);
when(playerRespawnBed.isBedSpawn()).thenReturn(true);
playerRespawnNormal = mock(PlayerRespawnEvent.class);
playerRespawnNormal = PowerMockito.mock(PlayerRespawnEvent.class);
when(playerRespawnNormal.getPlayer()).thenReturn(mockPlayer);
when(playerRespawnNormal.isBedSpawn()).thenReturn(false);
//// Entity events
mockHumanEntity = mock(HumanEntity.class);
// entity regain health
entityRegainHealthEvent = mock(EntityRegainHealthEvent.class);
entityRegainHealthEvent = PowerMockito.mock(EntityRegainHealthEvent.class);
when(entityRegainHealthEvent.getRegainReason()).thenReturn(RegainReason.REGEN);
when(mockHumanEntity.getLocation()).thenReturn(new Location(world, 0, 0, 0));
when(entityRegainHealthEvent.getEntity()).thenReturn(mockHumanEntity);
// entity food level change event
entityFoodLevelChangeEvent = mock(FoodLevelChangeEvent.class);
entityFoodLevelChangeEvent = PowerMockito.mock(FoodLevelChangeEvent.class);
// this won't do anything since we're not mocking a player,
// but the plugin should be able to handle this!
when(entityFoodLevelChangeEvent.getEntity()).thenReturn(mockHumanEntity);
entityFoodLevelRiseEvent = mock(FoodLevelChangeEvent.class);
entityFoodLevelRiseEvent = PowerMockito.mock(FoodLevelChangeEvent.class);
when(mockPlayer.getFoodLevel()).thenReturn(2);
when(entityFoodLevelRiseEvent.getEntity()).thenReturn(mockPlayer);
when(entityFoodLevelRiseEvent.getFoodLevel()).thenReturn(3);
@@ -4,21 +4,28 @@ import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.api.WorldPurger;
import com.onarandombox.MultiverseCore.utils.TestInstanceCreator;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Sheep;
import org.bukkit.entity.Zombie;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPluginLoader;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.Arrays;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.*;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ MultiverseCore.class, PluginDescriptionFile.class, JavaPluginLoader.class })
@PowerMockIgnore("javax.script.*")
public class TestWorldPurger {
TestInstanceCreator creator;
MultiverseCore core;
@@ -114,6 +121,6 @@ public class TestWorldPurger {
zombie = mock(Zombie.class);
when(zombie.getType()).thenReturn(EntityType.ZOMBIE);
when(zombie.getWorld()).thenReturn(world);
when(cbworld.getEntities()).thenReturn(Arrays.asList(sheep, zombie));
when(cbworld.getEntities()).thenReturn(Arrays.asList((Entity) sheep, (Entity) zombie));
}
}
@@ -12,30 +12,39 @@ import com.onarandombox.MultiverseCore.exceptions.PropertyDoesNotExistException;
import com.onarandombox.MultiverseCore.utils.MockWorldFactory;
import com.onarandombox.MultiverseCore.utils.TestInstanceCreator;
import com.onarandombox.MultiverseCore.utils.WorldCreatorMatcher;
import com.onarandombox.MultiverseCore.utils.WorldManager;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Server;
import org.bukkit.WorldCreator;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.Permission;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPluginLoader;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.mockito.Matchers;
import org.mockito.internal.verification.VerificationModeFactory;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.io.File;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static junit.framework.Assert.*;
import static org.mockito.Mockito.*;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ PluginManager.class, MultiverseCore.class, Permission.class, Bukkit.class, WorldManager.class,
PluginDescriptionFile.class, JavaPluginLoader.class })
@PowerMockIgnore("javax.script.*")
public class TestWorldStuff {
private TestInstanceCreator creator;
@@ -1,8 +1,7 @@
package com.onarandombox.MultiverseCore.utils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.nio.file.Files;
@@ -11,8 +10,10 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import com.dumptruckman.minecraft.util.Logging;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class FileUtilsTest {
@@ -136,7 +137,7 @@ public class FileUtilsTest {
assertTrue(Files.isRegularFile(targetChildDirFile));
}
@Test
@Test()
public void copyFolder_intoExistingFolder_whereFileExists() throws Exception {
Path targetDir = Files.createDirectory(tempDir.resolve("target"));
Path targetFile = Files.createFile(targetDir.resolve("parentDirFile.txt"));
@@ -21,17 +21,13 @@ import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.WeakHashMap;
import java.util.LinkedHashMap;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyBoolean;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.*;
public class MockWorldFactory {
@@ -27,9 +27,13 @@ import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.java.JavaPluginLoader;
import org.bukkit.scheduler.BukkitScheduler;
import org.mockito.internal.util.reflection.ReflectionMemberAccessor;
import org.mockito.ArgumentMatchers;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.easymock.PowerMock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.MockGateway;
import org.powermock.reflect.Whitebox;
import java.io.File;
import java.lang.reflect.Field;
@@ -40,16 +44,15 @@ import java.util.logging.Level;
import java.util.logging.Logger;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyBoolean;
import static org.mockito.Mockito.anyLong;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.isA;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.doAnswer;
public class TestInstanceCreator {
private MultiverseCore core;
@@ -66,20 +69,28 @@ public class TestInstanceCreator {
pluginDirectory.mkdirs();
assertTrue(pluginDirectory.exists());
MockGateway.MOCK_STANDARD_METHODS = false;
// Initialize the Mock server.
mockServer = mock(Server.class);
JavaPluginLoader mockPluginLoader = mock(JavaPluginLoader.class);
new ReflectionMemberAccessor().set(JavaPluginLoader.class.getDeclaredField("server"), mockPluginLoader, mockServer);
JavaPluginLoader mockPluginLoader = PowerMock.createMock(JavaPluginLoader.class);
Whitebox.setInternalState(mockPluginLoader, "server", mockServer);
when(mockServer.getName()).thenReturn("TestBukkit");
Logger.getLogger("Minecraft").setParent(Util.logger);
when(mockServer.getLogger()).thenReturn(Util.logger);
when(mockServer.getWorldContainer()).thenReturn(worldsDirectory);
// Return a fake PDF file.
PluginDescriptionFile pdf = spy(new PluginDescriptionFile("Multiverse-Core", "2.2-Test",
PluginDescriptionFile pdf = PowerMockito.spy(new PluginDescriptionFile("Multiverse-Core", "2.2-Test",
"com.onarandombox.MultiverseCore.MultiverseCore"));
when(pdf.getAuthors()).thenReturn(new ArrayList<String>());
core = spy(new MultiverseCore(mockPluginLoader, pdf, pluginDirectory, new File(pluginDirectory, "testPluginFile")));
core = PowerMockito.spy(new MultiverseCore(mockPluginLoader, pdf, pluginDirectory, new File(pluginDirectory, "testPluginFile")));
PowerMockito.doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
return null; // don't run metrics in tests
}
}).when(core, "setupMetrics");
// Let's let all MV files go to bin/test
doReturn(pluginDirectory).when(core).getDataFolder();
@@ -92,7 +103,7 @@ public class TestInstanceCreator {
JavaPlugin[] plugins = new JavaPlugin[] { core };
// Mock the Plugin Manager
PluginManager mockPluginManager = mock(PluginManager.class);
PluginManager mockPluginManager = PowerMockito.mock(PluginManager.class);
when(mockPluginManager.getPlugins()).thenReturn(plugins);
when(mockPluginManager.getPlugin("Multiverse-Core")).thenReturn(core);
when(mockPluginManager.getPermission(anyString())).thenReturn(null);
@@ -146,7 +157,7 @@ public class TestInstanceCreator {
when(mockServer.getPluginManager()).thenReturn(mockPluginManager);
when(mockServer.createWorld(isA(WorldCreator.class))).thenAnswer(
when(mockServer.createWorld(ArgumentMatchers.isA(WorldCreator.class))).thenAnswer(
new Answer<World>() {
@Override
public World answer(InvocationOnMock invocation) throws Throwable {
@@ -208,7 +219,7 @@ public class TestInstanceCreator {
buscriptfield.setAccessible(true);
try {
buscript = spy(new Buscript(core));
buscript = PowerMockito.spy(new Buscript(core));
when(buscript.getPlugin()).thenReturn(core);
} catch (NullPointerException e) {
buscript = null;
@@ -217,25 +228,25 @@ public class TestInstanceCreator {
buscriptfield.set(core, buscript);
// Set worldManager
WorldManager wm = spy(new WorldManager(core));
WorldManager wm = PowerMockito.spy(new WorldManager(core));
Field worldmanagerfield = MultiverseCore.class.getDeclaredField("worldManager");
worldmanagerfield.setAccessible(true);
worldmanagerfield.set(core, wm);
// Set playerListener
MVPlayerListener pl = spy(new MVPlayerListener(core));
MVPlayerListener pl = PowerMockito.spy(new MVPlayerListener(core));
Field playerlistenerfield = MultiverseCore.class.getDeclaredField("playerListener");
playerlistenerfield.setAccessible(true);
playerlistenerfield.set(core, pl);
// Set entityListener
MVEntityListener el = spy(new MVEntityListener(core));
MVEntityListener el = PowerMockito.spy(new MVEntityListener(core));
Field entitylistenerfield = MultiverseCore.class.getDeclaredField("entityListener");
entitylistenerfield.setAccessible(true);
entitylistenerfield.set(core, el);
// Set weatherListener
MVWeatherListener wl = spy(new MVWeatherListener(core));
MVWeatherListener wl = PowerMockito.spy(new MVWeatherListener(core));
Field weatherlistenerfield = MultiverseCore.class.getDeclaredField("weatherListener");
weatherlistenerfield.setAccessible(true);
weatherlistenerfield.set(core, wl);
@@ -253,9 +264,9 @@ public class TestInstanceCreator {
when(commandSender.getServer()).thenReturn(mockServer);
when(commandSender.getName()).thenReturn("MockCommandSender");
when(commandSender.isPermissionSet(anyString())).thenReturn(true);
when(commandSender.isPermissionSet(isA(Permission.class))).thenReturn(true);
when(commandSender.isPermissionSet(ArgumentMatchers.isA(Permission.class))).thenReturn(true);
when(commandSender.hasPermission(anyString())).thenReturn(true);
when(commandSender.hasPermission(isA(Permission.class))).thenReturn(true);
when(commandSender.hasPermission(ArgumentMatchers.isA(Permission.class))).thenReturn(true);
when(commandSender.addAttachment(core)).thenReturn(null);
when(commandSender.isOp()).thenReturn(true);
@@ -10,8 +10,8 @@ package com.onarandombox.MultiverseCore.utils;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
public class Util {
private Util() {}
@@ -11,7 +11,7 @@ import org.bukkit.WorldCreator;
import org.mockito.ArgumentMatcher;
public class WorldCreatorMatcher implements ArgumentMatcher<WorldCreator> {
private final WorldCreator worldCreator;
private WorldCreator worldCreator;
private boolean careAboutSeeds = false;
private boolean careAboutGenerators = false;
@@ -1 +0,0 @@
mock-maker-inline