From 0b0b3c0088c42335c07d5e3dbdb29f3782d4c987 Mon Sep 17 00:00:00 2001 From: Liam Date: Wed, 26 Oct 2016 23:49:30 +0100 Subject: [PATCH 001/134] Updated Vault repo New vault repo is here: http://nexus.hc.to/content/repositories/pub_releases --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index b322f8d3e..2fdb461b8 100644 --- a/pom.xml +++ b/pom.xml @@ -27,7 +27,7 @@ vault-repo - http://nexus.theyeticave.net/content/repositories/pub_releases + http://nexus.hc.to/content/repositories/pub_releases From b3841adcc13c717a7e4d7b2c590700a013101407 Mon Sep 17 00:00:00 2001 From: httpdop Date: Sun, 6 Nov 2016 11:14:10 +0100 Subject: [PATCH 002/134] Update dependencies and versions --- pom.xml | 39 +++++++++++++++++++++------------------ 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/pom.xml b/pom.xml index 2fdb461b8..787ee6ca2 100644 --- a/pom.xml +++ b/pom.xml @@ -75,16 +75,16 @@ org.apache.maven.plugins maven-compiler-plugin - 2.3.2 + 3.5.1 - 1.6 - 1.6 + 1.8 + 1.8 com.google.code.maven-replacer-plugin maven-replacer-plugin - 1.3.8 + 1.4.1 prepare-package @@ -107,7 +107,7 @@ org.apache.maven.plugins maven-jar-plugin - 2.3.1 + 3.0.2 @@ -118,7 +118,7 @@ org.apache.maven.plugins maven-surefire-plugin - 2.11 + 2.19.1 methods 10 @@ -131,14 +131,14 @@ org.apache.maven.surefire surefire-junit47 - 2.11 + 2.19.1 org.apache.maven.plugins maven-checkstyle-plugin - 2.10 + 2.17 true ${project.basedir}/config/mv_checks.xml @@ -147,7 +147,7 @@ org.apache.maven.plugins maven-source-plugin - 2.1.2 + 3.0.1 attach-sources @@ -160,7 +160,7 @@ maven-javadoc-plugin - 2.8.1 + 2.10.4 javadoc-jar @@ -168,13 +168,16 @@ jar + + false + org.apache.maven.plugins maven-shade-plugin - 1.5 + 2.4.3 package @@ -262,7 +265,7 @@ org.spigotmc spigot-api - 1.9-R0.1-SNAPSHOT + 1.10.2-R0.1-SNAPSHOT compile @@ -343,40 +346,40 @@ org.codehaus.jettison jettison - 1.3.7 + 1.3.8 junit junit - 4.8.2 + 4.12 org.powermock powermock-module-junit4 - 1.4.9 + 1.6.5 jar test org.powermock powermock-api-easymock - 1.4.9 + 1.6.5 jar test org.powermock powermock-api-mockito - 1.4.9 + 1.6.6 jar test org.easymock easymock - 3.0 + 3.4 test From 3db57ee1d955c81e6b18f015c275fb092d128f6e Mon Sep 17 00:00:00 2001 From: Eric Stokes Date: Sat, 19 Nov 2016 13:02:19 -0700 Subject: [PATCH 003/134] Move to Java 7 (Maybe java 8 soon...) * Also bump CH to v10, which uses Java 7 * Probably don't use this build, I have to test it first... --- pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 787ee6ca2..592b00b14 100644 --- a/pom.xml +++ b/pom.xml @@ -77,8 +77,8 @@ maven-compiler-plugin 3.5.1 - 1.8 - 1.8 + 1.7 + 1.7 @@ -298,7 +298,7 @@ com.pneumaticraft.commandhandler CommandHandler - 8 + 10 jar compile From 8fdc0ad3dad96e6c5a420bafa97ce91e9abfb878 Mon Sep 17 00:00:00 2001 From: rlf Date: Sat, 19 Nov 2016 13:51:11 -0700 Subject: [PATCH 004/134] Fixed failing tests (thanks @rlf) * This is the test fixing portion of PR#1746 * This fixes using a HashMap and relying on the order of the values. --- .../MultiverseCore/TestWorldProperties.java | 7 +++++++ .../MultiverseCore/utils/MockWorldFactory.java | 11 +++-------- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/src/test/java/com/onarandombox/MultiverseCore/TestWorldProperties.java b/src/test/java/com/onarandombox/MultiverseCore/TestWorldProperties.java index bf53b71d4..b73116c3b 100644 --- a/src/test/java/com/onarandombox/MultiverseCore/TestWorldProperties.java +++ b/src/test/java/com/onarandombox/MultiverseCore/TestWorldProperties.java @@ -104,6 +104,9 @@ public void test() throws Exception { verify(mockCommandSender).sendMessage("Starting import of world 'world'..."); verify(mockCommandSender).sendMessage(ChatColor.GREEN + "Complete!"); + assertEquals(core.getServer().getWorlds().size(), 1); + assertEquals(core.getServer().getWorlds().get(0).getName(), "world"); + // Import a second world String[] netherArgs = new String[] { "import", "world_nether", "nether" }; core.onCommand(mockCommandSender, mockCommand, "", netherArgs); @@ -111,6 +114,10 @@ public void test() throws Exception { verify(mockCommandSender, VerificationModeFactory.times(2)).sendMessage( ChatColor.GREEN + "Complete!"); + assertEquals(core.getServer().getWorlds().size(), 2); + assertEquals(core.getServer().getWorlds().get(0).getName(), "world"); + assertEquals(core.getServer().getWorlds().get(1).getName(), "world_nether"); + // //////////////////////////////////////////////// // let's set some world-properties // we can test the API with this, too :D diff --git a/src/test/java/com/onarandombox/MultiverseCore/utils/MockWorldFactory.java b/src/test/java/com/onarandombox/MultiverseCore/utils/MockWorldFactory.java index fb2223cc7..c5b680690 100644 --- a/src/test/java/com/onarandombox/MultiverseCore/utils/MockWorldFactory.java +++ b/src/test/java/com/onarandombox/MultiverseCore/utils/MockWorldFactory.java @@ -24,12 +24,13 @@ import java.util.Map; import java.util.UUID; import java.util.WeakHashMap; +import java.util.LinkedHashMap; import static org.mockito.Mockito.*; public class MockWorldFactory { - private static final Map createdWorlds = new HashMap(); + private static final Map createdWorlds = new LinkedHashMap(); private static final Map worldUIDS = new HashMap(); private static final Map pvpStates = new WeakHashMap(); @@ -212,13 +213,7 @@ public static World getWorld(UUID worldUID) { } public static List getWorlds() { - // we have to invert the order! - ArrayList myList = new ArrayList(createdWorlds.values()); - List retList = new ArrayList(); - for (int i = (myList.size() - 1); i >= 0; i--) { - retList.add(myList.get(i)); - } - return retList; + return new ArrayList(createdWorlds.values()); } public static void clearWorlds() { From aba1f05c5b80f3779c695982c675f1098aaeb03f Mon Sep 17 00:00:00 2001 From: rlf Date: Sat, 19 Nov 2016 14:17:26 -0700 Subject: [PATCH 005/134] Misc documentation fixes from @rlf --- .../com/onarandombox/MultiverseCore/MultiverseCore.java | 5 +++++ .../com/onarandombox/MultiverseCore/api/MVWorldManager.java | 4 ++-- .../com/onarandombox/MultiverseCore/api/WorldPurger.java | 2 +- .../com/onarandombox/MultiverseCore/utils/FancyMessage.java | 6 +++--- .../onarandombox/MultiverseCore/utils/MVPermissions.java | 2 +- .../com/onarandombox/MultiverseCore/utils/PurgeWorlds.java | 2 +- 6 files changed, 13 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java index 8bf674498..e641dad6a 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java @@ -138,6 +138,11 @@ public MultiverseCore() { /** * This is for unit testing. * @deprecated + * @param loader deprecated + * @param server deprecated + * @param description deprecated + * @param dataFolder deprecated + * @param file deprecated */ @Deprecated public MultiverseCore(PluginLoader loader, Server server, PluginDescriptionFile description, File dataFolder, File file) { diff --git a/src/main/java/com/onarandombox/MultiverseCore/api/MVWorldManager.java b/src/main/java/com/onarandombox/MultiverseCore/api/MVWorldManager.java index 8015f507c..3eb96e2d5 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/api/MVWorldManager.java +++ b/src/main/java/com/onarandombox/MultiverseCore/api/MVWorldManager.java @@ -199,7 +199,7 @@ boolean addWorld(String name, Environment env, String seedString, WorldType type boolean isMVWorld(World world); /** - * Load the Worlds & Settings from the configuration file. + * Load the Worlds & Settings from the configuration file. * * @param forceLoad If set to true, this will perform a total * reset and not just load new worlds. @@ -207,7 +207,7 @@ boolean addWorld(String name, Environment env, String seedString, WorldType type void loadWorlds(boolean forceLoad); /** - * Loads the Worlds & Settings for any worlds that bukkit loaded before us. + * Loads the Worlds & Settings for any worlds that bukkit loaded before us. *

* This way people will _always_ have some worlds in the list. */ diff --git a/src/main/java/com/onarandombox/MultiverseCore/api/WorldPurger.java b/src/main/java/com/onarandombox/MultiverseCore/api/WorldPurger.java index a52b73f30..b0ccad276 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/api/WorldPurger.java +++ b/src/main/java/com/onarandombox/MultiverseCore/api/WorldPurger.java @@ -17,7 +17,7 @@ public interface WorldPurger { void purgeWorlds(List worlds); /** - * Convenience method for {@link #purgeWorld(CommandSender, MultiverseWorld, List, boolean, boolean)} that takes the settings from the world-config. + * Convenience method for {@link #purgeWorld(MultiverseWorld, java.util.List, boolean, boolean)} that takes the settings from the world-config. * * @param world The {@link MultiverseWorld}. */ diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/FancyMessage.java b/src/main/java/com/onarandombox/MultiverseCore/utils/FancyMessage.java index e02c010e0..7775e9661 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/FancyMessage.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/FancyMessage.java @@ -22,9 +22,9 @@ public class FancyMessage implements FancyText { * Allows easy creation of an alternating colored list. * TODO: Documentation! Why does CheckStyle just ignore this? * - * @param title - * @param message - * @param scheme + * @param title The title. + * @param message The body of the message. + * @param scheme The color scheme to use for easy styling. */ public FancyMessage(String title, String message, FancyColorScheme scheme) { this.title = title; diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/MVPermissions.java b/src/main/java/com/onarandombox/MultiverseCore/utils/MVPermissions.java index 2ea793578..d1c078e72 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/MVPermissions.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/MVPermissions.java @@ -230,7 +230,7 @@ public void tellMeWhyICantDoThis(CommandSender asker, CommandSender playerInQues * * @param sender Who is requesting the permission. * @param node The permission node in string format; multiverse.core.list.worlds for example. - * @param isOpRequired @Deprecated. This is not used for anything anymore. + * @param isOpRequired deprecated This is not used for anything anymore. * @return True if they have that permission or any parent. */ @Override diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/PurgeWorlds.java b/src/main/java/com/onarandombox/MultiverseCore/utils/PurgeWorlds.java index 48ed4a2af..c932d2d88 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/PurgeWorlds.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/PurgeWorlds.java @@ -27,7 +27,7 @@ /** * Utility class that removes animals from worlds that don't belong there. * - * @deprecated Use instead: {@link WorldPurger} and {@link SimpleWorldPurger}. + * @deprecated Use instead: {@link com.onarandombox.MultiverseCore.api.WorldPurger} and {@link SimpleWorldPurger}. */ @Deprecated public class PurgeWorlds { From f3a420d85cc0a96cfc58c3ea5cfaca8ab153eb9b Mon Sep 17 00:00:00 2001 From: Eric Stokes Date: Sat, 19 Nov 2016 14:18:12 -0700 Subject: [PATCH 006/134] Added additional properties to the test checks for world properties --- .../onarandombox/MultiverseCore/TestWorldProperties.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/test/java/com/onarandombox/MultiverseCore/TestWorldProperties.java b/src/test/java/com/onarandombox/MultiverseCore/TestWorldProperties.java index b73116c3b..b74957c1b 100644 --- a/src/test/java/com/onarandombox/MultiverseCore/TestWorldProperties.java +++ b/src/test/java/com/onarandombox/MultiverseCore/TestWorldProperties.java @@ -19,6 +19,7 @@ import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.World; +import org.bukkit.WorldType; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; @@ -106,6 +107,9 @@ public void test() throws Exception { assertEquals(core.getServer().getWorlds().size(), 1); assertEquals(core.getServer().getWorlds().get(0).getName(), "world"); + assertEquals(core.getServer().getWorlds().get(0).getEnvironment(), World.Environment.NORMAL); + assertEquals(core.getServer().getWorlds().get(0).getWorldType(), WorldType.NORMAL); + // Import a second world String[] netherArgs = new String[] { "import", "world_nether", "nether" }; @@ -117,6 +121,8 @@ public void test() throws Exception { assertEquals(core.getServer().getWorlds().size(), 2); assertEquals(core.getServer().getWorlds().get(0).getName(), "world"); assertEquals(core.getServer().getWorlds().get(1).getName(), "world_nether"); + assertEquals(core.getServer().getWorlds().get(1).getEnvironment(), World.Environment.NETHER); + assertEquals(core.getServer().getWorlds().get(1).getWorldType(), WorldType.NORMAL); // //////////////////////////////////////////////// // let's set some world-properties From 67d172fd08c3462ef748eaaa96664d5ef2e6829c Mon Sep 17 00:00:00 2001 From: Eric Stokes Date: Sat, 19 Nov 2016 14:30:04 -0700 Subject: [PATCH 007/134] Removed redundantThrows checkstyle rule, it's gone in 6.2+ See: checkstyle/checkstyle#473 --- config/mv_checks.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/config/mv_checks.xml b/config/mv_checks.xml index f28ddaf91..0c660d8d9 100644 --- a/config/mv_checks.xml +++ b/config/mv_checks.xml @@ -115,7 +115,6 @@ - - + + org.spigotmc spigot-api - 1.10.2-R0.1-SNAPSHOT + 1.11.2-R0.1-SNAPSHOT compile - + From 2ed59a866ffb975949f7b98d7921b8b8126cea44 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Fri, 16 Jun 2017 22:08:51 -0400 Subject: [PATCH 018/134] Updated to Buscript 2.0. This reduces the size of the plugin jar by over ONE MEGABYTE!! --- pom.xml | 2 +- .../java/com/onarandombox/MultiverseCore/MultiverseCore.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index be882a62a..91bff78c4 100644 --- a/pom.xml +++ b/pom.xml @@ -307,7 +307,7 @@ com.dumptruckman.minecraft buscript - 1.0 + 2.0-SNAPSHOT jar compile diff --git a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java index 7dbc4e7c6..d696da7c0 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java @@ -356,7 +356,7 @@ public void onEnable() { private void initializeBuscript() { buscript = new Buscript(this); // Add global variable "multiverse" to javascript environment - buscript.getGlobalScope().put("multiverse", buscript.getGlobalScope(), this); + buscript.setScriptVariable("multiverse", this); } /** From 54209e153500fb9cff1e7e5b8ae84df8e4f33a40 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Sat, 17 Jun 2017 01:03:22 -0400 Subject: [PATCH 019/134] Testing new webhook --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 41d090ee0..3d4af1fc2 100644 --- a/README.md +++ b/README.md @@ -13,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. + From d18581828d257b51f5d918720a1bbdf6a4f9fb2a Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Sun, 9 Jul 2017 09:36:02 -0400 Subject: [PATCH 020/134] Exclude old Bukkit from SerializationConfig. --- pom.xml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/pom.xml b/pom.xml index 91bff78c4..1469e7fc6 100644 --- a/pom.xml +++ b/pom.xml @@ -283,6 +283,12 @@ 1.7 jar compile + + + org.bukkit + bukkit + + From bcd7fcaee7b257a72fd1f0870c22453d3b8745c7 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Sun, 9 Jul 2017 09:36:39 -0400 Subject: [PATCH 021/134] Build for Java 8. Might fix Travis and Circle... --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 1469e7fc6..1f4a72dcb 100644 --- a/pom.xml +++ b/pom.xml @@ -77,8 +77,8 @@ maven-compiler-plugin 3.5.1 - 1.7 - 1.7 + 1.8 + 1.8 From 63abf33414b479e8908ba1fa05e5dd5bb259f9c4 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Sun, 9 Jul 2017 11:30:45 -0400 Subject: [PATCH 022/134] Config travis and circle for Java 8. Resolves #1834 --- .travis.yml | 2 +- circle.yml | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) create mode 100644 circle.yml diff --git a/.travis.yml b/.travis.yml index 5767a6d4f..a64f9f60d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,6 @@ language: java jdk: - - openjdk7 + - oraclejdk8 notifications: email: false before_install: diff --git a/circle.yml b/circle.yml new file mode 100644 index 000000000..593dfcb24 --- /dev/null +++ b/circle.yml @@ -0,0 +1,3 @@ +machine: + java: + version: oraclejdk8 \ No newline at end of file From ceb6850670e2918fae9cb1728ff8d32967c39183 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Sun, 9 Jul 2017 11:36:23 -0400 Subject: [PATCH 023/134] Bump version to 2.5.1. --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 1f4a72dcb..bdca20f4d 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.onarandombox.multiversecore Multiverse-Core - 2.5.1-SNAPSHOT + 2.5.1 Multiverse-Core World Management Plugin From 467ec809b59a2479948dc2682b58f0a4dc63d09b Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Sun, 9 Jul 2017 18:53:50 -0400 Subject: [PATCH 024/134] Bump version to 2.6.0-SNAPSHOT for significant incoming changes. --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index bdca20f4d..078ca3a70 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.onarandombox.multiversecore Multiverse-Core - 2.5.1 + 2.6.0-SNAPSHOT Multiverse-Core World Management Plugin From 4878395460f72993ad8c71253ad5f4158932734b Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Sun, 9 Jul 2017 18:54:49 -0400 Subject: [PATCH 025/134] Bumped protocol version to 21 for upcoming addition of Kotlin lib. --- .../java/com/onarandombox/MultiverseCore/MultiverseCore.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java index d696da7c0..b78b51d48 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java @@ -123,7 +123,7 @@ * The implementation of the Multiverse-{@link Core}. */ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core { - private static final int PROTOCOL = 20; + private static final int PROTOCOL = 21; // TODO: Investigate if this one is really needed to be static. // Doubt it. -- FernFerret private static Map teleportQueue = new HashMap(); From bc20ecbe6032663484acfe022f4c1a7af945c3fa Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Wed, 12 Jul 2017 22:58:33 -0400 Subject: [PATCH 026/134] Hotfix for #1836. --- .../onarandombox/MultiverseCore/commands/ImportCommand.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/ImportCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/ImportCommand.java index be81297b8..83ff72cfe 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/ImportCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/ImportCommand.java @@ -131,6 +131,11 @@ public void runCommand(CommandSender sender, List args) { File worldFile = new File(this.plugin.getServer().getWorldContainer(), worldName); + if (!checkIfIsWorld(worldFile)) { + sender.sendMessage(ChatColor.RED + "Sorry, but that does not look like a world!"); + return; + } + String generator = CommandHandler.getFlag("-g", args); boolean useSpawnAdjust = true; for (String s : args) { From 2b4d386eb20e8c5bef9a08ed4a2a5ae9d9f284c1 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Thu, 13 Jul 2017 15:47:43 -0400 Subject: [PATCH 027/134] Removed unnecessary for #1836. --- .../onarandombox/MultiverseCore/commands/ImportCommand.java | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/ImportCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/ImportCommand.java index 83ff72cfe..be81297b8 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/ImportCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/ImportCommand.java @@ -131,11 +131,6 @@ public void runCommand(CommandSender sender, List args) { File worldFile = new File(this.plugin.getServer().getWorldContainer(), worldName); - if (!checkIfIsWorld(worldFile)) { - sender.sendMessage(ChatColor.RED + "Sorry, but that does not look like a world!"); - return; - } - String generator = CommandHandler.getFlag("-g", args); boolean useSpawnAdjust = true; for (String s : args) { From 532ffacf5a0a7f1c253eb8462021d55e15bc65f3 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Thu, 22 Feb 2018 18:11:12 -0500 Subject: [PATCH 028/134] Added relativity options to ExactDestination. Implements #1892. --- .../destination/ExactDestination.java | 59 ++++++++++++++++--- 1 file changed, 52 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/destination/ExactDestination.java b/src/main/java/com/onarandombox/MultiverseCore/destination/ExactDestination.java index fe46bbea7..081628933 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/destination/ExactDestination.java +++ b/src/main/java/com/onarandombox/MultiverseCore/destination/ExactDestination.java @@ -21,9 +21,10 @@ * An exact {@link MVDestination}. */ public class ExactDestination implements MVDestination { - private final String coordRegex = "(-?[\\d]+\\.?[\\d]*),(-?[\\d]+\\.?[\\d]*),(-?[\\d]+\\.?[\\d]*)"; + private final String coordRegex = "(-?[\\d]+\\.?[\\d]*|~-?[\\d]+\\.?[\\d]*|~),(-?[\\d]+\\.?[\\d]*|~-?[\\d]+\\.?[\\d]*|~),(-?[\\d]+\\.?[\\d]*|~-?[\\d]+\\.?[\\d]*|~)"; private boolean isValid; private Location location; + private boolean relativeX, relativeY, relativeZ; /** * {@inheritDoc} @@ -88,7 +89,20 @@ public boolean isThisType(JavaPlugin plugin, String destination) { */ @Override public Location getLocation(Entity e) { - return this.location; + Location loc = this.location.clone(); + if (relativeX || relativeY || relativeZ) { + Location eLoc = e.getLocation(); + loc.add(relativeX ? eLoc.getX() : 0, relativeY ? eLoc.getY() : 0, relativeZ ? eLoc.getZ() : 0); + // Since the location is relative, it makes sense to use the entity's pitch and yaw unless those were + // specified in the destination. + if (loc.getPitch() == 0) { + loc.setPitch(eLoc.getPitch()); + } + if (loc.getYaw() == 0) { + loc.setYaw(eLoc.getYaw()); + } + } + return loc; } /** @@ -134,11 +148,42 @@ public void setDestination(JavaPlugin plugin, String destination) { double[] coords = new double[3]; String[] coordString = parsed.get(2).split(","); for (int i = 0; i < 3; i++) { - try { - coords[i] = Double.parseDouble(coordString[i]); - } catch (NumberFormatException e) { - this.isValid = false; - return; + String[] relSplit = coordString[i].split("~"); + boolean relative = false; + if (relSplit.length == 0) { + // coord is "~" form + relative = true; + coords[i] = 0; + } else if (relSplit.length == 1) { + // coord is "123" form + try { + coords[i] = Double.parseDouble(relSplit[0]); + } catch (NumberFormatException e) { + this.isValid = false; + return; + } + } else { + // coord is "~123" form + relative = true; + try { + coords[i] = Double.parseDouble(relSplit[1]); + } catch (NumberFormatException e) { + this.isValid = false; + return; + } + } + if (relative) { + switch (i) { + case 0: + relativeX = true; + break; + case 1: + relativeY = true; + break; + case 2: + relativeZ = true; + break; + } } } this.location.setX(coords[0]); From 284b3179ad99a59336a3db894f62d9a96c8979a9 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Mon, 23 Jul 2018 14:15:44 -0400 Subject: [PATCH 029/134] Version 2.6.0 release. --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 078ca3a70..93f7ed4c2 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.onarandombox.multiversecore Multiverse-Core - 2.6.0-SNAPSHOT + 2.6.0 Multiverse-Core World Management Plugin From fb505ab16165397422275a9c4d434cced06df967 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Mon, 23 Jul 2018 14:16:29 -0400 Subject: [PATCH 030/134] Bumped version to 2.6.1-SNAPSHOT for continued development. --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 93f7ed4c2..9a4b59d38 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.onarandombox.multiversecore Multiverse-Core - 2.6.0 + 2.6.1-SNAPSHOT Multiverse-Core World Management Plugin From 658b5219c3101c286683d87b2b226049b7fc6c26 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Wed, 23 Jan 2019 22:29:12 -0500 Subject: [PATCH 031/134] Bumped version to 2.7.0-SNAPSHOT. --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 9a4b59d38..a68ebe973 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.onarandombox.multiversecore Multiverse-Core - 2.6.1-SNAPSHOT + 2.7.0-SNAPSHOT Multiverse-Core World Management Plugin From f7bbb5029b10349e3cb2dd70c44cf112f03b2d2d Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Wed, 23 Jan 2019 22:29:49 -0500 Subject: [PATCH 032/134] Bumped protocol to 22. --- .../java/com/onarandombox/MultiverseCore/MultiverseCore.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java index b78b51d48..e111c833a 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java @@ -123,7 +123,7 @@ * The implementation of the Multiverse-{@link Core}. */ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core { - private static final int PROTOCOL = 21; + private static final int PROTOCOL = 22; // TODO: Investigate if this one is really needed to be static. // Doubt it. -- FernFerret private static Map teleportQueue = new HashMap(); From 01f549f4087d371047fd14e5f5b03beb7fc57dd7 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Wed, 23 Jan 2019 23:50:47 -0500 Subject: [PATCH 033/134] Updated Multiverse-Core for Bukkit 1.13.2. --- pom.xml | 35 +- .../onarandombox/MultiverseCore/MVWorld.java | 6 +- .../MultiverseCore/MultiverseCore.java | 24 +- .../MultiverseCore/WorldProperties.java | 9 +- .../onarandombox/MultiverseCore/api/Core.java | 11 - .../MultiverseCore/api/MultiverseWorld.java | 14 +- .../MultiverseCore/commands/CoordCommand.java | 2 +- .../configuration/EntryFee.java | 33 +- .../listeners/MVMapListener.java | 2 +- .../listeners/MVPlayerListener.java | 2 +- .../listeners/MVPortalListener.java | 4 +- .../MultiverseCore/utils/BlockSafety.java | 281 --------- .../MultiverseCore/utils/MVEconomist.java | 569 +++++++++--------- .../MultiverseCore/utils/PermissionTools.java | 5 +- .../MultiverseCore/utils/SafeTTeleporter.java | 358 ----------- .../utils/SimpleBlockSafety.java | 88 +-- .../utils/SimpleSafeTTeleporter.java | 10 +- .../TestEntryFeeConversion.java | 63 ++ .../MultiverseCore/TestWorldProperties.java | 9 +- .../utils/MockWorldFactory.java | 2 - 20 files changed, 472 insertions(+), 1055 deletions(-) delete mode 100644 src/main/java/com/onarandombox/MultiverseCore/utils/BlockSafety.java delete mode 100644 src/main/java/com/onarandombox/MultiverseCore/utils/SafeTTeleporter.java create mode 100644 src/test/java/com/onarandombox/MultiverseCore/TestEntryFeeConversion.java diff --git a/pom.xml b/pom.xml index a68ebe973..68d509879 100644 --- a/pom.xml +++ b/pom.xml @@ -29,6 +29,10 @@ vault-repo http://nexus.hc.to/content/repositories/pub_releases + + minebench-repo + https://repo.minebench.de/ + elmakers-repo @@ -250,6 +254,19 @@ + + se.eris + notnull-instrumenter-maven-plugin + 0.6.8 + + + + instrument + tests-instrument + + + + @@ -263,9 +280,9 @@ - org.spigotmc - spigot-api - 1.12-R0.1-SNAPSHOT + org.bukkit + bukkit + 1.13.2-R0.1-SNAPSHOT compile @@ -355,6 +372,13 @@ 1.3.8 + + org.jetbrains + annotations + 16.0.2 + jar + compile + junit @@ -388,6 +412,11 @@ 3.4 test + + de.themoep.idconverter + mappings + 1.2-SNAPSHOT + diff --git a/src/main/java/com/onarandombox/MultiverseCore/MVWorld.java b/src/main/java/com/onarandombox/MultiverseCore/MVWorld.java index ce8770cd5..4007352ac 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MVWorld.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MVWorld.java @@ -24,6 +24,7 @@ import org.bukkit.Difficulty; import org.bukkit.GameMode; import org.bukkit.Location; +import org.bukkit.Material; import org.bukkit.World; import org.bukkit.World.Environment; import org.bukkit.WorldType; @@ -33,6 +34,7 @@ import org.bukkit.permissions.Permission; import org.bukkit.permissions.PermissionDefault; import org.bukkit.util.Vector; +import org.jetbrains.annotations.Nullable; import org.json.simple.JSONObject; import java.util.Collections; @@ -943,7 +945,7 @@ public Permission getAccessPermission() { * {@inheritDoc} */ @Override - public int getCurrency() { + public Material getCurrency() { return this.props.getCurrency(); } @@ -951,7 +953,7 @@ public int getCurrency() { * {@inheritDoc} */ @Override - public void setCurrency(int currency) { + public void setCurrency(@Nullable Material currency) { this.props.setCurrency(currency); } diff --git a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java index e111c833a..85a254bd4 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java @@ -84,12 +84,14 @@ import com.onarandombox.MultiverseCore.utils.VaultHandler; import com.onarandombox.MultiverseCore.utils.WorldManager; import com.pneumaticraft.commandhandler.CommandHandler; +import de.themoep.idconverter.IdMappings; import me.main__.util.SerializationConfig.NoSuchPropertyException; import me.main__.util.SerializationConfig.SerializationConfig; import org.bukkit.ChatColor; import org.bukkit.Difficulty; import org.bukkit.GameMode; import org.bukkit.Location; +import org.bukkit.Material; import org.bukkit.Server; import org.bukkit.World.Environment; import org.bukkit.command.Command; @@ -638,8 +640,15 @@ private void migrateWorldConfig() { // SUPPRESS CHECKSTYLE: MethodLength // migrate entryfee if (section.isConfigurationSection("entryfee")) { ConfigurationSection feeSection = section.getConfigurationSection("entryfee"); - if (feeSection.isInt("currency")) - world.setCurrency(feeSection.getInt("currency")); + if (feeSection.isInt("currency")) { + int oldCurrencyItemId = feeSection.getInt("currency", -1); + if (oldCurrencyItemId >= 0) { + String flatteningType = IdMappings.getById(Integer.toString(oldCurrencyItemId)) + .getFlatteningType(); + world.setCurrency(Material.matchMaterial(flatteningType)); + } + world.setCurrency(null); + } if (feeSection.isDouble("amount")) world.setPrice(feeSection.getDouble("amount")); @@ -885,17 +894,6 @@ public MVPlayerSession getPlayerSession(Player player) { } } - /** - * {@inheritDoc} - * - * @deprecated This is deprecated. - */ - @Override - @Deprecated - public com.onarandombox.MultiverseCore.utils.SafeTTeleporter getTeleporter() { - return new com.onarandombox.MultiverseCore.utils.SafeTTeleporter(this); - } - /** * {@inheritDoc} */ diff --git a/src/main/java/com/onarandombox/MultiverseCore/WorldProperties.java b/src/main/java/com/onarandombox/MultiverseCore/WorldProperties.java index 89ad4e815..1e882c712 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/WorldProperties.java +++ b/src/main/java/com/onarandombox/MultiverseCore/WorldProperties.java @@ -8,6 +8,7 @@ import com.onarandombox.MultiverseCore.enums.AllowedPortalType; import com.onarandombox.MultiverseCore.enums.EnglishChatColor; import com.onarandombox.MultiverseCore.enums.EnglishChatStyle; +import de.themoep.idconverter.IdMappings; import me.main__.util.SerializationConfig.IllegalPropertyValueException; import me.main__.util.SerializationConfig.Property; import me.main__.util.SerializationConfig.SerializationConfig; @@ -18,8 +19,10 @@ import org.bukkit.Difficulty; import org.bukkit.GameMode; import org.bukkit.Location; +import org.bukkit.Material; import org.bukkit.World.Environment; import org.bukkit.configuration.serialization.SerializableAs; +import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collections; @@ -261,7 +264,7 @@ public Long deserialize(String serialized, Class wanted) throws IllegalPro @Property(description = "Sorry, 'animals' must either be: true or false.") private volatile SpawnSettings spawning; @Property - private volatile EntryFee entryfee; + volatile EntryFee entryfee; @Property(description = "Sorry, 'hunger' must either be: true or false.") private volatile boolean hunger; @Property(description = "Sorry, 'autoheal' must either be: true or false.") @@ -496,11 +499,11 @@ public boolean setRespawnToWorld(String respawnToWorld) { return this.setPropertyValueUnchecked("respawnWorld", respawnToWorld); } - public int getCurrency() { + public Material getCurrency() { return this.entryfee.getCurrency(); } - public void setCurrency(int currency) { + public void setCurrency(@Nullable Material currency) { this.setPropertyValueUnchecked("entryfee.currency", currency); } diff --git a/src/main/java/com/onarandombox/MultiverseCore/api/Core.java b/src/main/java/com/onarandombox/MultiverseCore/api/Core.java index 907d033bc..ff8513d4c 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/api/Core.java +++ b/src/main/java/com/onarandombox/MultiverseCore/api/Core.java @@ -70,17 +70,6 @@ public interface Core { */ MVPlayerSession getPlayerSession(Player player); - /** - * Gets the instantiated Safe-T-Teleporter for performing - * safe teleports. - * - * @return A non-null {@link SafeTTeleporter}. - * - * @deprecated Use {@link #getSafeTTeleporter()} instead. - */ - @Deprecated - com.onarandombox.MultiverseCore.utils.SafeTTeleporter getTeleporter(); - /** * Multiverse uses an advanced permissions setup, this object * simplifies getting/setting permissions. diff --git a/src/main/java/com/onarandombox/MultiverseCore/api/MultiverseWorld.java b/src/main/java/com/onarandombox/MultiverseCore/api/MultiverseWorld.java index 5ddffafba..3561f49e0 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/api/MultiverseWorld.java +++ b/src/main/java/com/onarandombox/MultiverseCore/api/MultiverseWorld.java @@ -13,10 +13,12 @@ import org.bukkit.Difficulty; import org.bukkit.GameMode; import org.bukkit.Location; +import org.bukkit.Material; import org.bukkit.World; import org.bukkit.WorldType; import org.bukkit.command.CommandSender; import org.bukkit.permissions.Permission; +import org.jetbrains.annotations.Nullable; import java.util.List; @@ -511,19 +513,21 @@ public interface MultiverseWorld { void setPrice(double price); /** - * Gets the Type of currency that will be used when users enter this world. + * Gets the type of currency that will be used when users enter this world. A value of null indicates a non-item + * based currency is used. * - * @return The Type of currency that will be used when users enter this world. + * @return The type of currency that will be used when users enter this world. */ - int getCurrency(); + @Nullable + Material getCurrency(); /** * Sets the type of item that will be required given the price is not 0. - * Use -1 to use an AllPay economy, or any valid itemid + * Use a value of null to specify a non-item based currency. * * @param item The Type of currency that will be used when users enter this world. */ - void setCurrency(int item); + void setCurrency(@Nullable Material item); /** * Gets the world players will respawn in if they die in this one. diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/CoordCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/CoordCommand.java index 944d8029c..485cc3701 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/CoordCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/CoordCommand.java @@ -62,7 +62,7 @@ public void runCommand(CommandSender sender, List args) { df.setMaximumFractionDigits(2); p.sendMessage(ChatColor.AQUA + "Coordinates: " + ChatColor.WHITE + plugin.getLocationManipulation().strCoords(p.getLocation())); p.sendMessage(ChatColor.AQUA + "Direction: " + ChatColor.WHITE + plugin.getLocationManipulation().getDirection(p.getLocation())); - p.sendMessage(ChatColor.AQUA + "Block: " + ChatColor.WHITE + Material.getMaterial(world.getBlockTypeIdAt(p.getLocation()))); + p.sendMessage(ChatColor.AQUA + "Block: " + ChatColor.WHITE + world.getBlockAt(p.getLocation()).getType()); } else { sender.sendMessage("This command needs to be used from a Player."); } diff --git a/src/main/java/com/onarandombox/MultiverseCore/configuration/EntryFee.java b/src/main/java/com/onarandombox/MultiverseCore/configuration/EntryFee.java index e754e6820..42a1d4c39 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/configuration/EntryFee.java +++ b/src/main/java/com/onarandombox/MultiverseCore/configuration/EntryFee.java @@ -2,10 +2,15 @@ import java.util.Map; +import de.themoep.idconverter.IdMappings; +import me.main__.util.SerializationConfig.IllegalPropertyValueException; import me.main__.util.SerializationConfig.Property; import me.main__.util.SerializationConfig.SerializationConfig; +import me.main__.util.SerializationConfig.Serializor; +import org.bukkit.Material; import org.bukkit.configuration.serialization.SerializableAs; +import org.jetbrains.annotations.Nullable; /** * Entryfee-settings. @@ -14,8 +19,9 @@ public class EntryFee extends SerializationConfig { @Property private double amount; - @Property - private int currency; + @Property(serializor = EntryFeeCurrencySerializor.class) + @Nullable + private Material currency; public EntryFee() { super(); @@ -31,7 +37,7 @@ public EntryFee(Map values) { @Override protected void setDefaults() { amount = 0D; - currency = -1; + currency = null; } /** @@ -44,7 +50,8 @@ public double getAmount() { /** * @return the currency */ - public int getCurrency() { + @Nullable + public Material getCurrency() { return currency; } @@ -60,7 +67,23 @@ public void setAmount(double amount) { * Sets the currency. * @param currency The new value. */ - public void setCurrency(int currency) { + public void setCurrency(@Nullable Material currency) { this.currency = currency; } + + public static final class EntryFeeCurrencySerializor implements Serializor { + @Override + public String serialize(Material material) { + return material.toString(); + } + + @Override + public Material deserialize(Object o, Class aClass) throws IllegalPropertyValueException { + IdMappings.Mapping mapping = IdMappings.getById(o.toString()); + if (mapping != null) { + return Material.matchMaterial(mapping.getFlatteningType()); + } + return Material.matchMaterial(o.toString()); + } + } } diff --git a/src/main/java/com/onarandombox/MultiverseCore/listeners/MVMapListener.java b/src/main/java/com/onarandombox/MultiverseCore/listeners/MVMapListener.java index fe039a6c3..2443337a3 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/listeners/MVMapListener.java +++ b/src/main/java/com/onarandombox/MultiverseCore/listeners/MVMapListener.java @@ -29,7 +29,7 @@ public MVMapListener(final MultiverseCore plugin) { public void mapInitialize(final MapInitializeEvent event) { for (final Player player : Bukkit.getOnlinePlayers()) { if ((player.getItemInHand().getType() == Material.MAP - || player.getItemInHand().getType() == Material.EMPTY_MAP) + || player.getItemInHand().getType() == Material.FILLED_MAP) && player.getItemInHand().getDurability() == event.getMap().getId()) { final Location playerLoc = player.getLocation(); final MapView map = event.getMap(); diff --git a/src/main/java/com/onarandombox/MultiverseCore/listeners/MVPlayerListener.java b/src/main/java/com/onarandombox/MultiverseCore/listeners/MVPlayerListener.java index 190e494f0..ad9356098 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/listeners/MVPlayerListener.java +++ b/src/main/java/com/onarandombox/MultiverseCore/listeners/MVPlayerListener.java @@ -252,7 +252,7 @@ public void playerPortalCheck(PlayerPortalEvent event) { // REMEMBER! getTo MAY be NULL HERE!!! // If the player was actually outside of the portal, adjust the from location - if (event.getFrom().getWorld().getBlockAt(event.getFrom()).getType() != Material.PORTAL) { + if (event.getFrom().getWorld().getBlockAt(event.getFrom()).getType() != Material.NETHER_PORTAL) { Location newloc = this.plugin.getSafeTTeleporter().findPortalBlockNextTo(event.getFrom()); // TODO: Fix this. Currently, we only check for PORTAL blocks. I'll have to figure out what // TODO: we want to do here. diff --git a/src/main/java/com/onarandombox/MultiverseCore/listeners/MVPortalListener.java b/src/main/java/com/onarandombox/MultiverseCore/listeners/MVPortalListener.java index 75b64df69..31d6f4693 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/listeners/MVPortalListener.java +++ b/src/main/java/com/onarandombox/MultiverseCore/listeners/MVPortalListener.java @@ -71,10 +71,10 @@ public void portalForm(PlayerInteractEvent event) { if (event.getAction() != Action.RIGHT_CLICK_BLOCK) { return; } - if (event.getClickedBlock().getType() != Material.ENDER_PORTAL_FRAME) { + if (event.getClickedBlock().getType() != Material.END_PORTAL_FRAME) { return; } - if (event.getItem() == null || event.getItem().getType() != Material.EYE_OF_ENDER) { + if (event.getItem() == null || event.getItem().getType() != Material.ENDER_EYE) { return; } MultiverseWorld world = this.plugin.getMVWorldManager().getMVWorld(event.getPlayer().getWorld()); diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/BlockSafety.java b/src/main/java/com/onarandombox/MultiverseCore/utils/BlockSafety.java deleted file mode 100644 index 562e70d05..000000000 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/BlockSafety.java +++ /dev/null @@ -1,281 +0,0 @@ -/****************************************************************************** - * Multiverse 2 Copyright (c) the Multiverse Team 2011. * - * 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.utils; - -import com.dumptruckman.minecraft.util.Logging; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.entity.Minecart; -import org.bukkit.entity.Vehicle; - -/** - * Used to determine block/location-related facts. - * - * @deprecated Use instead: {@link com.onarandombox.MultiverseCore.api.BlockSafety} and {@link SimpleBlockSafety}. - */ -@Deprecated -public class BlockSafety { - - /** - * This function checks whether the block at the given coordinates are above air or not. - * @param l The {@link Location} of the block. - * @return True if the block at that {@link Location} is above air. - */ - public boolean isBlockAboveAir(Location l) { - Location downOne = l.clone(); - downOne.setY(downOne.getY() - 1); - return (downOne.getBlock().getType() == Material.AIR); - } - - // TODO maybe remove this? - private boolean blockIsNotSafe(World world, double x, double y, double z) { - return !playerCanSpawnHereSafely(world, x, y, z); - } - - /** - * Checks if a player can spawn safely at the given coordinates. - * @param world The {@link World}. - * @param x The x-coordinate. - * @param y The y-coordinate. - * @param z The z-coordinate. - * @return True if a player can spawn safely at the given coordinates. - */ - public boolean playerCanSpawnHereSafely(World world, double x, double y, double z) { - Location l = new Location(world, x, y, z); - return playerCanSpawnHereSafely(l); - } - - /** - * This function checks whether the block at the coordinates given is safe or not by checking for Lava/Fire/Air - * etc. This also ensures there is enough space for a player to spawn! - * - * @param l The {@link Location} - * @return Whether the player can spawn safely at the given {@link Location} - */ - public boolean playerCanSpawnHereSafely(Location l) { - if (l == null) { - // Can't safely spawn at a null location! - return false; - } - - World world = l.getWorld(); - Location actual = l.clone(); - Location upOne = l.clone(); - Location downOne = l.clone(); - upOne.setY(upOne.getY() + 1); - downOne.setY(downOne.getY() - 1); - - if (this.isSolidBlock(world.getBlockAt(actual).getType()) - || this.isSolidBlock(upOne.getBlock().getType())) { - Logging.finest("Error Here (Actual)? (%s)[%s]", actual.getBlock().getType(), - this.isSolidBlock(actual.getBlock().getType())); - Logging.finest("Error Here (upOne)? (%s)[%s]", upOne.getBlock().getType(), - this.isSolidBlock(upOne.getBlock().getType())); - return false; - } - - if (downOne.getBlock().getType() == Material.LAVA || downOne.getBlock().getType() == Material.STATIONARY_LAVA) { - Logging.finest("Error Here (downOne)? (%s)[%s]", downOne.getBlock().getType(), - this.isSolidBlock(downOne.getBlock().getType())); - return false; - } - - if (downOne.getBlock().getType() == Material.FIRE) { - Logging.finest("There's fire below! (%s)[%s]", actual.getBlock().getType(), - this.isSolidBlock(actual.getBlock().getType())); - return false; - } - - if (isBlockAboveAir(actual)) { - Logging.finest("Is block above air [%s]", isBlockAboveAir(actual)); - Logging.finest("Has 2 blocks of water below [%s]", this.hasTwoBlocksofWaterBelow(actual)); - return this.hasTwoBlocksofWaterBelow(actual); - } - return true; - } - - /** - * Gets the location of the top block at the specified {@link Location}. - * @param l Any {@link Location}. - * @return The {@link Location} of the top-block. - */ - public Location getTopBlock(Location l) { - Location check = l.clone(); - check.setY(127); // SUPPRESS CHECKSTYLE: MagicNumberCheck - while (check.getY() > 0) { - if (this.playerCanSpawnHereSafely(check)) { - return check; - } - check.setY(check.getY() - 1); - } - return null; - } - - /** - * Gets the location of the top block at the specified {@link Location}. - * @param l Any {@link Location}. - * @return The {@link Location} of the top-block. - */ - public Location getBottomBlock(Location l) { - Location check = l.clone(); - check.setY(0); - while (check.getY() < 127) { // SUPPRESS CHECKSTYLE: MagicNumberCheck - if (this.playerCanSpawnHereSafely(check)) { - return check; - } - check.setY(check.getY() + 1); - } - return null; - } - - /* - * If someone has a better way of this... Please either tell us, or submit a pull request! - */ - private boolean isSolidBlock(Material type) { - switch (type) { - case AIR: - return false; - case SNOW: - return false; - case TRAP_DOOR: - return false; - case TORCH: - return false; - case YELLOW_FLOWER: - return false; - case RED_ROSE: - return false; - case RED_MUSHROOM: - return false; - case BROWN_MUSHROOM: - return false; - case REDSTONE: - return false; - case REDSTONE_WIRE: - return false; - case RAILS: - return false; - case POWERED_RAIL: - return false; - case REDSTONE_TORCH_ON: - return false; - case REDSTONE_TORCH_OFF: - return false; - case DEAD_BUSH: - return false; - case SAPLING: - return false; - case STONE_BUTTON: - return false; - case LEVER: - return false; - case LONG_GRASS: - return false; - case PORTAL: - return false; - case STONE_PLATE: - return false; - case WOOD_PLATE: - return false; - case SEEDS: - return false; - case SUGAR_CANE_BLOCK: - return false; - case WALL_SIGN: - return false; - case SIGN_POST: - return false; - case WOODEN_DOOR: - return false; - case STATIONARY_WATER: - return false; - case WATER: - return false; - default: - return true; - } - } - - /** - * Checks if an entity would be on track at the specified {@link Location}. - * @param l The {@link Location}. - * @return True if an entity would be on tracks at the specified {@link Location}. - */ - public boolean isEntitiyOnTrack(Location l) { - Material currentBlock = l.getBlock().getType(); - return (currentBlock == Material.POWERED_RAIL || currentBlock == Material.DETECTOR_RAIL || currentBlock == Material.RAILS); - } - - // TODO maybe remove this? - private void showDangers(Location l) { - Location actual = new Location(l.getWorld(), l.getX(), l.getY(), l.getZ()); - Location upOne = new Location(l.getWorld(), l.getX(), l.getY(), l.getZ()); - Location downOne = new Location(l.getWorld(), l.getX(), l.getY(), l.getZ()); - upOne.setY(upOne.getY() + 1); - downOne.setY(downOne.getY() - 1); - - System.out.print("Location Up: " + upOne.getBlock().getType()); - System.out.print(" " + upOne); - System.out.print("Location: " + actual.getBlock().getType()); - System.out.print(" " + actual); - System.out.print("Location Down: " + downOne.getBlock().getType()); - System.out.print(" " + downOne); - } - - /** - * Checks recursively below a {@link Location} for 2 blocks of water. - * - * @param l The {@link Location} - * @return Whether there are 2 blocks of water - */ - private boolean hasTwoBlocksofWaterBelow(Location l) { - if (l.getBlockY() < 0) { - return false; - } - Location oneBelow = l.clone(); - oneBelow.subtract(0, 1, 0); - if (oneBelow.getBlock().getType() == Material.WATER || oneBelow.getBlock().getType() == Material.STATIONARY_WATER) { - Location twoBelow = oneBelow.clone(); - twoBelow.subtract(0, 1, 0); - return (oneBelow.getBlock().getType() == Material.WATER || oneBelow.getBlock().getType() == Material.STATIONARY_WATER); - } - if (oneBelow.getBlock().getType() != Material.AIR) { - return false; - } - return hasTwoBlocksofWaterBelow(oneBelow); - } - - /** - * Checks if the specified {@link Minecart} can spawn safely. - * @param cart The {@link Minecart}. - * @return True if the minecart can spawn safely. - */ - public boolean canSpawnCartSafely(Minecart cart) { - if (this.isBlockAboveAir(cart.getLocation())) { - return true; - } - if (this.isEntitiyOnTrack(LocationManipulation.getNextBlock(cart))) { - return true; - } - return false; - } - - /** - * Checks if the specified {@link Vehicle} can spawn safely. - * @param vehicle The {@link Vehicle}. - * @return True if the vehicle can spawn safely. - */ - public boolean canSpawnVehicleSafely(Vehicle vehicle) { - if (this.isBlockAboveAir(vehicle.getLocation())) { - return true; - } - return false; - } - -} diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/MVEconomist.java b/src/main/java/com/onarandombox/MultiverseCore/utils/MVEconomist.java index 702428e17..04353649a 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/MVEconomist.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/MVEconomist.java @@ -1,284 +1,285 @@ -package com.onarandombox.MultiverseCore.utils; - -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.plugin.Plugin; - -import java.util.HashMap; - -/** - * Multiverse's Friendly Economist. This is used to deal with external economies and also item costs for stuff in MV. - */ -public class MVEconomist { - - private final VaultHandler vaultHandler; - - public MVEconomist(Plugin plugin) { - vaultHandler = new VaultHandler(plugin); - } - - private boolean isUsingVault(int currency) { - return !isItemCurrency(currency) && getVaultHandler().hasEconomy(); - } - - /** - * Checks if an economy plugin is in use. - * - * @return true if an economy plugin is detected by Vault. - */ - public boolean isUsingEconomyPlugin() { - return getVaultHandler().hasEconomy(); - } - - /** - * Formats the amount to a human readable currency string. - * - * @param amount the amount of currency. - * @param currency the type of currency. A value greater than -1 indicates the material type used for currency. - * @return the human readable currency string. - */ - public String formatPrice(double amount, int currency) { - if (isUsingVault(currency)) { - return getVaultHandler().getEconomy().format(amount); - } else { - return ItemEconomy.getFormattedPrice(amount, currency); - } - } - - /** - * Returns the name of the economy in use. - * - * @return the name of the economy in use. - */ - public String getEconomyName() { - if (getVaultHandler().hasEconomy()) { - return getVaultHandler().getEconomy().getName(); - } else { - return ItemEconomy.getName(); - } - } - - /** - * Determines if a player has enough of a given currency. - * @param player the player to check for currency. - * @param amount the amount of currency. - * @param currency the type of currency. A value greater than -1 indicates the material type used for currency. - * @return true if the player has enough of the given currency or the amount is 0 or less. - */ - public boolean isPlayerWealthyEnough(Player player, double amount, int currency) { - if (amount <= 0D) { - return true; - } else if (isUsingVault(currency)) { - return getVaultHandler().getEconomy().has(player, amount); - } else { - return ItemEconomy.hasEnough(player, amount, currency); - } - } - - /** - * Formats a message for a player indicating they don't have enough currency. - * - * @param currency the type of currency. A value greater than -1 indicates the material type used for currency. - * @param message The more specific message to append to the generic message of not having enough. - * @return the formatted insufficient funds message. - */ - public String getNSFMessage(int currency, String message) { - return "Sorry, you don't have enough " + (isItemCurrency(currency) ? "items" : "funds") + ". " + message; - } - - /** - * Deposits a given amount of currency either into the player's economy account or inventory if the currency - * represents an item. - * - * @param player the player to give currency to. - * @param amount the amount to give. - * @param currency the type of currency. A value greater than -1 indicates the material type used for currency. - */ - public void deposit(Player player, double amount, int currency) { - if (isUsingVault(currency)) { - getVaultHandler().getEconomy().depositPlayer(player, amount); - } else { - ItemEconomy.deposit(player, amount, currency); - } - } - - /** - * Withdraws a given amount of currency either from the player's economy account or inventory if the currency - * represents an item. - * - * @param player the player to take currency from. - * @param amount the amount to take. - * @param currency the type of currency. A value greater than -1 indicates the material type used for currency. - */ - public void withdraw(Player player, double amount, int currency) { - if (isUsingVault(currency)) { - getVaultHandler().getEconomy().withdrawPlayer(player, amount); - } else { - ItemEconomy.withdraw(player, amount, currency); - } - } - - /** - * Returns the economy balance of the given player. - * - * @param player the player to get the balance for. - * @return the economy balance of the given player. - * @throws IllegalStateException thrown if this is used when no economy plugin is available. - */ - public double getBalance(Player player) throws IllegalStateException { - return getBalance(player, null); - } - - /** - * Returns the economy balance of the given player in the given world. If the economy plugin does not have world - * specific balances then the global balance will be returned. - * - * @param player the player to get the balance for. - * @param world the world to get the balance for. - * @return the economy balance of the given player in the given world. - * @throws IllegalStateException thrown if this is used when no economy plugin is available. - */ - public double getBalance(Player player, World world) throws IllegalStateException { - if (!isUsingEconomyPlugin()) { - throw new IllegalStateException("getBalance is only available when using an economy plugin with Vault"); - } - if (world != null) { - return getVaultHandler().getEconomy().getBalance(player, world.getName()); - } else { - return getVaultHandler().getEconomy().getBalance(player); - } - } - - /** - * Sets the economy balance for the given player. - * - * @param player the player to set the balance for. - * @param amount the amount to set the player's balance to. - * @throws IllegalStateException thrown if this is used when no economy plugin is available. - */ - public void setBalance(Player player, double amount) throws IllegalStateException { - setBalance(player, null, amount); - } - - /** - * Sets the economy balance for the given player in the given world. If the economy plugin does not have world - * specific balances then the global balance will be set. - * - * @param player the player to set the balance for. - * @param world the world to get the balance for. - * @param amount the amount to set the player's balance to. - * @throws IllegalStateException thrown if this is used when no economy plugin is available. - */ - public void setBalance(Player player, World world, double amount) throws IllegalStateException { - if (!isUsingEconomyPlugin()) { - throw new IllegalStateException("getBalance is only available when using an economy plugin with Vault"); - } - if (world != null) { - getVaultHandler().getEconomy().withdrawPlayer(player, world.getName(), getBalance(player, world)); - getVaultHandler().getEconomy().depositPlayer(player, world.getName(), amount); - } else { - getVaultHandler().getEconomy().withdrawPlayer(player, getBalance(player)); - getVaultHandler().getEconomy().depositPlayer(player, amount); - } - } - - /** - * This method is public for backwards compatibility. - * - * @return the old VaultHandler. - * @deprecated just use the other methods in this class for economy stuff. - */ - // TODO make private - @Deprecated - public VaultHandler getVaultHandler() { - return vaultHandler; - } - - /** - * Determines if the currency type given represents an item currency. - * - * @param currency the type of currency. A value greater than -1 indicates the material type used for currency. - * @return true if currency is greater than -1. - */ - public static boolean isItemCurrency(int currency) { - return currency >= 0; - } - - private static class ItemEconomy { - - private static final String ECONOMY_NAME = "Simple Item Economy"; - - private static String getFormattedPrice(double amount, int currency) { - if (isItemCurrency(currency)) { - Material m = Material.getMaterial(currency); - return m != null ? amount + " " + m.toString() : "NO ITEM FOUND"; - } else { - return ""; - } - } - - private static String getName() { - return ECONOMY_NAME; - } - - private static boolean hasEnough(Player player, double amount, int currency) { - if (isItemCurrency(currency)) { - return player.getInventory().contains(currency, (int) amount); - } else { - return true; - } - } - - private static void deposit(Player player, double amount, int currency) { - if (isItemCurrency(currency)) { - giveItem(player, amount, currency); - } - } - - private static void withdraw(Player player, double amount, int currency) { - if (isItemCurrency(currency)) { - takeItem(player, amount, currency); - } - } - - private static void giveItem(Player player, double amount, int type) { - ItemStack item = new ItemStack(type, (int) amount); - player.getInventory().addItem(item); - showReceipt(player, (amount * -1), type); - } - - private static void takeItem(Player player, double amount, int type) { - int removed = 0; - HashMap items = (HashMap) player.getInventory().all(type); - for (int i : items.keySet()) { - if (removed >= amount) { - break; - } - int diff = (int) (amount - removed); - int amt = player.getInventory().getItem(i).getAmount(); - if (amt - diff > 0) { - player.getInventory().getItem(i).setAmount(amt - diff); - break; - } else { - removed += amt; - player.getInventory().clear(i); - } - } - showReceipt(player, amount, type); - } - - private static void showReceipt(Player player, double price, int item) { - if (price > 0D) { - player.sendMessage(String.format("%s%s%s %s", - ChatColor.WHITE, "You have been charged", ChatColor.GREEN, getFormattedPrice(price, item))); - } else if (price < 0D) { - player.sendMessage(String.format("%s%s%s %s", - ChatColor.DARK_GREEN, getFormattedPrice((price * -1), item), - ChatColor.WHITE, "has been added to your inventory.")); - } - } - } -} +package com.onarandombox.MultiverseCore.utils; + +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.Plugin; +import org.jetbrains.annotations.Nullable; + +import java.util.HashMap; + +/** + * Multiverse's Friendly Economist. This is used to deal with external economies and also item costs for stuff in MV. + */ +public class MVEconomist { + + private final VaultHandler vaultHandler; + + public MVEconomist(Plugin plugin) { + vaultHandler = new VaultHandler(plugin); + } + + private boolean isUsingVault(Material currency) { + return !isItemCurrency(currency) && getVaultHandler().hasEconomy(); + } + + /** + * Checks if an economy plugin is in use. + * + * @return true if an economy plugin is detected by Vault. + */ + public boolean isUsingEconomyPlugin() { + return getVaultHandler().hasEconomy(); + } + + /** + * Formats the amount to a human readable currency string. + * + * @param amount the amount of currency. + * @param currency the type of currency. Null indicates a non-item currency is used. + * @return the human readable currency string. + */ + public String formatPrice(double amount, @Nullable Material currency) { + if (isUsingVault(currency)) { + return getVaultHandler().getEconomy().format(amount); + } else { + return ItemEconomy.getFormattedPrice(amount, currency); + } + } + + /** + * Returns the name of the economy in use. + * + * @return the name of the economy in use. + */ + public String getEconomyName() { + if (getVaultHandler().hasEconomy()) { + return getVaultHandler().getEconomy().getName(); + } else { + return ItemEconomy.getName(); + } + } + + /** + * Determines if a player has enough of a given currency. + * + * @param player the player to check for currency. + * @param amount the amount of currency. + * @param currency the type of currency. Null indicates non-item currency is used. + * @return true if the player has enough of the given currency or the amount is 0 or less. + */ + public boolean isPlayerWealthyEnough(Player player, double amount, Material currency) { + if (amount <= 0D) { + return true; + } else if (isUsingVault(currency)) { + return getVaultHandler().getEconomy().has(player, amount); + } else { + return ItemEconomy.hasEnough(player, amount, currency); + } + } + + /** + * Formats a message for a player indicating they don't have enough currency. + * + * @param currency the type of currency. Null indicates a non-item currency is used. + * @param message The more specific message to append to the generic message of not having enough. + * @return the formatted insufficient funds message. + */ + public String getNSFMessage(Material currency, String message) { + return "Sorry, you don't have enough " + (isItemCurrency(currency) ? "items" : "funds") + ". " + message; + } + + /** + * Deposits a given amount of currency either into the player's economy account or inventory if the currency + * is not null. + * + * @param player the player to give currency to. + * @param amount the amount to give. + * @param currency the type of currency. + */ + public void deposit(Player player, double amount, @Nullable Material currency) { + if (isUsingVault(currency)) { + getVaultHandler().getEconomy().depositPlayer(player, amount); + } else { + ItemEconomy.deposit(player, amount, currency); + } + } + + /** + * Withdraws a given amount of currency either from the player's economy account or inventory if the currency + * is not null. + * + * @param player the player to take currency from. + * @param amount the amount to take. + * @param currency the type of currency. + */ + public void withdraw(Player player, double amount, @Nullable Material currency) { + if (isUsingVault(currency)) { + getVaultHandler().getEconomy().withdrawPlayer(player, amount); + } else { + ItemEconomy.withdraw(player, amount, currency); + } + } + + /** + * Returns the economy balance of the given player. + * + * @param player the player to get the balance for. + * @return the economy balance of the given player. + * @throws IllegalStateException thrown if this is used when no economy plugin is available. + */ + public double getBalance(Player player) throws IllegalStateException { + return getBalance(player, null); + } + + /** + * Returns the economy balance of the given player in the given world. If the economy plugin does not have world + * specific balances then the global balance will be returned. + * + * @param player the player to get the balance for. + * @param world the world to get the balance for. + * @return the economy balance of the given player in the given world. + * @throws IllegalStateException thrown if this is used when no economy plugin is available. + */ + public double getBalance(Player player, World world) throws IllegalStateException { + if (!isUsingEconomyPlugin()) { + throw new IllegalStateException("getBalance is only available when using an economy plugin with Vault"); + } + if (world != null) { + return getVaultHandler().getEconomy().getBalance(player, world.getName()); + } else { + return getVaultHandler().getEconomy().getBalance(player); + } + } + + /** + * Sets the economy balance for the given player. + * + * @param player the player to set the balance for. + * @param amount the amount to set the player's balance to. + * @throws IllegalStateException thrown if this is used when no economy plugin is available. + */ + public void setBalance(Player player, double amount) throws IllegalStateException { + setBalance(player, null, amount); + } + + /** + * Sets the economy balance for the given player in the given world. If the economy plugin does not have world + * specific balances then the global balance will be set. + * + * @param player the player to set the balance for. + * @param world the world to get the balance for. + * @param amount the amount to set the player's balance to. + * @throws IllegalStateException thrown if this is used when no economy plugin is available. + */ + public void setBalance(Player player, World world, double amount) throws IllegalStateException { + if (!isUsingEconomyPlugin()) { + throw new IllegalStateException("getBalance is only available when using an economy plugin with Vault"); + } + if (world != null) { + getVaultHandler().getEconomy().withdrawPlayer(player, world.getName(), getBalance(player, world)); + getVaultHandler().getEconomy().depositPlayer(player, world.getName(), amount); + } else { + getVaultHandler().getEconomy().withdrawPlayer(player, getBalance(player)); + getVaultHandler().getEconomy().depositPlayer(player, amount); + } + } + + /** + * This method is public for backwards compatibility. + * + * @return the old VaultHandler. + * @deprecated just use the other methods in this class for economy stuff. + */ + // TODO make private + @Deprecated + public VaultHandler getVaultHandler() { + return vaultHandler; + } + + /** + * Determines if the currency type string given represents an item currency. + * + * @param currency the type of currency. + * @return true if currency string matches a valid material. + */ + public static boolean isItemCurrency(Material currency) { + return currency != null; + } + + private static class ItemEconomy { + + private static final String ECONOMY_NAME = "Simple Item Economy"; + + private static String getFormattedPrice(double amount, Material currency) { + if (isItemCurrency(currency)) { + return amount + " " + currency.toString(); + } else { + return ""; + } + } + + private static String getName() { + return ECONOMY_NAME; + } + + private static boolean hasEnough(Player player, double amount, Material currency) { + if (currency != null) { + return player.getInventory().contains(currency, (int) amount); + } else { + return true; + } + } + + private static void deposit(Player player, double amount, Material currency) { + if (isItemCurrency(currency)) { + giveItem(player, amount, currency); + } + } + + private static void withdraw(Player player, double amount, Material currency) { + if (isItemCurrency(currency)) { + takeItem(player, amount, currency); + } + } + + private static void giveItem(Player player, double amount, Material type) { + ItemStack item = new ItemStack(type, (int) amount); + player.getInventory().addItem(item); + showReceipt(player, (amount * -1), type); + } + + private static void takeItem(Player player, double amount, Material type) { + int removed = 0; + HashMap items = (HashMap) player.getInventory().all(type); + for (int i : items.keySet()) { + if (removed >= amount) { + break; + } + int diff = (int) (amount - removed); + int amt = player.getInventory().getItem(i).getAmount(); + if (amt - diff > 0) { + player.getInventory().getItem(i).setAmount(amt - diff); + break; + } else { + removed += amt; + player.getInventory().clear(i); + } + } + showReceipt(player, amount, type); + } + + private static void showReceipt(Player player, double price, Material item) { + if (price > 0D) { + player.sendMessage(String.format("%s%s%s %s", + ChatColor.WHITE, "You have been charged", ChatColor.GREEN, getFormattedPrice(price, item))); + } else if (price < 0D) { + player.sendMessage(String.format("%s%s%s %s", + ChatColor.DARK_GREEN, getFormattedPrice((price * -1), item), + ChatColor.WHITE, "has been added to your inventory.")); + } + } + } +} diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/PermissionTools.java b/src/main/java/com/onarandombox/MultiverseCore/utils/PermissionTools.java index 119d02cfd..a6e988205 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/PermissionTools.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/PermissionTools.java @@ -9,6 +9,7 @@ import com.onarandombox.MultiverseCore.MultiverseCore; import com.onarandombox.MultiverseCore.api.MultiverseWorld; +import org.bukkit.Material; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; @@ -145,7 +146,7 @@ public boolean playerHasMoneyToEnter(MultiverseWorld fromWorld, MultiverseWorld } final MVEconomist economist = plugin.getEconomist(); - final int currency = toWorld.getCurrency(); + final Material currency = toWorld.getCurrency(); final String formattedAmount = economist.formatPrice(price, currency); if (economist.isPlayerWealthyEnough(teleporterPlayer, price, currency)) { @@ -171,7 +172,7 @@ public boolean playerHasMoneyToEnter(MultiverseWorld fromWorld, MultiverseWorld return true; } - private void sendTeleportPaymentMessage (MVEconomist economist, Player teleporterPlayer, Player teleportee, String toWorld, double price, int currency) { + private void sendTeleportPaymentMessage (MVEconomist economist, Player teleporterPlayer, Player teleportee, String toWorld, double price, Material currency) { price = Math.abs(price); if (teleporterPlayer.equals(teleportee)) { teleporterPlayer.sendMessage("You were " + (price > 0D ? "charged " : "given ") + economist.formatPrice(price, currency) + " for teleporting to " + toWorld); diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/SafeTTeleporter.java b/src/main/java/com/onarandombox/MultiverseCore/utils/SafeTTeleporter.java deleted file mode 100644 index 0984c437e..000000000 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/SafeTTeleporter.java +++ /dev/null @@ -1,358 +0,0 @@ -/****************************************************************************** - * Multiverse 2 Copyright (c) the Multiverse Team 2011. * - * 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.utils; - -import com.onarandombox.MultiverseCore.MultiverseCore; -import com.onarandombox.MultiverseCore.api.BlockSafety; -import com.onarandombox.MultiverseCore.api.MVDestination; -import com.onarandombox.MultiverseCore.destination.InvalidDestination; -import com.onarandombox.MultiverseCore.enums.TeleportResult; - -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Minecart; -import org.bukkit.entity.Player; -import org.bukkit.entity.Vehicle; -import org.bukkit.util.Vector; - -import java.util.logging.Level; - -/** - * The {@link SafeTTeleporter}. - * - * @deprecated Use instead: {@link com.onarandombox.MultiverseCore.api.SafeTTeleporter} and {@link SimpleSafeTTeleporter}. - */ -@Deprecated -public class SafeTTeleporter { - - private MultiverseCore plugin; - private BlockSafety bs; - - public SafeTTeleporter(MultiverseCore plugin) { - this.plugin = plugin; - this.bs = plugin.getBlockSafety(); - } - - private static final int DEFAULT_TOLERANCE = 6; - private static final int DEFAULT_RADIUS = 9; - - /** - * Gets the next safe location around the given location. - * @param l A {@link Location}. - * @return A safe {@link Location}. - */ - public Location getSafeLocation(Location l) { - return this.getSafeLocation(l, DEFAULT_TOLERANCE, DEFAULT_RADIUS); - } - - /** - * Gets the next safe location around the given location. - * @param l A {@link Location}. - * @param tolerance The tolerance. - * @param radius The radius. - * @return A safe {@link Location}. - */ - public Location getSafeLocation(Location l, int tolerance, int radius) { - // Check around the player first in a configurable radius: - Location safe = checkAboveAndBelowLocation(l, tolerance, radius); - if (safe != null) { - safe.setX(safe.getBlockX() + .5); // SUPPRESS CHECKSTYLE: MagicNumberCheck - safe.setZ(safe.getBlockZ() + .5); // SUPPRESS CHECKSTYLE: MagicNumberCheck - this.plugin.log(Level.FINE, "Hey! I found one: " + plugin.getLocationManipulation().strCoordsRaw(safe)); - } else { - this.plugin.log(Level.FINE, "Uh oh! No safe place found!"); - } - return safe; - } - - private Location checkAboveAndBelowLocation(Location l, int tolerance, int radius) { - // Tolerance must be an even number: - if (tolerance % 2 != 0) { - tolerance += 1; - } - // We want half of it, so we can go up and down - tolerance /= 2; - this.plugin.log(Level.FINER, "Given Location of: " + plugin.getLocationManipulation().strCoordsRaw(l)); - this.plugin.log(Level.FINER, "Checking +-" + tolerance + " with a radius of " + radius); - - // For now this will just do a straight up block. - Location locToCheck = l.clone(); - // Check the main level - Location safe = this.checkAroundLocation(locToCheck, radius); - if (safe != null) { - return safe; - } - // We've already checked zero right above this. - int currentLevel = 1; - while (currentLevel <= tolerance) { - // Check above - locToCheck = l.clone(); - locToCheck.add(0, currentLevel, 0); - safe = this.checkAroundLocation(locToCheck, radius); - if (safe != null) { - return safe; - } - - // Check below - locToCheck = l.clone(); - locToCheck.subtract(0, currentLevel, 0); - safe = this.checkAroundLocation(locToCheck, radius); - if (safe != null) { - return safe; - } - currentLevel++; - } - - return null; - } - - /* - * For my crappy algorithm, radius MUST be odd. - */ - private Location checkAroundLocation(Location l, int diameter) { - if (diameter % 2 == 0) { - diameter += 1; - } - Location checkLoc = l.clone(); - - // Start at 3, the min diameter around a block - int loopcounter = 3; - while (loopcounter <= diameter) { - boolean foundSafeArea = checkAroundSpecificDiameter(checkLoc, loopcounter); - // If a safe area was found: - if (foundSafeArea) { - // Return the checkLoc, it is the safe location. - return checkLoc; - } - // Otherwise, let's reset our location - checkLoc = l.clone(); - // And increment the radius - loopcounter += 2; - } - return null; - } - - private boolean checkAroundSpecificDiameter(Location checkLoc, int circle) { - // Adjust the circle to get how many blocks to step out. - // A radius of 3 makes the block step 1 - // A radius of 5 makes the block step 2 - // A radius of 7 makes the block step 3 - // ... - int adjustedCircle = ((circle - 1) / 2); - checkLoc.add(adjustedCircle, 0, 0); - if (this.bs.playerCanSpawnHereSafely(checkLoc)) { - return true; - } - // Now we go to the right that adjustedCircle many - for (int i = 0; i < adjustedCircle; i++) { - checkLoc.add(0, 0, 1); - if (this.bs.playerCanSpawnHereSafely(checkLoc)) { - return true; - } - } - - // Then down adjustedCircle *2 - for (int i = 0; i < adjustedCircle * 2; i++) { - checkLoc.add(-1, 0, 0); - if (this.bs.playerCanSpawnHereSafely(checkLoc)) { - return true; - } - } - - // Then left adjustedCircle *2 - for (int i = 0; i < adjustedCircle * 2; i++) { - checkLoc.add(0, 0, -1); - if (this.bs.playerCanSpawnHereSafely(checkLoc)) { - return true; - } - } - - // Then up Then left adjustedCircle *2 - for (int i = 0; i < adjustedCircle * 2; i++) { - checkLoc.add(1, 0, 0); - if (this.bs.playerCanSpawnHereSafely(checkLoc)) { - return true; - } - } - - // Then finish up by doing adjustedCircle - 1 - for (int i = 0; i < adjustedCircle - 1; i++) { - checkLoc.add(0, 0, 1); - if (this.bs.playerCanSpawnHereSafely(checkLoc)) { - return true; - } - } - return false; - } - - /** - * Safely teleport the entity to the MVDestination. This will perform checks to see if the place is safe, and if - * it's not, will adjust the final destination accordingly. - * - * @param teleporter Person who performed the teleport command. - * @param teleportee Entity to teleport - * @param d Destination to teleport them to - * @return true for success, false for failure - */ - public TeleportResult safelyTeleport(CommandSender teleporter, Entity teleportee, MVDestination d) { - if (d instanceof InvalidDestination) { - this.plugin.log(Level.FINER, "Entity tried to teleport to an invalid destination"); - return TeleportResult.FAIL_INVALID; - } - Player teleporteePlayer = null; - if (teleportee instanceof Player) { - teleporteePlayer = ((Player) teleportee); - } else if (teleportee.getPassenger() instanceof Player) { - teleporteePlayer = ((Player) teleportee.getPassenger()); - } - - if (teleporteePlayer == null) { - return TeleportResult.FAIL_INVALID; - } - MultiverseCore.addPlayerToTeleportQueue(teleporter.getName(), teleporteePlayer.getName()); - - Location safeLoc = d.getLocation(teleportee); - if (d.useSafeTeleporter()) { - safeLoc = this.getSafeLocation(teleportee, d); - } - - if (safeLoc != null) { - if (teleportee.teleport(safeLoc)) { - if (!d.getVelocity().equals(new Vector(0, 0, 0))) { - teleportee.setVelocity(d.getVelocity()); - } - return TeleportResult.SUCCESS; - } - return TeleportResult.FAIL_OTHER; - } - return TeleportResult.FAIL_UNSAFE; - } - - /** - * Safely teleport the entity to the Location. This may perform checks to - * see if the place is safe, and if - * it's not, will adjust the final destination accordingly. - * - * @param teleporter Person who issued the teleport command. - * @param teleportee Entity to teleport. - * @param location Location to teleport them to. - * @param safely Should the destination be checked for safety before teleport? - * @return true for success, false for failure. - */ - public TeleportResult safelyTeleport(CommandSender teleporter, Entity teleportee, Location location, boolean safely) { - if (safely) { - location = this.getSafeLocation(location); - } - - if (location != null) { - if (teleportee.teleport(location)) { - return TeleportResult.SUCCESS; - } - return TeleportResult.FAIL_OTHER; - } - return TeleportResult.FAIL_UNSAFE; - } - - /** - * Returns a safe location for the entity to spawn at. - * - * @param e The entity to spawn - * @param d The MVDestination to take the entity to. - * @return A new location to spawn the entity at. - */ - public Location getSafeLocation(Entity e, MVDestination d) { - Location l = d.getLocation(e); - if (this.bs.playerCanSpawnHereSafely(l)) { - plugin.log(Level.FINE, "The first location you gave me was safe."); - return l; - } - if (e instanceof Minecart) { - Minecart m = (Minecart) e; - if (!this.bs.canSpawnCartSafely(m)) { - return null; - } - } else if (e instanceof Vehicle) { - Vehicle v = (Vehicle) e; - if (!this.bs.canSpawnVehicleSafely(v)) { - return null; - } - } - Location safeLocation = this.getSafeLocation(l); - if (safeLocation != null) { - // Add offset to account for a vehicle on dry land! - if (e instanceof Minecart && !this.bs.isEntitiyOnTrack(safeLocation)) { - safeLocation.setY(safeLocation.getBlockY() + .5); - this.plugin.log(Level.FINER, "Player was inside a minecart. Offsetting Y location."); - } - this.plugin.log(Level.FINE, "Had to look for a bit, but I found a safe place for ya!"); - return safeLocation; - } - if (e instanceof Player) { - Player p = (Player) e; - this.plugin.getMessaging().sendMessage(p, "No safe locations found!", false); - this.plugin.log(Level.FINER, "No safe location found for " + p.getName()); - } else if (e.getPassenger() instanceof Player) { - Player p = (Player) e.getPassenger(); - this.plugin.getMessaging().sendMessage(p, "No safe locations found!", false); - this.plugin.log(Level.FINER, "No safe location found for " + p.getName()); - } - this.plugin.log(Level.FINE, "Sorry champ, you're basically trying to teleport into a minefield. I should just kill you now."); - return null; - } - - /** - * Finds a portal-block next to the specified {@link Location}. - * @param l The {@link Location} - * @return The next portal-block's {@link Location}. - */ - public static Location findPortalBlockNextTo(Location l) { - Block b = l.getWorld().getBlockAt(l); - Location foundLocation = null; - if (b.getType() == Material.PORTAL) { - return l; - } - if (b.getRelative(BlockFace.NORTH).getType() == Material.PORTAL) { - foundLocation = getCloserBlock(l, b.getRelative(BlockFace.NORTH).getLocation(), foundLocation); - } - if (b.getRelative(BlockFace.SOUTH).getType() == Material.PORTAL) { - foundLocation = getCloserBlock(l, b.getRelative(BlockFace.SOUTH).getLocation(), foundLocation); - } - if (b.getRelative(BlockFace.EAST).getType() == Material.PORTAL) { - foundLocation = getCloserBlock(l, b.getRelative(BlockFace.EAST).getLocation(), foundLocation); - } - if (b.getRelative(BlockFace.WEST).getType() == Material.PORTAL) { - foundLocation = getCloserBlock(l, b.getRelative(BlockFace.WEST).getLocation(), foundLocation); - } - return foundLocation; - } - - private static Location getCloserBlock(Location source, Location blockA, Location blockB) { - // If B wasn't given, return a. - if (blockB == null) { - return blockA; - } - // Center our calculations - blockA.add(.5, 0, .5); - blockB.add(.5, 0, .5); - - // Retrieve the distance to the normalized blocks - double testA = source.distance(blockA); - double testB = source.distance(blockB); - - // Compare and return - if (testA <= testB) { - return blockA; - } - return blockB; - } - -} diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/SimpleBlockSafety.java b/src/main/java/com/onarandombox/MultiverseCore/utils/SimpleBlockSafety.java index a75673801..3072d8a8d 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/SimpleBlockSafety.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/SimpleBlockSafety.java @@ -14,9 +14,10 @@ import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.BlockFace; +import org.bukkit.block.data.BlockData; +import org.bukkit.block.data.type.Bed; import org.bukkit.entity.Minecart; import org.bukkit.entity.Vehicle; -import org.bukkit.material.Bed; import java.util.EnumSet; import java.util.Iterator; @@ -89,7 +90,7 @@ public boolean playerCanSpawnHereSafely(Location l) { return false; } - if (downOne.getBlock().getType() == Material.LAVA || downOne.getBlock().getType() == Material.STATIONARY_LAVA) { + if (downOne.getBlock().getType() == Material.LAVA) { Logging.finer("Error Here (downOne)? (%s)[%s]", downOne.getBlock().getType(), isSolidBlock(downOne.getBlock().getType())); return false; } @@ -151,12 +152,13 @@ private Location getSafeSpawnAroundABlock(Location l) { * @return The location of the other bed piece, or null if it was a jacked up bed. */ private Location findOtherBedPiece(Location checkLoc) { - if (checkLoc.getBlock().getType() != Material.BED_BLOCK) { + BlockData data = checkLoc.getBlock().getBlockData(); + if (!(data instanceof Bed)) { return null; } - // Construct a bed object at this location - final Bed b = new Bed(Material.BED_BLOCK, checkLoc.getBlock().getData()); - if (b.isHeadOfBed()) { + Bed b = (Bed) data; + + if (b.getPart() == Bed.Part.HEAD) { return checkLoc.getBlock().getRelative(b.getFacing().getOppositeFace()).getLocation(); } // We shouldn't ever be looking at the foot, but here's the code for it. @@ -199,69 +201,8 @@ public Location getBottomBlock(Location l) { /* * If someone has a better way of this... Please either tell us, or submit a pull request! */ - private static boolean isSolidBlock(Material type) { - switch (type) { - case AIR: - return false; - case SNOW: - return false; - case TRAP_DOOR: - return false; - case TORCH: - return false; - case YELLOW_FLOWER: - return false; - case RED_ROSE: - return false; - case RED_MUSHROOM: - return false; - case BROWN_MUSHROOM: - return false; - case REDSTONE: - return false; - case REDSTONE_WIRE: - return false; - case RAILS: - return false; - case POWERED_RAIL: - return false; - case REDSTONE_TORCH_ON: - return false; - case REDSTONE_TORCH_OFF: - return false; - case DEAD_BUSH: - return false; - case SAPLING: - return false; - case STONE_BUTTON: - return false; - case LEVER: - return false; - case LONG_GRASS: - return false; - case PORTAL: - return false; - case STONE_PLATE: - return false; - case WOOD_PLATE: - return false; - case SEEDS: - return false; - case SUGAR_CANE_BLOCK: - return false; - case WALL_SIGN: - return false; - case SIGN_POST: - return false; - case WOODEN_DOOR: - return false; - case STATIONARY_WATER: - return false; - case WATER: - return false; - default: - return true; - } + public static boolean isSolidBlock(Material type) { + return type.isSolid(); } /** @@ -270,7 +211,10 @@ private static boolean isSolidBlock(Material type) { @Override public boolean isEntitiyOnTrack(Location l) { Material currentBlock = l.getBlock().getType(); - return (currentBlock == Material.POWERED_RAIL || currentBlock == Material.DETECTOR_RAIL || currentBlock == Material.RAILS); + return (currentBlock == Material.POWERED_RAIL + || currentBlock == Material.DETECTOR_RAIL + || currentBlock == Material.RAIL + || currentBlock == Material.ACTIVATOR_RAIL); } /** @@ -285,10 +229,10 @@ private boolean hasTwoBlocksofWaterBelow(Location l) { } Location oneBelow = l.clone(); oneBelow.subtract(0, 1, 0); - if (oneBelow.getBlock().getType() == Material.WATER || oneBelow.getBlock().getType() == Material.STATIONARY_WATER) { + if (oneBelow.getBlock().getType() == Material.WATER) { Location twoBelow = oneBelow.clone(); twoBelow.subtract(0, 1, 0); - return (oneBelow.getBlock().getType() == Material.WATER || oneBelow.getBlock().getType() == Material.STATIONARY_WATER); + return (oneBelow.getBlock().getType() == Material.WATER); } if (oneBelow.getBlock().getType() != Material.AIR) { return false; diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/SimpleSafeTTeleporter.java b/src/main/java/com/onarandombox/MultiverseCore/utils/SimpleSafeTTeleporter.java index 0608dc150..baae83e59 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/SimpleSafeTTeleporter.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/SimpleSafeTTeleporter.java @@ -292,19 +292,19 @@ public Location getSafeLocation(Entity e, MVDestination d) { public Location findPortalBlockNextTo(Location l) { Block b = l.getWorld().getBlockAt(l); Location foundLocation = null; - if (b.getType() == Material.PORTAL) { + if (b.getType() == Material.NETHER_PORTAL) { return l; } - if (b.getRelative(BlockFace.NORTH).getType() == Material.PORTAL) { + if (b.getRelative(BlockFace.NORTH).getType() == Material.NETHER_PORTAL) { foundLocation = getCloserBlock(l, b.getRelative(BlockFace.NORTH).getLocation(), foundLocation); } - if (b.getRelative(BlockFace.SOUTH).getType() == Material.PORTAL) { + if (b.getRelative(BlockFace.SOUTH).getType() == Material.NETHER_PORTAL) { foundLocation = getCloserBlock(l, b.getRelative(BlockFace.SOUTH).getLocation(), foundLocation); } - if (b.getRelative(BlockFace.EAST).getType() == Material.PORTAL) { + if (b.getRelative(BlockFace.EAST).getType() == Material.NETHER_PORTAL) { foundLocation = getCloserBlock(l, b.getRelative(BlockFace.EAST).getLocation(), foundLocation); } - if (b.getRelative(BlockFace.WEST).getType() == Material.PORTAL) { + if (b.getRelative(BlockFace.WEST).getType() == Material.NETHER_PORTAL) { foundLocation = getCloserBlock(l, b.getRelative(BlockFace.WEST).getLocation(), foundLocation); } return foundLocation; diff --git a/src/test/java/com/onarandombox/MultiverseCore/TestEntryFeeConversion.java b/src/test/java/com/onarandombox/MultiverseCore/TestEntryFeeConversion.java new file mode 100644 index 000000000..b11bbdfa7 --- /dev/null +++ b/src/test/java/com/onarandombox/MultiverseCore/TestEntryFeeConversion.java @@ -0,0 +1,63 @@ +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.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.*; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ MultiverseCore.class, PluginDescriptionFile.class, JavaPluginLoader.class}) +public class TestEntryFeeConversion { + + private TestInstanceCreator creator; + private MultiverseCore core; + Map config; + Map entryFee; + + @Before + public void setUp() { + creator = new TestInstanceCreator(); + assertTrue(creator.setUp()); + core = creator.getCore(); + + config = new HashMap<>(); + entryFee = new HashMap<>(); + config.put("entryfee", entryFee); + entryFee.put("==", "MVEntryFee"); + } + + @After + public void tearDown() { + creator.tearDown(); + } + + @Test + public void testConvertIntegerCurrencyToMaterialCurrency() { + entryFee.put("currency", -1); + WorldProperties props = new WorldProperties(config); + assertNull(props.entryfee.getCurrency()); + + entryFee.put("currency", 1); + props = new WorldProperties(config); + assertEquals(Material.STONE, props.entryfee.getCurrency()); + + entryFee.put("currency", "1"); + props = new WorldProperties(config); + assertEquals(Material.STONE, props.entryfee.getCurrency()); + + entryFee.put("currency", "stone"); + props = new WorldProperties(config); + assertEquals(Material.STONE, props.entryfee.getCurrency()); + } +} diff --git a/src/test/java/com/onarandombox/MultiverseCore/TestWorldProperties.java b/src/test/java/com/onarandombox/MultiverseCore/TestWorldProperties.java index 751ad97cc..aa114fb6a 100644 --- a/src/test/java/com/onarandombox/MultiverseCore/TestWorldProperties.java +++ b/src/test/java/com/onarandombox/MultiverseCore/TestWorldProperties.java @@ -18,6 +18,7 @@ import org.bukkit.Difficulty; import org.bukkit.GameMode; import org.bukkit.Location; +import org.bukkit.Material; import org.bukkit.World; import org.bukkit.WorldType; import org.bukkit.command.Command; @@ -151,7 +152,7 @@ public void test() throws Exception { assertEquals(Difficulty.NORMAL, mvWorld.getDifficulty()); assertTrue(mvWorld.canAnimalsSpawn()); assertTrue(mvWorld.canMonstersSpawn()); - assertEquals(-1, mvWorld.getCurrency()); + assertNull(mvWorld.getCurrency()); assertEquals(0, mvWorld.getPrice(), 0); assertTrue(mvWorld.getHunger()); assertTrue(mvWorld.getAutoHeal()); @@ -233,8 +234,8 @@ public void test() throws Exception { assertEquals(false, mvWorld.canAnimalsSpawn()); mvWorld.setAllowMonsterSpawn(false); assertEquals(false, mvWorld.canMonstersSpawn()); - mvWorld.setCurrency(1); - assertEquals(1, mvWorld.getCurrency()); + mvWorld.setCurrency(Material.STONE); + assertEquals(Material.STONE, mvWorld.getCurrency()); mvWorld.setPrice(1D); assertEquals(1D, mvWorld.getPrice(), 0); mvWorld.setHunger(false); @@ -332,7 +333,7 @@ public void test() throws Exception { assertEquals(Difficulty.PEACEFUL, mvWorld.getDifficulty()); assertEquals(false, mvWorld.canAnimalsSpawn()); assertEquals(false, mvWorld.canMonstersSpawn()); - assertEquals(1, mvWorld.getCurrency()); + assertEquals(Material.STONE, mvWorld.getCurrency()); assertEquals(1D, mvWorld.getPrice(), 0); assertEquals(false, mvWorld.getHunger()); assertEquals(false, mvWorld.getAutoHeal()); diff --git a/src/test/java/com/onarandombox/MultiverseCore/utils/MockWorldFactory.java b/src/test/java/com/onarandombox/MultiverseCore/utils/MockWorldFactory.java index c5b680690..ffe0e6687 100644 --- a/src/test/java/com/onarandombox/MultiverseCore/utils/MockWorldFactory.java +++ b/src/test/java/com/onarandombox/MultiverseCore/utils/MockWorldFactory.java @@ -126,7 +126,6 @@ public Block answer(InvocationOnMock invocation) throws Throwable { } when(mockBlock.getType()).thenReturn(blockType); - when(mockBlock.getTypeId()).thenReturn(blockType.getId()); when(mockBlock.getWorld()).thenReturn(loc.getWorld()); when(mockBlock.getX()).thenReturn(loc.getBlockX()); when(mockBlock.getY()).thenReturn(loc.getBlockY()); @@ -170,7 +169,6 @@ public Block answer(InvocationOnMock invocation) throws Throwable { Material blockType = Material.AIR; when(mockBlock.getType()).thenReturn(blockType); - when(mockBlock.getTypeId()).thenReturn(blockType.getId()); when(mockBlock.getWorld()).thenReturn(loc.getWorld()); when(mockBlock.getX()).thenReturn(loc.getBlockX()); when(mockBlock.getY()).thenReturn(loc.getBlockY()); From 4bdeacfd0516a7eed2c2c591861ab5b9c945876e Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Thu, 24 Jan 2019 01:00:42 -0500 Subject: [PATCH 034/134] Updated testing dependencies and maven plugins. --- pom.xml | 26 +++++++++---------- .../MultiverseCore/TestDebugMode.java | 2 ++ .../MultiverseCore/TestEntitySpawnRules.java | 7 ++++- .../TestEntryFeeConversion.java | 2 ++ .../MultiverseCore/TestModifyCommand.java | 2 ++ .../MultiverseCore/TestWorldProperties.java | 2 ++ .../MultiverseCore/TestWorldPurger.java | 2 ++ .../MultiverseCore/TestWorldStuff.java | 7 +++-- .../utils/MockWorldFactory.java | 1 + .../utils/TestInstanceCreator.java | 24 +++++++++-------- .../utils/WorldCreatorMatcher.java | 16 ++++++------ 11 files changed, 56 insertions(+), 35 deletions(-) diff --git a/pom.xml b/pom.xml index 68d509879..5b8bcbd6e 100644 --- a/pom.xml +++ b/pom.xml @@ -79,7 +79,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.5.1 + 3.7.0 1.8 1.8 @@ -122,7 +122,7 @@ org.apache.maven.plugins maven-surefire-plugin - 2.19.1 + 3.0.0-M3 methods 10 @@ -135,7 +135,7 @@ org.apache.maven.surefire surefire-junit47 - 2.19.1 + 3.0.0-M3 @@ -379,6 +379,11 @@ jar compile + + de.themoep.idconverter + mappings + 1.2-SNAPSHOT + junit @@ -388,35 +393,30 @@ org.powermock powermock-module-junit4 - 1.6.5 + 2.0.0 jar test org.powermock powermock-api-easymock - 1.6.5 + 2.0.0 jar test org.powermock - powermock-api-mockito - 1.6.6 + powermock-api-mockito2 + 2.0.0 jar test org.easymock easymock - 3.4 + 4.0.2 test - - de.themoep.idconverter - mappings - 1.2-SNAPSHOT - diff --git a/src/test/java/com/onarandombox/MultiverseCore/TestDebugMode.java b/src/test/java/com/onarandombox/MultiverseCore/TestDebugMode.java index f79244479..da2cd237e 100644 --- a/src/test/java/com/onarandombox/MultiverseCore/TestDebugMode.java +++ b/src/test/java/com/onarandombox/MultiverseCore/TestDebugMode.java @@ -20,6 +20,7 @@ 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; @@ -32,6 +33,7 @@ @RunWith(PowerMockRunner.class) @PrepareForTest({ MultiverseCore.class, PluginDescriptionFile.class, JavaPluginLoader.class}) +@PowerMockIgnore("javax.script.*") public class TestDebugMode { TestInstanceCreator creator; Server mockServer; diff --git a/src/test/java/com/onarandombox/MultiverseCore/TestEntitySpawnRules.java b/src/test/java/com/onarandombox/MultiverseCore/TestEntitySpawnRules.java index e6b985a11..6982b0244 100644 --- a/src/test/java/com/onarandombox/MultiverseCore/TestEntitySpawnRules.java +++ b/src/test/java/com/onarandombox/MultiverseCore/TestEntitySpawnRules.java @@ -3,8 +3,10 @@ import com.onarandombox.MultiverseCore.api.MVWorldManager; import com.onarandombox.MultiverseCore.api.MultiverseWorld; import com.onarandombox.MultiverseCore.listeners.MVEntityListener; +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; @@ -18,6 +20,7 @@ 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; @@ -26,11 +29,13 @@ 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.*; @RunWith(PowerMockRunner.class) @PrepareForTest({ MultiverseCore.class, PluginDescriptionFile.class, JavaPluginLoader.class}) +@PowerMockIgnore("javax.script.*") public class TestEntitySpawnRules { TestInstanceCreator creator; MultiverseCore core; @@ -53,7 +58,7 @@ public void setUp() throws Exception { listener = core.getEntityListener(); mvWorld = mock(MultiverseWorld.class); - cbworld = mock(World.class); + cbworld = MockWorldFactory.makeNewMockWorld("world", World.Environment.NORMAL, WorldType.NORMAL); when(mvWorld.getCBWorld()).thenReturn(cbworld); MVWorldManager worldman = mock(MVWorldManager.class); diff --git a/src/test/java/com/onarandombox/MultiverseCore/TestEntryFeeConversion.java b/src/test/java/com/onarandombox/MultiverseCore/TestEntryFeeConversion.java index b11bbdfa7..05b94d334 100644 --- a/src/test/java/com/onarandombox/MultiverseCore/TestEntryFeeConversion.java +++ b/src/test/java/com/onarandombox/MultiverseCore/TestEntryFeeConversion.java @@ -8,6 +8,7 @@ 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; @@ -18,6 +19,7 @@ @RunWith(PowerMockRunner.class) @PrepareForTest({ MultiverseCore.class, PluginDescriptionFile.class, JavaPluginLoader.class}) +@PowerMockIgnore("javax.script.*") public class TestEntryFeeConversion { private TestInstanceCreator creator; diff --git a/src/test/java/com/onarandombox/MultiverseCore/TestModifyCommand.java b/src/test/java/com/onarandombox/MultiverseCore/TestModifyCommand.java index 7d64081c6..26b21c8a7 100644 --- a/src/test/java/com/onarandombox/MultiverseCore/TestModifyCommand.java +++ b/src/test/java/com/onarandombox/MultiverseCore/TestModifyCommand.java @@ -12,6 +12,7 @@ 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; @@ -22,6 +23,7 @@ @RunWith(PowerMockRunner.class) @PrepareForTest({ MultiverseCore.class, PluginDescriptionFile.class, JavaPluginLoader.class }) +@PowerMockIgnore("javax.script.*") public class TestModifyCommand { TestInstanceCreator creator; Server mockServer; diff --git a/src/test/java/com/onarandombox/MultiverseCore/TestWorldProperties.java b/src/test/java/com/onarandombox/MultiverseCore/TestWorldProperties.java index aa114fb6a..4d61bebbb 100644 --- a/src/test/java/com/onarandombox/MultiverseCore/TestWorldProperties.java +++ b/src/test/java/com/onarandombox/MultiverseCore/TestWorldProperties.java @@ -45,6 +45,7 @@ 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; @@ -60,6 +61,7 @@ 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; diff --git a/src/test/java/com/onarandombox/MultiverseCore/TestWorldPurger.java b/src/test/java/com/onarandombox/MultiverseCore/TestWorldPurger.java index 838bb0571..10c5edfea 100644 --- a/src/test/java/com/onarandombox/MultiverseCore/TestWorldPurger.java +++ b/src/test/java/com/onarandombox/MultiverseCore/TestWorldPurger.java @@ -14,6 +14,7 @@ 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; @@ -24,6 +25,7 @@ @RunWith(PowerMockRunner.class) @PrepareForTest({ MultiverseCore.class, PluginDescriptionFile.class, JavaPluginLoader.class }) +@PowerMockIgnore("javax.script.*") public class TestWorldPurger { TestInstanceCreator creator; MultiverseCore core; diff --git a/src/test/java/com/onarandombox/MultiverseCore/TestWorldStuff.java b/src/test/java/com/onarandombox/MultiverseCore/TestWorldStuff.java index b98725d14..3920199e2 100644 --- a/src/test/java/com/onarandombox/MultiverseCore/TestWorldStuff.java +++ b/src/test/java/com/onarandombox/MultiverseCore/TestWorldStuff.java @@ -28,8 +28,10 @@ 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; @@ -41,6 +43,7 @@ @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; @@ -170,7 +173,7 @@ public void testWorldCreation() { verify(mockCommandSender).sendMessage("Complete!"); WorldCreatorMatcher matcher = new WorldCreatorMatcher(new WorldCreator("newworld")); - verify(mockServer).createWorld(Matchers.argThat(matcher)); + verify(mockServer).createWorld(ArgumentMatchers.argThat(matcher)); } @Test @@ -233,7 +236,7 @@ public void testNullWorld() { verify(mockCommandSender).sendMessage("Complete!"); WorldCreatorMatcher matcher = new WorldCreatorMatcher(new WorldCreator("nullworld")); - verify(mockServer).createWorld(Matchers.argThat(matcher)); + verify(mockServer).createWorld(ArgumentMatchers.argThat(matcher)); } @Test diff --git a/src/test/java/com/onarandombox/MultiverseCore/utils/MockWorldFactory.java b/src/test/java/com/onarandombox/MultiverseCore/utils/MockWorldFactory.java index ffe0e6687..79827c62f 100644 --- a/src/test/java/com/onarandombox/MultiverseCore/utils/MockWorldFactory.java +++ b/src/test/java/com/onarandombox/MultiverseCore/utils/MockWorldFactory.java @@ -178,6 +178,7 @@ public Block answer(InvocationOnMock invocation) throws Throwable { return mockBlock; } }); + when(mockWorld.getUID()).thenReturn(UUID.randomUUID()); return mockWorld; } diff --git a/src/test/java/com/onarandombox/MultiverseCore/utils/TestInstanceCreator.java b/src/test/java/com/onarandombox/MultiverseCore/utils/TestInstanceCreator.java index c4972d6a7..c198e0224 100644 --- a/src/test/java/com/onarandombox/MultiverseCore/utils/TestInstanceCreator.java +++ b/src/test/java/com/onarandombox/MultiverseCore/utils/TestInstanceCreator.java @@ -27,7 +27,7 @@ import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPluginLoader; import org.bukkit.scheduler.BukkitScheduler; -import org.mockito.Matchers; +import org.mockito.ArgumentMatchers; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.powermock.api.easymock.PowerMock; @@ -44,11 +44,15 @@ import java.util.logging.Logger; import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.any; -import static org.mockito.Mockito.anyBoolean; -import static org.mockito.Mockito.anyLong; -import static org.mockito.Mockito.*; +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; @@ -116,8 +120,6 @@ public Void answer(InvocationOnMock invocation) throws Throwable { Util.log("Creating world-folder: " + worldSkylandsFile.getAbsolutePath()); worldSkylandsFile.mkdirs(); - - // Give the server some worlds when(mockServer.getWorld(anyString())).thenAnswer(new Answer() { @Override @@ -154,7 +156,7 @@ public List answer(InvocationOnMock invocation) throws Throwable { when(mockServer.getPluginManager()).thenReturn(mockPluginManager); - when(mockServer.createWorld(Matchers.isA(WorldCreator.class))).thenAnswer( + when(mockServer.createWorld(ArgumentMatchers.isA(WorldCreator.class))).thenAnswer( new Answer() { @Override public World answer(InvocationOnMock invocation) throws Throwable { @@ -254,9 +256,9 @@ public Void answer(InvocationOnMock invocation) throws Throwable { when(commandSender.getServer()).thenReturn(mockServer); when(commandSender.getName()).thenReturn("MockCommandSender"); when(commandSender.isPermissionSet(anyString())).thenReturn(true); - when(commandSender.isPermissionSet(Matchers.isA(Permission.class))).thenReturn(true); + when(commandSender.isPermissionSet(ArgumentMatchers.isA(Permission.class))).thenReturn(true); when(commandSender.hasPermission(anyString())).thenReturn(true); - when(commandSender.hasPermission(Matchers.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); diff --git a/src/test/java/com/onarandombox/MultiverseCore/utils/WorldCreatorMatcher.java b/src/test/java/com/onarandombox/MultiverseCore/utils/WorldCreatorMatcher.java index 50d3682b9..5aa21841b 100644 --- a/src/test/java/com/onarandombox/MultiverseCore/utils/WorldCreatorMatcher.java +++ b/src/test/java/com/onarandombox/MultiverseCore/utils/WorldCreatorMatcher.java @@ -10,7 +10,7 @@ import org.bukkit.WorldCreator; import org.mockito.ArgumentMatcher; -public class WorldCreatorMatcher extends ArgumentMatcher { +public class WorldCreatorMatcher implements ArgumentMatcher { private WorldCreator worldCreator; private boolean careAboutSeeds = false; private boolean careAboutGenerators = false; @@ -28,23 +28,23 @@ public void careAboutGenerators(boolean doICare) { this.careAboutGenerators = doICare; } - public boolean matches(Object creator) { + public boolean matches(WorldCreator creator) { Util.log("Checking world creators."); if (creator == null) { Util.log("The given creator was null, but I was checking: " + this.worldCreator.name()); return false; } - Util.log("Checking Names...(" + ((WorldCreator) creator).name() + ") vs (" + this.worldCreator.name() + ")"); - Util.log("Checking Envs...(" + ((WorldCreator) creator).environment() + ") vs (" + this.worldCreator.environment() + ")"); - if (!((WorldCreator) creator).name().equals(this.worldCreator.name())) { + Util.log("Checking Names...(" + creator.name() + ") vs (" + this.worldCreator.name() + ")"); + Util.log("Checking Envs...(" + creator.environment() + ") vs (" + this.worldCreator.environment() + ")"); + if (!creator.name().equals(this.worldCreator.name())) { return false; - } else if (!((WorldCreator) creator).environment().equals(this.worldCreator.environment())) { + } else if (!creator.environment().equals(this.worldCreator.environment())) { Util.log("Checking Environments..."); return false; - } else if (careAboutSeeds && ((WorldCreator) creator).seed() != this.worldCreator.seed()) { + } else if (careAboutSeeds && creator.seed() != this.worldCreator.seed()) { Util.log("Checking Seeds..."); return false; - } else if (careAboutGenerators && !((WorldCreator) creator).generator().equals(this.worldCreator.generator())) { + } else if (careAboutGenerators && !creator.generator().equals(this.worldCreator.generator())) { Util.log("Checking Gens..."); return false; } From a6912c3cb534bef104650b07cdb762a73a0da9ad Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Thu, 24 Jan 2019 09:28:03 -0500 Subject: [PATCH 035/134] Added api-version: 1.13 to plugin.yml. Should fix #1958 --- src/main/resources/plugin.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 456eff628..d65a37791 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -2,6 +2,7 @@ name: Multiverse-Core main: com.onarandombox.MultiverseCore.MultiverseCore authors: ['Rigby', 'fernferret', 'lithium3141', 'main--', 'dumptruckman'] website: 'https://dev.bukkit.org/projects/multiverse-core' +api-version: 1.13 version: maven-version-number commands: mv: @@ -232,4 +233,4 @@ commands: mvrules: description: Lists the gamerules. usage: | - / [WORLD] \ No newline at end of file + / [WORLD] From 4552f70f7e958b24f880e86279802d0687497f6d Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Thu, 24 Jan 2019 21:22:56 -0500 Subject: [PATCH 036/134] Shade in id converter. --- pom.xml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/pom.xml b/pom.xml index 5b8bcbd6e..c7ad4cc77 100644 --- a/pom.xml +++ b/pom.xml @@ -197,6 +197,7 @@ org.mcstats.bukkit:metrics com.dumptruckman.minecraft:Logging org.codehaus.jettison:jettison + de.themoep.idconverter:mappings @@ -228,6 +229,10 @@ org.codehaus.jettison.json org.codehaus.jettison.json.multiverse + + de.themoep.idconverter + de.themoep.idconverter.multiverse + From d0180f05d5be58171702e57327f421be49c55ac8 Mon Sep 17 00:00:00 2001 From: Brokkonaut Date: Fri, 25 Jan 2019 19:16:29 +0100 Subject: [PATCH 037/134] Option to disable the automatic purge of entities (#1933) --- .../com/onarandombox/MultiverseCore/MVWorld.java | 4 +++- .../MultiverseCoreConfiguration.java | 13 +++++++++++++ .../MultiverseCore/api/MultiverseCoreConfig.java | 14 ++++++++++++++ .../MultiverseCore/utils/WorldManager.java | 5 ++++- 4 files changed, 34 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/MVWorld.java b/src/main/java/com/onarandombox/MultiverseCore/MVWorld.java index 4007352ac..bd85e3757 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MVWorld.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MVWorld.java @@ -282,7 +282,9 @@ public SpawnSettings validateChange(String property, SpawnSettings newValue, Spa } world.setSpawnFlags(allowMonsters, allowAnimals); } - plugin.getMVWorldManager().getTheWorldPurger().purgeWorld(MVWorld.this); + if (MultiverseCoreConfiguration.getInstance().isAutoPurgeEnabled()) { + plugin.getMVWorldManager().getTheWorldPurger().purgeWorld(MVWorld.this); + } return super.validateChange(property, newValue, oldValue, object); } } diff --git a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCoreConfiguration.java b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCoreConfiguration.java index 4ffadbb7c..65142f814 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCoreConfiguration.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCoreConfiguration.java @@ -67,6 +67,8 @@ public static MultiverseCoreConfiguration getInstance() { private volatile boolean defaultportalsearch; @Property private volatile int portalsearchradius; + @Property + private volatile boolean autopurge; public MultiverseCoreConfiguration() { super(); @@ -98,6 +100,7 @@ protected void setDefaults() { silentstart = false; defaultportalsearch = false; portalsearchradius = 128; + autopurge = true; // END CHECKSTYLE-SUPPRESSION: MagicNumberCheck } @@ -332,4 +335,14 @@ public void setPortalSearchRadius(int searchRadius) { public int getPortalSearchRadius() { return portalsearchradius; } + + @Override + public boolean isAutoPurgeEnabled() { + return autopurge; + } + + @Override + public void setAutoPurgeEnabled(boolean autopurge) { + this.autopurge = autopurge; + } } diff --git a/src/main/java/com/onarandombox/MultiverseCore/api/MultiverseCoreConfig.java b/src/main/java/com/onarandombox/MultiverseCore/api/MultiverseCoreConfig.java index bb49048fb..f66922ec3 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/api/MultiverseCoreConfig.java +++ b/src/main/java/com/onarandombox/MultiverseCore/api/MultiverseCoreConfig.java @@ -199,4 +199,18 @@ public interface MultiverseCoreConfig extends ConfigurationSerializable { * @return The portal search radius. */ int getPortalSearchRadius(); + + /** + * Gets whether or not the automatic purge of entities is enabled. + * + * @return True if automatic purge is enabled. + */ + boolean isAutoPurgeEnabled(); + + /** + * Sets whether or not the automatic purge of entities is enabled. + * + * @param autopurge True if automatic purge should be enabled. + */ + void setAutoPurgeEnabled(boolean autopurge); } diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/WorldManager.java b/src/main/java/com/onarandombox/MultiverseCore/utils/WorldManager.java index 681bfd1d3..41cd707e1 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/WorldManager.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/WorldManager.java @@ -10,6 +10,7 @@ import com.dumptruckman.minecraft.util.Logging; import com.onarandombox.MultiverseCore.MVWorld; import com.onarandombox.MultiverseCore.MultiverseCore; +import com.onarandombox.MultiverseCore.MultiverseCoreConfiguration; import com.onarandombox.MultiverseCore.WorldProperties; import com.onarandombox.MultiverseCore.api.MVWorldManager; import com.onarandombox.MultiverseCore.api.MultiverseWorld; @@ -474,7 +475,9 @@ private boolean doLoad(WorldCreator creator, boolean ignoreExists) { return false; } MVWorld world = new MVWorld(plugin, cbworld, mvworld); - this.worldPurger.purgeWorld(world); + if (MultiverseCoreConfiguration.getInstance().isAutoPurgeEnabled()) { + this.worldPurger.purgeWorld(world); + } this.worlds.put(worldName, world); return true; } From ae314108a3b458a49a62129c4d06d7380ad18de1 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Sun, 27 Jan 2019 21:34:26 -0500 Subject: [PATCH 038/134] Removed deprecated MVConfigProperty and MVActiveConfigProperty. --- .../onarandombox/MultiverseCore/MVWorld.java | 23 ------- .../MultiverseCore/api/MultiverseWorld.java | 31 --------- .../configuration/MVActiveConfigProperty.java | 37 ---------- .../configuration/MVConfigProperty.java | 69 ------------------- 4 files changed, 160 deletions(-) delete mode 100644 src/main/java/com/onarandombox/MultiverseCore/configuration/MVActiveConfigProperty.java delete mode 100644 src/main/java/com/onarandombox/MultiverseCore/configuration/MVConfigProperty.java diff --git a/src/main/java/com/onarandombox/MultiverseCore/MVWorld.java b/src/main/java/com/onarandombox/MultiverseCore/MVWorld.java index bd85e3757..d8f64e972 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MVWorld.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MVWorld.java @@ -605,29 +605,6 @@ else if (property.equalsIgnoreCase("monsters")) return null; } - /** - * {@inheritDoc} - * - * @deprecated This is deprecated. - */ - @Override - @Deprecated - public com.onarandombox.MultiverseCore.configuration.MVConfigProperty getProperty(String property, - Class expected) throws PropertyDoesNotExistException { - throw new UnsupportedOperationException("'MVConfigProperty getProperty(String,Class)' is no longer supported!"); - } - - /** - * {@inheritDoc} - * - * @deprecated This is deprecated. - */ - @Override - @Deprecated - public boolean setProperty(String name, String value, CommandSender sender) throws PropertyDoesNotExistException { - return this.setPropertyValue(name, value); - } - /** * {@inheritDoc} */ diff --git a/src/main/java/com/onarandombox/MultiverseCore/api/MultiverseWorld.java b/src/main/java/com/onarandombox/MultiverseCore/api/MultiverseWorld.java index 3561f49e0..1788cde8c 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/api/MultiverseWorld.java +++ b/src/main/java/com/onarandombox/MultiverseCore/api/MultiverseWorld.java @@ -155,37 +155,6 @@ public interface MultiverseWorld { */ boolean setPropertyValue(String property, String value) throws PropertyDoesNotExistException; - /** - * Gets the actual MVConfigProperty from this world. - * It will throw a PropertyDoesNotExistException if the property is not found. - * - * @param property The name of a world property to get. - * @param expected The type of the expected property. Use Object.class if this doesn't matter for you. - * @param The type of the expected property. - * - * @return A valid MVWorldProperty. - * - * @throws PropertyDoesNotExistException Thrown if the property was not found in the world. - * @deprecated We don't use {@link com.onarandombox.MultiverseCore.configuration.MVConfigProperty} any longer! - */ - @Deprecated - com.onarandombox.MultiverseCore.configuration.MVConfigProperty getProperty(String property, Class expected) throws PropertyDoesNotExistException; - - // old config - /** - * Adds the property to the given value. - * It will throw a PropertyDoesNotExistException if the property is not found. - * - * @param property The name of a world property to set. - * @param value A value in string representation, it will be parsed to the correct type. - * @param sender The sender who wants this value to be set. - * @return True if the value was set, false if not. - * @throws PropertyDoesNotExistException Thrown if the property was not found in the world. - * @deprecated Use {@link #setPropertyValue(String, String)} instead. - */ - @Deprecated - boolean setProperty(String property, String value, CommandSender sender) throws PropertyDoesNotExistException; - /** * Adds a value to the given property. The property must be a {@link com.onarandombox.MultiverseCore.enums.AddProperties}. * diff --git a/src/main/java/com/onarandombox/MultiverseCore/configuration/MVActiveConfigProperty.java b/src/main/java/com/onarandombox/MultiverseCore/configuration/MVActiveConfigProperty.java deleted file mode 100644 index 403d0026d..000000000 --- a/src/main/java/com/onarandombox/MultiverseCore/configuration/MVActiveConfigProperty.java +++ /dev/null @@ -1,37 +0,0 @@ -/****************************************************************************** - * Multiverse 2 Copyright (c) the Multiverse Team 2012. * - * 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.configuration; - -/** - * An "active" {@link MVConfigProperty} that uses the specified method to be "actually" set. - * @param The type of the config-property. - * @deprecated This is deprecated. - * @see MVConfigProperty - */ -@Deprecated -public interface MVActiveConfigProperty extends MVConfigProperty { - /** - * Gets the method that will be executed. - * - * @return The name of the method in MVWorld to be called. - */ - String getMethod(); - - /** - * Sets the method that will be executed. - * - * @param methodName The name of the method in MVWorld to be called. - */ - void setMethod(String methodName); - - /** - * Returns the class of the object we're looking at. - * @return the class of the object we're looking at. - */ - Class getPropertyClass(); -} diff --git a/src/main/java/com/onarandombox/MultiverseCore/configuration/MVConfigProperty.java b/src/main/java/com/onarandombox/MultiverseCore/configuration/MVConfigProperty.java deleted file mode 100644 index 537a46b57..000000000 --- a/src/main/java/com/onarandombox/MultiverseCore/configuration/MVConfigProperty.java +++ /dev/null @@ -1,69 +0,0 @@ -/****************************************************************************** - * Multiverse 2 Copyright (c) the Multiverse Team 2011. * - * 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.configuration; - -/** - * A generic config-property. - * - * @param The type of the config-property. - * @deprecated This is deprecated. - */ -@Deprecated -public interface MVConfigProperty { - /** - * Gets the name of this property. - * - * @return The name of this property. - */ - String getName(); - - /** - * Gets the value of this property. - * - * @return The value of this property. - */ - T getValue(); - - /** - * Gets the string representation of this value. - * - * @return The value of this property as a string. - */ - String toString(); - - /** - * Gets the help string for this. - * - * @return The value of this property as a string. - */ - String getHelp(); - - /** - * Sets the value of this property. - * - * @param value The T representation of this value. - * @return True the value was successfully set. - */ - boolean setValue(T value); - - /** - * This parseValue should be used with strings. - * - * @param value The string representation of the value to set. - * - * @return True if the value was set, false if not. - */ - boolean parseValue(String value); - - /** - * Gets the name of the config-node that this {@link MVConfigProperty} is saved as. - * - * @return The name of the config-node that this {@link MVConfigProperty} is saved as. - */ - String getConfigNode(); -} From a7cace0fdcee1b21ecb846e9551f6ad75924c0e0 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Mon, 28 Jan 2019 19:43:13 -0500 Subject: [PATCH 039/134] Fixed potential NPE. --- .../onarandombox/MultiverseCore/MultiverseCore.java | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java index 85a254bd4..cef299975 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java @@ -643,11 +643,15 @@ private void migrateWorldConfig() { // SUPPRESS CHECKSTYLE: MethodLength if (feeSection.isInt("currency")) { int oldCurrencyItemId = feeSection.getInt("currency", -1); if (oldCurrencyItemId >= 0) { - String flatteningType = IdMappings.getById(Integer.toString(oldCurrencyItemId)) - .getFlatteningType(); - world.setCurrency(Material.matchMaterial(flatteningType)); + IdMappings.Mapping mapping = IdMappings.getById(Integer.toString(oldCurrencyItemId)); + if (mapping != null) { + world.setCurrency(Material.matchMaterial(mapping.getFlatteningType())); + } else { + world.setCurrency(null); + } + } else { + world.setCurrency(null); } - world.setCurrency(null); } if (feeSection.isDouble("amount")) From 606a3fa3ce8f3c4266aa4eabe6571a483ebe4acd Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Tue, 29 Jan 2019 23:46:40 -0500 Subject: [PATCH 040/134] Added MaterialConverter util class for type id conversions. --- .travis.yml | 14 +++---- .../MultiverseCore/MultiverseCore.java | 17 +-------- .../MultiverseCore/WorldProperties.java | 1 - .../configuration/EntryFee.java | 11 ++---- .../utils/MaterialConverter.java | 38 +++++++++++++++++++ 5 files changed, 50 insertions(+), 31 deletions(-) create mode 100644 src/main/java/com/onarandombox/MultiverseCore/utils/MaterialConverter.java diff --git a/.travis.yml b/.travis.yml index a64f9f60d..1ecfa2d1f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,7 @@ -language: java -jdk: - - oraclejdk8 -notifications: - email: false -before_install: - - sed -i.bak -e 's|https://nexus.codehaus.org/snapshots/|https://oss.sonatype.org/content/repositories/codehaus-snapshots/|g' ~/.m2/settings.xml +language: java +jdk: + - oraclejdk8 +notifications: + email: false +before_install: + - sed -i.bak -e 's|https://nexus.codehaus.org/snapshots/|https://oss.sonatype.org/content/repositories/codehaus-snapshots/|g' ~/.m2/settings.xml diff --git a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java index cef299975..6d37f01e0 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java @@ -77,6 +77,7 @@ import com.onarandombox.MultiverseCore.utils.MVMessaging; import com.onarandombox.MultiverseCore.utils.MVPermissions; import com.onarandombox.MultiverseCore.utils.MVPlayerSession; +import com.onarandombox.MultiverseCore.utils.MaterialConverter; import com.onarandombox.MultiverseCore.utils.SimpleBlockSafety; import com.onarandombox.MultiverseCore.utils.SimpleLocationManipulation; import com.onarandombox.MultiverseCore.utils.SimpleSafeTTeleporter; @@ -84,15 +85,12 @@ import com.onarandombox.MultiverseCore.utils.VaultHandler; import com.onarandombox.MultiverseCore.utils.WorldManager; import com.pneumaticraft.commandhandler.CommandHandler; -import de.themoep.idconverter.IdMappings; import me.main__.util.SerializationConfig.NoSuchPropertyException; import me.main__.util.SerializationConfig.SerializationConfig; import org.bukkit.ChatColor; import org.bukkit.Difficulty; import org.bukkit.GameMode; import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.Server; import org.bukkit.World.Environment; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; @@ -103,7 +101,6 @@ import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.PluginDescriptionFile; -import org.bukkit.plugin.PluginLoader; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPluginLoader; @@ -641,17 +638,7 @@ private void migrateWorldConfig() { // SUPPRESS CHECKSTYLE: MethodLength if (section.isConfigurationSection("entryfee")) { ConfigurationSection feeSection = section.getConfigurationSection("entryfee"); if (feeSection.isInt("currency")) { - int oldCurrencyItemId = feeSection.getInt("currency", -1); - if (oldCurrencyItemId >= 0) { - IdMappings.Mapping mapping = IdMappings.getById(Integer.toString(oldCurrencyItemId)); - if (mapping != null) { - world.setCurrency(Material.matchMaterial(mapping.getFlatteningType())); - } else { - world.setCurrency(null); - } - } else { - world.setCurrency(null); - } + world.setCurrency(MaterialConverter.convertConfigType(feeSection, "currency")); } if (feeSection.isDouble("amount")) diff --git a/src/main/java/com/onarandombox/MultiverseCore/WorldProperties.java b/src/main/java/com/onarandombox/MultiverseCore/WorldProperties.java index 1e882c712..3dd208b86 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/WorldProperties.java +++ b/src/main/java/com/onarandombox/MultiverseCore/WorldProperties.java @@ -8,7 +8,6 @@ import com.onarandombox.MultiverseCore.enums.AllowedPortalType; import com.onarandombox.MultiverseCore.enums.EnglishChatColor; import com.onarandombox.MultiverseCore.enums.EnglishChatStyle; -import de.themoep.idconverter.IdMappings; import me.main__.util.SerializationConfig.IllegalPropertyValueException; import me.main__.util.SerializationConfig.Property; import me.main__.util.SerializationConfig.SerializationConfig; diff --git a/src/main/java/com/onarandombox/MultiverseCore/configuration/EntryFee.java b/src/main/java/com/onarandombox/MultiverseCore/configuration/EntryFee.java index 42a1d4c39..be66fb3ad 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/configuration/EntryFee.java +++ b/src/main/java/com/onarandombox/MultiverseCore/configuration/EntryFee.java @@ -2,8 +2,7 @@ import java.util.Map; -import de.themoep.idconverter.IdMappings; -import me.main__.util.SerializationConfig.IllegalPropertyValueException; +import com.onarandombox.MultiverseCore.utils.MaterialConverter; import me.main__.util.SerializationConfig.Property; import me.main__.util.SerializationConfig.SerializationConfig; @@ -78,12 +77,8 @@ public String serialize(Material material) { } @Override - public Material deserialize(Object o, Class aClass) throws IllegalPropertyValueException { - IdMappings.Mapping mapping = IdMappings.getById(o.toString()); - if (mapping != null) { - return Material.matchMaterial(mapping.getFlatteningType()); - } - return Material.matchMaterial(o.toString()); + public Material deserialize(Object o, Class aClass) { + return MaterialConverter.convertTypeString(o.toString()); } } } diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/MaterialConverter.java b/src/main/java/com/onarandombox/MultiverseCore/utils/MaterialConverter.java new file mode 100644 index 000000000..cf4e1286d --- /dev/null +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/MaterialConverter.java @@ -0,0 +1,38 @@ +package com.onarandombox.MultiverseCore.utils; + +import de.themoep.idconverter.IdMappings; +import org.bukkit.Material; +import org.bukkit.configuration.ConfigurationSection; + +/** + * A tool for converting values which may be an old type ID to a Material. + */ +public class MaterialConverter { + + /** + * Converts the value in the given config at the given path from a numeric id or flattened material name to a + * Material. + * + * @param config The config with the value to convert. + * @param path The path of the value in the config. + * @return The converted Material type or null if no matching type. + */ + public static Material convertConfigType(ConfigurationSection config, String path) { + return convertTypeString(config.getString(path)); + } + + /** + * Converts a string representing a numeric id or flattened material name to a Material. + * + * @param value The value to convert. + * @return The converted Material type or null if no matching type. + */ + public static Material convertTypeString(String value) { + IdMappings.Mapping mapping = IdMappings.getById(value); + if (mapping != null) { + return Material.matchMaterial(mapping.getFlatteningType()); + } else { + return Material.matchMaterial(value); + } + } +} From 9b88d1d49112103a9139472efba8fabc551d7c9d Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Tue, 29 Jan 2019 23:54:58 -0500 Subject: [PATCH 041/134] Updated logging library to 1.1.1. --- pom.xml | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/pom.xml b/pom.xml index c7ad4cc77..90f243629 100644 --- a/pom.xml +++ b/pom.xml @@ -359,15 +359,9 @@ com.dumptruckman.minecraft Logging - 1.0.9 + 1.1.1 jar compile - - - org.bukkit - craftbukkit - - From 0f14ee557d790538afb3426be833d9463ea9e947 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Wed, 30 Jan 2019 00:14:16 -0500 Subject: [PATCH 042/134] Make Bukkit dependency scope provided. --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 90f243629..7db971046 100644 --- a/pom.xml +++ b/pom.xml @@ -288,7 +288,7 @@ org.bukkit bukkit 1.13.2-R0.1-SNAPSHOT - compile + provided org.bukkit bukkit 1.13.2-R0.1-SNAPSHOT provided - me.main__.util diff --git a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java index 6d37f01e0..f5ac4d11c 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java @@ -230,7 +230,6 @@ public int getProtocolVersion() { private Buscript buscript; private int pluginCount; private DestinationFactory destFactory; - //private SpoutInterface spoutInterface = null; private MultiverseMessaging messaging; private BlockSafety blockSafety; private LocationManipulation locationManipulation; @@ -334,13 +333,6 @@ public void onEnable() { this.chatListener = new MVPlayerChatListener(this, this.playerListener); } getServer().getPluginManager().registerEvents(this.chatListener, this); - /* - // Check to see if spout was already loaded (most likely): - if (this.getServer().getPluginManager().getPlugin("Spout") != null) { - this.setSpout(); - this.log(Level.INFO, "Spout integration enabled."); - } - */ this.initializeBuscript(); this.setupMetrics(); @@ -1084,25 +1076,6 @@ public void setServerFolder(File newServerFolder) { this.serverFolder = newServerFolder; } - /* - /** - * Initializes Spout. - * / - public void setSpout() { - this.spoutInterface = new SpoutInterface(); - this.commandHandler.registerCommand(new SpoutCommand(this)); - } - - /** - * Gets our {@link SpoutInterface}. - * - * @return The {@link SpoutInterface} we're using. - * / - public SpoutInterface getSpout() { - return this.spoutInterface; - } - */ - /** * {@inheritDoc} */ diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/SpoutCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/SpoutCommand.java deleted file mode 100644 index 3683d9375..000000000 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/SpoutCommand.java +++ /dev/null @@ -1,66 +0,0 @@ -/****************************************************************************** - * Multiverse 2 Copyright (c) the Multiverse Team 2011. * - * 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.commands; - -import com.onarandombox.MultiverseCore.MultiverseCore; -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.permissions.PermissionDefault; -import org.getspout.spoutapi.gui.GenericButton; -import org.getspout.spoutapi.gui.GenericPopup; -import org.getspout.spoutapi.gui.PopupScreen; -import org.getspout.spoutapi.player.SpoutPlayer; - -import java.util.List; - -/** - * Edit a world with spout. - * / -public class SpoutCommand extends MultiverseCommand { - - public SpoutCommand(MultiverseCore plugin) { - super(plugin); - this.setName("Edit World with Spout"); - this.setCommandUsage("/mv spout"); - this.setArgRange(0, 0); - this.addKey("mv spout"); - this.setPermission("multiverse.core.spout", "Edit a world with spout.", PermissionDefault.OP); - this.addCommandExample("/mv spout"); - } - - @Override - public void runCommand(CommandSender sender, List args) { - if (!(sender instanceof Player)) { - sender.sendMessage(ChatColor.RED + "This command must be run as a player!"); - return; - } - if (plugin.getSpout() == null) { - sender.sendMessage(ChatColor.RED + "You need spout installed on this server to use it with Multiverse!"); - return; - } - SpoutPlayer p = (SpoutPlayer) sender; - if (!p.isSpoutCraftEnabled()) { - sender.sendMessage(ChatColor.RED + p.getName() + "You need to be using the Spoutcraft client to run this command!"); - return; - } - PopupScreen pop = new GenericPopup(); - GenericButton button = new GenericButton("Fish"); - // TO-DO maybe use constants for these - // BEGIN CHECKSTYLE-SUPPRESSION: MagicNumberCheck - button.setX(50); - button.setY(50); - button.setWidth(100); - button.setHeight(40); - // END CHECKSTYLE-SUPPRESSION: MagicNumberCheck - pop.attachWidget(this.plugin, button); - sender.sendMessage(ChatColor.GREEN + "YAY!"); - p.getMainScreen().attachPopupScreen(pop); - } -} -*/ diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/SpoutInterface.java b/src/main/java/com/onarandombox/MultiverseCore/utils/SpoutInterface.java deleted file mode 100644 index 192215084..000000000 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/SpoutInterface.java +++ /dev/null @@ -1,30 +0,0 @@ -/****************************************************************************** - * Multiverse 2 Copyright (c) the Multiverse Team 2011. * - * 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.utils; - -import org.getspout.spoutapi.SpoutManager; - -/** - * A helper-class holding the {@link SpoutManager}. - * / -public class SpoutInterface { - private SpoutManager spoutManager; - - public SpoutInterface() { - this.spoutManager = SpoutManager.getInstance(); - } - - /** - * Gets the {@link SpoutManager}. - * @return The {@link SpoutManager}. - * / - public SpoutManager getManager() { - return this.spoutManager; - } -} -*/ From 5e067fa72da3b5e6bc772021d97ec94a6ef125ed Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Wed, 30 Jan 2019 08:53:40 -0500 Subject: [PATCH 046/134] Fixes NPE in MaterialConverter. --- .../onarandombox/MultiverseCore/utils/MaterialConverter.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/MaterialConverter.java b/src/main/java/com/onarandombox/MultiverseCore/utils/MaterialConverter.java index 7f8068dc5..016758453 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/MaterialConverter.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/MaterialConverter.java @@ -32,7 +32,7 @@ public static Material convertConfigType(@NotNull ConfigurationSection config, @ */ @Nullable public static Material convertTypeString(@Nullable String value) { - IdMappings.Mapping mapping = IdMappings.getById(value); + IdMappings.Mapping mapping = IdMappings.getById(value != null ? value : ""); if (mapping != null) { return Material.matchMaterial(mapping.getFlatteningType()); } else { From d7894eb847e0d00ed360c224f0d6f41639f5d906 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Wed, 30 Jan 2019 10:11:43 -0500 Subject: [PATCH 047/134] Fix another NPE in MaterialConverter. --- .../onarandombox/MultiverseCore/utils/MaterialConverter.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/MaterialConverter.java b/src/main/java/com/onarandombox/MultiverseCore/utils/MaterialConverter.java index 016758453..0fd19457e 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/MaterialConverter.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/MaterialConverter.java @@ -36,7 +36,7 @@ public static Material convertTypeString(@Nullable String value) { if (mapping != null) { return Material.matchMaterial(mapping.getFlatteningType()); } else { - return Material.matchMaterial(value); + return Material.matchMaterial(value != null ? value : ""); } } } From aa574b62369c00154861bb1c24e943ba1189c5d4 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Thu, 31 Jan 2019 21:19:23 -0500 Subject: [PATCH 048/134] Cleaned up the pom a bit and fixed some dependency shading issues. --- pom.xml | 62 +++++++++++++++------------------------------------------ 1 file changed, 16 insertions(+), 46 deletions(-) diff --git a/pom.xml b/pom.xml index b49e68284..8e11e688f 100644 --- a/pom.xml +++ b/pom.xml @@ -173,15 +173,15 @@ jar - false - + false + org.apache.maven.plugins maven-shade-plugin - 2.4.3 + 3.1.1 package @@ -190,32 +190,24 @@ - - me.main__.util:SerializationConfig - com.pneumaticraft.commandhandler:CommandHandler - com.dumptruckman.minecraft:buscript - org.mcstats.bukkit:metrics - com.dumptruckman.minecraft:Logging - org.codehaus.jettison:jettison - de.themoep.idconverter:mappings - + commons-io:commons-io me.main__.util - me.main__.util.multiverse + com.onarandombox.serializationconfig com.pneumaticraft.commandhandler - com.pneumaticraft.commandhandler.multiverse + com.onarandombox.commandhandler buscript - buscript.multiverse + com.onarandombox.buscript org.mcstats - org.mcstats.multiverse + com.onarandombox.mcstats com.dumptruckman.minecraft.util.Logging @@ -226,12 +218,12 @@ com.onarandombox.MultiverseCore.utils.DebugFileLogger - org.codehaus.jettison.json - org.codehaus.jettison.json.multiverse + org.codehaus.jettison + com.onarandombox.jettison de.themoep.idconverter - de.themoep.idconverter.multiverse + com.onarandombox.idconverter @@ -251,7 +243,7 @@ org.apache.commons - org.apache.commons.multiverse + com.onarandombox.commons true @@ -280,8 +272,6 @@ commons-io commons-io 2.4 - jar - compile org.bukkit @@ -294,8 +284,6 @@ me.main__.util SerializationConfig 1.7 - jar - compile org.bukkit @@ -309,8 +297,7 @@ net.milkbowl.vault VaultAPI 1.5 - jar - compile + provided @@ -318,26 +305,16 @@ com.pneumaticraft.commandhandler CommandHandler 10 - jar - compile - - com.dumptruckman.minecraft buscript 2.0-SNAPSHOT - jar - compile - - org.mcstats.bukkit metrics R8-SNAPSHOT - jar - compile org.bukkit @@ -345,40 +322,34 @@ - - com.dumptruckman.minecraft Logging 1.1.1 - jar - compile - - + org.codehaus.jettison jettison 1.3.8 - org.jetbrains annotations 16.0.2 - jar - compile de.themoep.idconverter mappings 1.2-SNAPSHOT + junit junit 4.12 + test org.powermock @@ -407,7 +378,6 @@ 4.0.2 test - From d832e9e6d9497a16ed0438396cbe05d4b8d52f61 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Thu, 31 Jan 2019 21:21:50 -0500 Subject: [PATCH 049/134] Updated vault dependency to 1.7. --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 8e11e688f..5887bf4f2 100644 --- a/pom.xml +++ b/pom.xml @@ -296,7 +296,7 @@ net.milkbowl.vault VaultAPI - 1.5 + 1.7 provided From 564a7d36849f40cf37d4dae228746ad7e14c5ebe Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Thu, 31 Jan 2019 21:26:12 -0500 Subject: [PATCH 050/134] Removed pastie paste service. --- .../commands/VersionCommand.java | 5 +- .../utils/webpaste/PasteService.java | 2 +- .../utils/webpaste/PasteServiceFactory.java | 2 - .../utils/webpaste/PasteServiceType.java | 4 - .../utils/webpaste/PastiePasteService.java | 118 ------------------ 5 files changed, 2 insertions(+), 129 deletions(-) delete mode 100644 src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PastiePasteService.java diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java index f529c1591..1a577e263 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java @@ -160,10 +160,7 @@ public void runCommand(final CommandSender sender, final List args) { public void run() { if (args.size() == 1) { String pasteUrl; - if (args.get(0).equalsIgnoreCase("-p")) { - // private post to pastie - pasteUrl = postToService(PasteServiceType.PASTIE, true, data, files); - } else if (args.get(0).equalsIgnoreCase("-b")) { + if (args.get(0).equalsIgnoreCase("-b")) { // private post to pastebin pasteUrl = postToService(PasteServiceType.PASTEBIN, true, data, files); } else if (args.get(0).equalsIgnoreCase("-g")) { diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteService.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteService.java index 71ba3a8e0..403f5ab83 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteService.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteService.java @@ -13,7 +13,7 @@ * * Services that provide a distinction between "public" and "private" pastes * should implement a custom constructor that specifies which kind the PasteService - * instance is submitting; an example of this is the PastiePasteService class. + * instance is submitting; an example of this is the PastebinPasteService class. */ public interface PasteService { diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceFactory.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceFactory.java index 1319ac20a..4ef179bee 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceFactory.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceFactory.java @@ -16,8 +16,6 @@ public static PasteService getService(PasteServiceType type, boolean isPrivate) switch(type) { case PASTEBIN: return new PastebinPasteService(isPrivate); - case PASTIE: - return new PastiePasteService(isPrivate); case GITHUB: return new GithubPasteService(isPrivate); default: diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceType.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceType.java index 5954dd884..ccdd5febe 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceType.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceType.java @@ -11,10 +11,6 @@ public enum PasteServiceType { * @see PastebinPasteService */ PASTEBIN, - /** - * @see PastiePasteService - */ - PASTIE, /** * @see GithubPasteService */ diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PastiePasteService.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PastiePasteService.java deleted file mode 100644 index 16c062a2f..000000000 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PastiePasteService.java +++ /dev/null @@ -1,118 +0,0 @@ -package com.onarandombox.MultiverseCore.utils.webpaste; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.UnsupportedEncodingException; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLEncoder; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Pastes to {@code pastie.org}. - */ -public class PastiePasteService implements PasteService { - - private boolean isPrivate; - - public PastiePasteService(boolean isPrivate) { - this.isPrivate = isPrivate; - } - - /** - * {@inheritDoc} - */ - @Override - public URL getPostURL() { - try { - return new URL("http://pastie.org/pastes"); - } catch (MalformedURLException e) { - return null; // should never hit here - } - } - - /** - * {@inheritDoc} - */ - @Override - public String encodeData(String data) { - try { - String encData = URLEncoder.encode("paste[authorization]", "UTF-8") + "=" + URLEncoder.encode("burger", "UTF-8"); // burger is magic - encData += "&" + URLEncoder.encode("paste[restricted]", "UTF-8") + "=" + URLEncoder.encode(this.isPrivate ? "1" : "0", "UTF-8"); - encData += "&" + URLEncoder.encode("paste[parser_id]", "UTF-8") + "=" + URLEncoder.encode("6", "UTF-8"); // 6 is plain text - encData += "&" + URLEncoder.encode("paste[body]", "UTF-8") + "=" + URLEncoder.encode(data, "UTF-8"); - return encData; - } catch (UnsupportedEncodingException e) { - return ""; // should never hit here - } - } - - @Override - public String encodeData(Map data) { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String postData(String encodedData, URL url) throws PasteFailedException { - OutputStreamWriter wr = null; - BufferedReader rd = null; - try { - URLConnection conn = url.openConnection(); - conn.setDoOutput(true); - wr = new OutputStreamWriter(conn.getOutputStream()); - wr.write(encodedData); - wr.flush(); - - rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); - String line; - String pastieUrl = ""; - Pattern pastiePattern = this.getURLMatchingPattern(); - while ((line = rd.readLine()) != null) { - Matcher m = pastiePattern.matcher(line); - if (m.matches()) { - String pastieID = m.group(1); - pastieUrl = this.formatURL(pastieID); - } - } - return pastieUrl; - } catch (Exception e) { - throw new PasteFailedException(e); - } finally { - if (wr != null) { - try { - wr.close(); - } catch (IOException ignore) { } - } - if (rd != null) { - try { - rd.close(); - } catch (IOException ignore) { } - } - } - } - - @Override - public boolean supportsMultiFile() { - return false; - } - - private Pattern getURLMatchingPattern() { - if (this.isPrivate) { - return Pattern.compile(".*http://pastie.org/.*key=([0-9a-z]+).*"); - } else { - return Pattern.compile(".*http://pastie.org/([0-9]+).*"); - } - } - - private String formatURL(String pastieID) { - return "http://pastie.org/" + (this.isPrivate ? "private/" : "") + pastieID; - } -} From 4c9d108f082df09ab5bc875674a47ed6b05d6cb7 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Thu, 31 Jan 2019 21:31:39 -0500 Subject: [PATCH 051/134] Disabled github paste service. --- .../onarandombox/MultiverseCore/commands/VersionCommand.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java index 1a577e263..3d1e3f7eb 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java @@ -163,9 +163,6 @@ public void run() { if (args.get(0).equalsIgnoreCase("-b")) { // private post to pastebin pasteUrl = postToService(PasteServiceType.PASTEBIN, true, data, files); - } else if (args.get(0).equalsIgnoreCase("-g")) { - // private post to github - pasteUrl = postToService(PasteServiceType.GITHUB, true, data, files); } else { return; } From b201b097197bfcc31d7332cec48f368acc8718b7 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Thu, 31 Jan 2019 22:02:13 -0500 Subject: [PATCH 052/134] Added a theoretically working Hastebin option for mvv output. --- .../commands/VersionCommand.java | 5 +- .../utils/webpaste/HastebinPasteService.java | 81 +++++++++++++++++++ .../utils/webpaste/PasteServiceFactory.java | 2 + .../utils/webpaste/PasteServiceType.java | 4 + 4 files changed, 91 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HastebinPasteService.java diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java index 3d1e3f7eb..e3f16742e 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java @@ -36,7 +36,7 @@ public class VersionCommand extends MultiverseCommand { public VersionCommand(MultiverseCore plugin) { super(plugin); this.setName("Multiverse Version"); - this.setCommandUsage("/mv version " + ChatColor.GOLD + "-[pbg]"); + this.setCommandUsage("/mv version " + ChatColor.GOLD + "-[bh]"); this.setArgRange(0, 1); this.addKey("mv version"); this.addKey("mvv"); @@ -163,6 +163,9 @@ public void run() { if (args.get(0).equalsIgnoreCase("-b")) { // private post to pastebin pasteUrl = postToService(PasteServiceType.PASTEBIN, true, data, files); + } else if (args.get(0).equalsIgnoreCase("-h")) { + // private post to pastebin + pasteUrl = postToService(PasteServiceType.HASTEBIN, true, data, files); } else { return; } diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HastebinPasteService.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HastebinPasteService.java new file mode 100644 index 000000000..69438cfd7 --- /dev/null +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HastebinPasteService.java @@ -0,0 +1,81 @@ +package com.onarandombox.MultiverseCore.utils.webpaste; + +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.util.Map; + +/** + * Pastes to {@code hastebin.com}. + */ +public class HastebinPasteService implements PasteService { + + @Override + public String encodeData(String data) { + return data; + } + + @Override + public String encodeData(Map data) { + throw new UnsupportedOperationException(); + } + + @Override + public URL getPostURL() { + try { + return new URL("https://hastebin.com/documents"); + } catch (MalformedURLException e) { + return null; // should never hit here + } + } + + @Override + public String postData(String encodedData, URL url) throws PasteFailedException { + OutputStreamWriter wr = null; + BufferedReader rd = null; + try { + URLConnection conn = url.openConnection(); + conn.setDoOutput(true); + + wr = new OutputStreamWriter(conn.getOutputStream()); + rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); + + wr.write(encodedData); + wr.flush(); + + String line; + StringBuilder responseString = new StringBuilder(); + while ((line = rd.readLine()) != null) { + responseString.append(line); + } + String key = new JsonParser().parse(responseString.toString()).getAsJsonObject().get("key").getAsString(); + + return "https://hastebin.com/" + key; + } catch (Exception e) { + throw new PasteFailedException(e); + } finally { + if (wr != null) { + try { + wr.close(); + } catch (IOException ignore) { } + } + if (rd != null) { + try { + rd.close(); + } catch (IOException ignore) { } + } + } + } + + @Override + public boolean supportsMultiFile() { + return false; + } +} diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceFactory.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceFactory.java index 4ef179bee..df4fb8315 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceFactory.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceFactory.java @@ -16,6 +16,8 @@ public static PasteService getService(PasteServiceType type, boolean isPrivate) switch(type) { case PASTEBIN: return new PastebinPasteService(isPrivate); + case HASTEBIN: + return new HastebinPasteService(); case GITHUB: return new GithubPasteService(isPrivate); default: diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceType.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceType.java index ccdd5febe..0bd93e635 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceType.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceType.java @@ -11,6 +11,10 @@ public enum PasteServiceType { * @see PastebinPasteService */ PASTEBIN, + /** + * @see HastebinPasteService + */ + HASTEBIN, /** * @see GithubPasteService */ From 8b358b0955025de8f77faeb4e5bff0eebd1038b0 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Thu, 31 Jan 2019 22:03:11 -0500 Subject: [PATCH 053/134] Don't send mvv url response to console twice when run from console. --- .../onarandombox/MultiverseCore/commands/VersionCommand.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java index e3f16742e..95013ca51 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java @@ -18,6 +18,7 @@ import com.onarandombox.MultiverseCore.utils.webpaste.URLShortener; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; +import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; import org.bukkit.permissions.PermissionDefault; import org.bukkit.scheduler.BukkitRunnable; @@ -170,7 +171,9 @@ public void run() { return; } - sender.sendMessage("Version info dumped here: " + ChatColor.GREEN + pasteUrl); + if (!(sender instanceof ConsoleCommandSender)) { + sender.sendMessage("Version info dumped here: " + ChatColor.GREEN + pasteUrl); + } Logging.info("Version info dumped here: %s", pasteUrl); } } From 6ebc1188e80f754b62ce707ba02626fe02631107 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Thu, 31 Jan 2019 22:09:09 -0500 Subject: [PATCH 054/134] Removed unnecessary json dependency. --- pom.xml | 6 ---- .../utils/webpaste/GithubPasteService.java | 36 ++++++++----------- 2 files changed, 15 insertions(+), 27 deletions(-) diff --git a/pom.xml b/pom.xml index 5887bf4f2..e534ff196 100644 --- a/pom.xml +++ b/pom.xml @@ -327,12 +327,6 @@ Logging 1.1.1 - - - org.codehaus.jettison - jettison - 1.3.8 - org.jetbrains annotations diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/GithubPasteService.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/GithubPasteService.java index 86f9888ed..6d8409692 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/GithubPasteService.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/GithubPasteService.java @@ -1,7 +1,8 @@ package com.onarandombox.MultiverseCore.utils.webpaste; -import org.codehaus.jettison.json.JSONException; -import org.codehaus.jettison.json.JSONObject; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.JsonPrimitive; import java.io.BufferedReader; import java.io.IOException; @@ -30,24 +31,18 @@ public String encodeData(String data) { @Override public String encodeData(Map files) { - JSONObject root = new JSONObject(); - String result = ""; - try { - root.put("description", "Multiverse-Core Debug Info"); - root.put("public", !this.isPrivate); - JSONObject fileList = new JSONObject(); - for (Map.Entry entry : files.entrySet()) - { - JSONObject fileObject = new JSONObject(); - fileObject.put("content", entry.getValue()); - fileList.put(entry.getKey(), fileObject); - } - root.put("files", fileList); - result = root.toString(); - } catch (JSONException e) { - e.printStackTrace(); + JsonObject root = new JsonObject(); + root.add("description", new JsonPrimitive("Multiverse-Core Debug Info")); + root.add("public", new JsonPrimitive(!this.isPrivate)); + JsonObject fileList = new JsonObject(); + for (Map.Entry entry : files.entrySet()) + { + JsonObject fileObject = new JsonObject(); + fileObject.add("content", new JsonPrimitive(entry.getValue())); + fileList.add(entry.getKey(), fileObject); } - return result; + root.add("files", fileList); + return root.toString(); } @Override @@ -80,8 +75,7 @@ public String postData(String encodedData, URL url) throws PasteFailedException while ((line = rd.readLine()) != null) { responseString.append(line); } - JSONObject response = new JSONObject(responseString.toString()); - return response.get("html_url").toString(); + return new JsonParser().parse(responseString.toString()).getAsJsonObject().get("html_url").getAsString(); } catch (Exception e) { throw new PasteFailedException(e); } finally { From 7762aca019fbdcdf61c5e12ccc384d1024c12ad7 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Sat, 2 Feb 2019 00:53:51 -0500 Subject: [PATCH 055/134] Removed commons-io as compile dependency to fix weird pom issues. --- pom.xml | 35 ++------ .../MultiverseCore/utils/FileUtils.java | 29 +++++-- .../MultiverseCore/utils/FileUtilsTest.java | 85 +++++++++++++++++++ 3 files changed, 112 insertions(+), 37 deletions(-) create mode 100644 src/test/java/com/onarandombox/MultiverseCore/utils/FileUtilsTest.java diff --git a/pom.xml b/pom.xml index e534ff196..6a1ed1818 100644 --- a/pom.xml +++ b/pom.xml @@ -189,9 +189,6 @@ shade - - commons-io:commons-io - me.main__.util @@ -228,27 +225,6 @@ - - apache-commons-io - package - - shade - - - - - commons-io:commons-io - - - - - org.apache.commons - com.onarandombox.commons - - - true - - @@ -268,11 +244,6 @@ - - commons-io - commons-io - 2.4 - org.bukkit bukkit @@ -372,6 +343,12 @@ 4.0.2 test + + commons-io + commons-io + 2.4 + test + diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/FileUtils.java b/src/main/java/com/onarandombox/MultiverseCore/utils/FileUtils.java index 4bc4a18ab..18a39d577 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/FileUtils.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/FileUtils.java @@ -11,7 +11,11 @@ import java.io.File; import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Comparator; import java.util.logging.Logger; +import java.util.stream.Stream; /** * File-utilities. @@ -28,8 +32,8 @@ protected FileUtils() { * @return true if the folder was successfully deleted. */ public static boolean deleteFolder(File file) { - try { - org.apache.commons.io.FileUtils.deleteDirectory(file); + try (Stream files = Files.walk(file.toPath())) { + files.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete); return true; } catch (IOException e) { Logging.warning(e.getMessage()); @@ -44,8 +48,11 @@ public static boolean deleteFolder(File file) { * @return true if the contents were successfully deleted */ public static boolean deleteFolderContents(File file) { - try { - org.apache.commons.io.FileUtils.cleanDirectory(file); + try (Stream files = Files.walk(file.toPath())){ + files.sorted(Comparator.reverseOrder()) + .map(Path::toFile) + .filter(f -> !f.equals(file)) + .forEach(File::delete); return true; } catch (IOException e) { Logging.warning(e.getMessage()); @@ -53,8 +60,6 @@ public static boolean deleteFolderContents(File file) { } } - private static final int COPY_BLOCK_SIZE = 1024; - /** * Helper method to copy the world-folder. * @param source Source-File @@ -64,8 +69,16 @@ public static boolean deleteFolderContents(File file) { * @return if it had success */ public static boolean copyFolder(File source, File target, Logger log) { - try { - org.apache.commons.io.FileUtils.copyDirectory(source, target); + Path sourcePath = source.toPath(); + Path destPath = target.toPath(); + try (Stream files = Files.walk(source.toPath())) { + files.forEachOrdered(src -> { + try { + Files.copy(src, sourcePath.resolve(destPath.relativize(src))); + } catch (IOException e) { + log.warning(e.getMessage()); + } + }); return true; } catch (IOException e) { log.warning(e.getMessage()); diff --git a/src/test/java/com/onarandombox/MultiverseCore/utils/FileUtilsTest.java b/src/test/java/com/onarandombox/MultiverseCore/utils/FileUtilsTest.java new file mode 100644 index 000000000..b32de6556 --- /dev/null +++ b/src/test/java/com/onarandombox/MultiverseCore/utils/FileUtilsTest.java @@ -0,0 +1,85 @@ +package com.onarandombox.MultiverseCore.utils; + +import com.dumptruckman.minecraft.util.Logging; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; + +import static org.junit.Assert.*; + +public class FileUtilsTest { + + private File parentDir; + private File parentDirFile; + private File childDir; + private File childDirFile; + private File dest; + + @Before + public void setUp() throws Exception { + parentDir = Files.createTempDirectory("parentDir").toFile(); + parentDirFile = new File(parentDir, "parentDirFile.txt"); + parentDirFile.createNewFile(); + childDir = Files.createTempDirectory(parentDir.toPath(), "childDir").toFile(); + childDirFile = new File(childDir, "childDirFile.txt"); + childDirFile.createNewFile(); + dest = Files.createTempDirectory("dest").toFile(); + + assertTrue(parentDir.exists()); + assertTrue(parentDirFile.exists()); + assertTrue(childDir.exists()); + assertTrue(childDirFile.exists()); + assertTrue(dest.exists()); + } + + @After + public void tearDown() throws Exception { + try { + org.apache.commons.io.FileUtils.deleteDirectory(parentDir); + } catch (IOException e) { + if (parentDir.exists()) { + throw e; + } + } + try { + org.apache.commons.io.FileUtils.deleteDirectory(dest); + } catch (IOException e) { + if (parentDir.exists()) { + throw e; + } + } + } + + @Test + public void deleteFolder() { + FileUtils.deleteFolder(parentDir); + assertFalse(parentDir.exists()); + assertFalse(parentDirFile.exists()); + assertFalse(childDir.exists()); + assertFalse(childDirFile.exists()); + } + + @Test + public void deleteFolderContents() { + FileUtils.deleteFolderContents(parentDir); + assertTrue(parentDir.exists()); + assertFalse(parentDirFile.exists()); + assertFalse(childDir.exists()); + assertFalse(childDirFile.exists()); + } + + @Test + public void copyFolder() { + File destFile = new File(dest, "parentDirFile.txt"); + File destChildDir = new File(dest, "childDir"); + File destChildDirFile = new File(destChildDir, "childDirFile.txt"); + assertFalse(destFile.exists()); + assertFalse(destChildDir.exists()); + assertFalse(destChildDirFile.exists()); + FileUtils.copyFolder(parentDir, dest, Logging.getLogger()); + } +} \ No newline at end of file From 4343167240d318292e981da19268c7d09f749deb Mon Sep 17 00:00:00 2001 From: BaronyCraft <47856220+BaronyCraft@users.noreply.github.com> Date: Fri, 15 Mar 2019 01:20:49 +0100 Subject: [PATCH 056/134] allow coord arguments to setspawn command (#1975) * allow coord arguments to setspawn command * Implement PR changes as requested --- .../commands/SetSpawnCommand.java | 118 ++++++++++++++---- 1 file changed, 93 insertions(+), 25 deletions(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/SetSpawnCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/SetSpawnCommand.java index ef39e043a..2c3c25a87 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/SetSpawnCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/SetSpawnCommand.java @@ -18,6 +18,7 @@ import org.bukkit.permissions.PermissionDefault; import java.util.List; +import org.bukkit.Bukkit; /** * Sets the spawn for a world. @@ -27,7 +28,7 @@ public SetSpawnCommand(MultiverseCore plugin) { super(plugin); this.setName("Set World Spawn"); this.setCommandUsage("/mv setspawn"); - this.setArgRange(0, 0); + this.setArgRange(0, 6); this.addKey("mvsetspawn"); this.addKey("mvss"); this.addKey("mv set spawn"); @@ -37,43 +38,110 @@ public SetSpawnCommand(MultiverseCore plugin) { this.setPermission("multiverse.core.spawn.set", "Sets the spawn for the current world.", PermissionDefault.OP); } + /** + * Dispatches the user's command depending on the number of parameters + * @param sender The player who executes the command, may be console as well. + * @param args Command line parameters + */ @Override public void runCommand(CommandSender sender, List args) { - setWorldSpawn(sender); + if (args.isEmpty()) { + setWorldSpawn(sender); + } else if (args.size() == 4) { + setWorldSpawn(sender, args.get(0), args.get(1), args.get(2), args.get(3)); + } else if (args.size() == 6) { + setWorldSpawn(sender, args.get(0), args.get(1), args.get(2), args.get(3), args.get(4), args.get(5)); + } else { + sender.sendMessage("Use no arguments for your current location, or world/x/y/z, or world/x/y/z/yaw/pitch!"); + } } /** - * Does the actual spawn-setting-work. - * - * @param sender The {@link CommandSender} that's setting the spawn. + * Set the world spawn when no parameters are given + * @param sender The {@link CommandSender} who executes the command. + * Everything not a {@link Player}, e.g. console, gets rejected, as we can't get coordinates from there. */ protected void setWorldSpawn(CommandSender sender) { if (sender instanceof Player) { Player p = (Player) sender; Location l = p.getLocation(); World w = p.getWorld(); - MultiverseWorld foundWorld = this.plugin.getMVWorldManager().getMVWorld(w.getName()); - if (foundWorld != null) { - foundWorld.setSpawnLocation(p.getLocation()); - BlockSafety bs = this.plugin.getBlockSafety(); - if (!bs.playerCanSpawnHereSafely(p.getLocation()) && foundWorld.getAdjustSpawn()) { - sender.sendMessage("It looks like that location would normally be unsafe. But I trust you."); - sender.sendMessage("I'm turning off the Safe-T-Teleporter for spawns to this world."); - sender.sendMessage("If you want this turned back on just do:"); - sender.sendMessage(ChatColor.AQUA + "/mvm set adjustspawn true " + foundWorld.getAlias()); - foundWorld.setAdjustSpawn(false); - } - sender.sendMessage("Spawn was set to: " + plugin.getLocationManipulation().strCoords(p.getLocation())); - if (!plugin.saveWorldConfig()) { - sender.sendMessage(ChatColor.RED + "There was an issue saving worlds.yml! Your changes will only be temporary!"); - } - } else { - w.setSpawnLocation(l.getBlockX(), l.getBlockY(), l.getBlockZ()); - sender.sendMessage("Multiverse does not know about this world, only X,Y and Z set. Please import it to set the spawn fully (Pitch/Yaws)."); - } + setWorldSpawn(sender, w, l); + } else { + sender.sendMessage("You need to give coordinates to use this command from the console!"); + } + } + + /** + * Set the world spawn when 4 parameters are given + * @param sender The {@link CommandSender} who executes the command + * @param world The world to set the spawn in + * @param x X-coordinate to set the spawn to (as a {@link String} as it's from the command line, gets parsed into a double) + * @param y Y-coordinate to set the spawn to (as a {@link String} as it's from the command line, gets parsed into a double) + * @param z Z-coordinate to set the spawn to (as a {@link String} as it's from the command line, gets parsed into a double) + */ + protected void setWorldSpawn(CommandSender sender, String world, String x, String y, String z) { + setWorldSpawn(sender, world, x, y, z, "0", "0"); + } + /** + * Set the world spawn when 6 parameters are given + * @param sender The {@link CommandSender} who executes the command + * @param world The world to set the spawn in + * @param x X-coordinate to set the spawn to (as a {@link String} as it's from the command line, gets parsed into a double) + * @param y Y-coordinate to set the spawn to (as a {@link String} as it's from the command line, gets parsed into a double) + * @param z Z-coordinate to set the spawn to (as a {@link String} as it's from the command line, gets parsed into a double) + * @param yaw Yaw a newly spawned player should look at (as a {@link String} as it's from the command line, gets parsed into a float) + * @param pitch Pitch a newly spawned player should look at (as a {@link String} as it's from the command line, gets parsed into a float) + */ + protected void setWorldSpawn(CommandSender sender, String world, String x, String y, String z, String yaw, String pitch) { + double dx, dy, dz; + float fpitch, fyaw; + World bukkitWorld = Bukkit.getWorld(world); + if (bukkitWorld == null) { + sender.sendMessage("World " + world + " is unknown!"); + return; + } + try { + dx = Double.parseDouble(x); + dy = Double.parseDouble(y); + dz = Double.parseDouble(z); + fpitch = Float.parseFloat(pitch); + fyaw = Float.parseFloat(yaw); + } catch (NumberFormatException ex) { + sender.sendMessage("All coordinates must be numeric"); + return; + } + Location l = new Location(bukkitWorld, dx, dy, dz, fyaw, fpitch); + setWorldSpawn(sender, bukkitWorld, l); + } + + /** + * Does the actual spawn-setting-work. + * + * @param sender The {@link CommandSender} that's setting the spawn. + * @param w The {@link World} to set the spawn in + * @param l The {@link Location} to set the spawn to + */ + private void setWorldSpawn(CommandSender sender, World w, Location l) { + MultiverseWorld foundWorld = this.plugin.getMVWorldManager().getMVWorld(w.getName()); + if (foundWorld != null) { + foundWorld.setSpawnLocation(l); + BlockSafety bs = this.plugin.getBlockSafety(); + if (!bs.playerCanSpawnHereSafely(l) && foundWorld.getAdjustSpawn()) { + sender.sendMessage("It looks like that location would normally be unsafe. But I trust you."); + sender.sendMessage("I'm turning off the Safe-T-Teleporter for spawns to this world."); + sender.sendMessage("If you want this turned back on just do:"); + sender.sendMessage(ChatColor.AQUA + "/mvm set adjustspawn true " + foundWorld.getAlias()); + foundWorld.setAdjustSpawn(false); + } + sender.sendMessage("Spawn was set to: " + plugin.getLocationManipulation().strCoords(l)); + if (!plugin.saveWorldConfig()) { + sender.sendMessage(ChatColor.RED + "There was an issue saving worlds.yml! Your changes will only be temporary!"); + } } else { - sender.sendMessage("You cannot use this command from the console."); + w.setSpawnLocation(l.getBlockX(), l.getBlockY(), l.getBlockZ()); + sender.sendMessage("Multiverse does not know about this world, only X,Y and Z set. Please import it to set the spawn fully (Pitch/Yaws)."); } } } From 06bd1a838f729283972c072230df987f71e6dcc2 Mon Sep 17 00:00:00 2001 From: Brokkonaut Date: Tue, 21 May 2019 19:15:14 +0200 Subject: [PATCH 057/134] Fix javadocs: it is now setCurrency(Material) instead of setCurrency(int) --- .../com/onarandombox/MultiverseCore/api/MultiverseWorld.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/api/MultiverseWorld.java b/src/main/java/com/onarandombox/MultiverseCore/api/MultiverseWorld.java index 1788cde8c..07ba347f3 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/api/MultiverseWorld.java +++ b/src/main/java/com/onarandombox/MultiverseCore/api/MultiverseWorld.java @@ -475,7 +475,7 @@ public interface MultiverseWorld { /** * Sets the price for entry to this world. * You can think of this like an amount. - * The type can be set with {@link #setCurrency(int)} + * The type can be set with {@link #setCurrency(Material)} * * @param price The Amount of money/item to enter the world. */ From 9737b62813ec8b004d092ff367a95440dfea9f86 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Tue, 4 Jun 2019 09:11:01 -0400 Subject: [PATCH 058/134] Bump version to 3.0.0 for release. --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 6a1ed1818..f6f497c91 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.onarandombox.multiversecore Multiverse-Core - 3.0.0-SNAPSHOT + 3.0.0 Multiverse-Core World Management Plugin From d4454703e4ce781e342cce4ec975106eec05f1af Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Tue, 4 Jun 2019 09:15:34 -0400 Subject: [PATCH 059/134] Bumped version to 4.0.0-SNAPSHOT for 1.14 updates. --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index f6f497c91..1bb5c40ef 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.onarandombox.multiversecore Multiverse-Core - 3.0.0 + 4.0.0-SNAPSHOT Multiverse-Core World Management Plugin From 253ede1c9a6ff42d9715ac7aa84299b141b804c8 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Tue, 4 Jun 2019 10:08:11 -0400 Subject: [PATCH 060/134] Wrap the travel agent in an adapter. --- .../listeners/MVPlayerListener.java | 20 +++- .../utils/BukkitTravelAgent.java | 110 ++++++++++++++++++ .../MultiverseCore/utils/MVTravelAgent.java | 105 +---------------- 3 files changed, 129 insertions(+), 106 deletions(-) create mode 100644 src/main/java/com/onarandombox/MultiverseCore/utils/BukkitTravelAgent.java diff --git a/src/main/java/com/onarandombox/MultiverseCore/listeners/MVPlayerListener.java b/src/main/java/com/onarandombox/MultiverseCore/listeners/MVPlayerListener.java index ad9356098..1bda64b87 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/listeners/MVPlayerListener.java +++ b/src/main/java/com/onarandombox/MultiverseCore/listeners/MVPlayerListener.java @@ -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; @@ -29,10 +33,6 @@ import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.event.player.PlayerTeleportEvent; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Level; - /** * Multiverse's {@link Listener} for players. */ @@ -304,8 +304,16 @@ public void playerPortal(PlayerPortalEvent event) { + "' was allowed to go to '" + event.getTo().getWorld().getName() + "' because enforceaccess is off."); } - if (!plugin.getMVConfig().isUsingDefaultPortalSearch() && event.getPortalTravelAgent() != null) { - event.getPortalTravelAgent().setSearchRadius(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) { + plugin.log(Level.WARNING, "TravelAgent not available for PlayerPortalEvent for " + event.getPlayer().getName()); + } + } } diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/BukkitTravelAgent.java b/src/main/java/com/onarandombox/MultiverseCore/utils/BukkitTravelAgent.java new file mode 100644 index 000000000..fd68d2ea4 --- /dev/null +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/BukkitTravelAgent.java @@ -0,0 +1,110 @@ +package com.onarandombox.MultiverseCore.utils; + +import java.util.logging.Level; + +import com.onarandombox.MultiverseCore.api.SafeTTeleporter; +import com.onarandombox.MultiverseCore.destination.CannonDestination; +import org.bukkit.Location; +import org.bukkit.TravelAgent; +import org.bukkit.event.player.PlayerPortalEvent; + +public class BukkitTravelAgent implements TravelAgent { + private final MVTravelAgent agent; + + public BukkitTravelAgent(MVTravelAgent agent) { + this.agent = agent; + } + + /** + * {@inheritDoc} + */ + @Override + public BukkitTravelAgent setSearchRadius(int radius) { + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public int getSearchRadius() { + return 0; + } + + /** + * {@inheritDoc} + */ + @Override + public BukkitTravelAgent setCreationRadius(int radius) { + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public int getCreationRadius() { + return 0; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean getCanCreatePortal() { + return false; + } + + /** + * {@inheritDoc} + */ + @Override + public void setCanCreatePortal(boolean create) { + } + + /** + * {@inheritDoc} + */ + @Override + public Location findOrCreate(Location location) { + return this.getSafeLocation(); + } + + /** + * {@inheritDoc} + */ + @Override + public Location findPortal(Location location) { + return this.getSafeLocation(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean createPortal(Location location) { + return false; + } + + private Location getSafeLocation() { + // At this time, these can never use the velocity. + if (agent.destination instanceof CannonDestination) { + agent.core.log(Level.FINE, "Using Stock TP method. This cannon will have 0 velocity"); + } + SafeTTeleporter teleporter = agent.core.getSafeTTeleporter(); + Location newLoc = agent.destination.getLocation(agent.player); + if (agent.destination.useSafeTeleporter()) { + newLoc = teleporter.getSafeLocation(agent.player, agent.destination); + } + if (newLoc == null) { + return agent.player.getLocation(); + } + return newLoc; + + } + + public void setPortalEventTravelAgent(PlayerPortalEvent event) { + event.setPortalTravelAgent(this); + event.useTravelAgent(true); + } +} diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/MVTravelAgent.java b/src/main/java/com/onarandombox/MultiverseCore/utils/MVTravelAgent.java index 0f3ada975..a86def8a5 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/MVTravelAgent.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/MVTravelAgent.java @@ -9,114 +9,19 @@ import com.onarandombox.MultiverseCore.MultiverseCore; import com.onarandombox.MultiverseCore.api.MVDestination; -import com.onarandombox.MultiverseCore.api.SafeTTeleporter; -import com.onarandombox.MultiverseCore.destination.CannonDestination; -import org.bukkit.Location; -import org.bukkit.TravelAgent; import org.bukkit.entity.Player; -import java.util.logging.Level; - /** - * The Multiverse-{@link TravelAgent}. + * The Multiverse TravelAgent. */ -public class MVTravelAgent implements TravelAgent { - private MVDestination destination; - private MultiverseCore core; - private Player player; +public class MVTravelAgent { + protected MVDestination destination; + protected MultiverseCore core; + protected Player player; public MVTravelAgent(MultiverseCore multiverseCore, MVDestination d, Player p) { this.destination = d; this.core = multiverseCore; this.player = p; } - - /** - * {@inheritDoc} - */ - @Override - public TravelAgent setSearchRadius(int radius) { - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public int getSearchRadius() { - return 0; - } - - /** - * {@inheritDoc} - */ - @Override - public TravelAgent setCreationRadius(int radius) { - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public int getCreationRadius() { - return 0; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean getCanCreatePortal() { - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public void setCanCreatePortal(boolean create) { - } - - /** - * {@inheritDoc} - */ - @Override - public Location findOrCreate(Location location) { - return this.getSafeLocation(); - } - - /** - * {@inheritDoc} - */ - @Override - public Location findPortal(Location location) { - return this.getSafeLocation(); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean createPortal(Location location) { - return false; - } - - private Location getSafeLocation() { - // At this time, these can never use the velocity. - if (this.destination instanceof CannonDestination) { - this.core.log(Level.FINE, "Using Stock TP method. This cannon will have 0 velocity"); - } - SafeTTeleporter teleporter = this.core.getSafeTTeleporter(); - Location newLoc = this.destination.getLocation(this.player); - if (this.destination.useSafeTeleporter()) { - newLoc = teleporter.getSafeLocation(this.player, this.destination); - } - if (newLoc == null) { - return this.player.getLocation(); - } - return newLoc; - - } - } From 20a1fcb9f50c888d2e97fe45e76dfc24dc92dacd Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Tue, 4 Jun 2019 10:08:35 -0400 Subject: [PATCH 061/134] Bump protocol version to 23. --- .../MultiverseCore/MultiverseCore.java | 31 +++++++++++-------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java index f5ac4d11c..3a1d8c177 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java @@ -7,6 +7,23 @@ package com.onarandombox.MultiverseCore; +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.logging.Level; + import buscript.Buscript; import com.dumptruckman.minecraft.util.Logging; import com.onarandombox.MultiverseCore.MVWorld.NullLocation; @@ -106,23 +123,11 @@ import org.bukkit.plugin.java.JavaPluginLoader; import org.mcstats.Metrics; -import java.io.*; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.logging.Level; - /** * The implementation of the Multiverse-{@link Core}. */ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core { - private static final int PROTOCOL = 22; + private static final int PROTOCOL = 23; // TODO: Investigate if this one is really needed to be static. // Doubt it. -- FernFerret private static Map teleportQueue = new HashMap(); From c3f08318d405bfe0524def0181429fb637cce1c5 Mon Sep 17 00:00:00 2001 From: Brokkonaut Date: Mon, 17 Jun 2019 05:48:02 +0200 Subject: [PATCH 062/134] Phantoms are monsters --- .../onarandombox/MultiverseCore/utils/SimpleWorldPurger.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/SimpleWorldPurger.java b/src/main/java/com/onarandombox/MultiverseCore/utils/SimpleWorldPurger.java index 9c3456c7b..bfaa4df99 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/SimpleWorldPurger.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/SimpleWorldPurger.java @@ -20,6 +20,7 @@ import org.bukkit.entity.Golem; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Monster; +import org.bukkit.entity.Phantom; import org.bukkit.entity.Projectile; import org.bukkit.entity.Slime; import org.bukkit.entity.Squid; @@ -148,7 +149,7 @@ private boolean killDecision(Entity e, List thingsToKill, boolean negate if (specifiedAnimals) specified = true; negate = negateAnimals; - } else if (e instanceof Monster || e instanceof Ghast || e instanceof Slime) { + } else if (e instanceof Monster || e instanceof Ghast || e instanceof Slime || e instanceof Phantom) { // it's a monster if (specifiedMonsters && !negateMonsters) { Logging.finest("Removing an entity because I was told to remove all monsters in world %s: %s", e.getWorld().getName(), e); From 950402a144539462557b75cc317eaf74e438ef34 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Tue, 25 Jun 2019 13:33:20 -0400 Subject: [PATCH 063/134] Release version 4.0.0. --- pom.xml | 2 +- .../java/com/onarandombox/MultiverseCore/MultiverseCore.java | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 1bb5c40ef..49b5be7e7 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.onarandombox.multiversecore Multiverse-Core - 4.0.0-SNAPSHOT + 4.0.0 Multiverse-Core World Management Plugin diff --git a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java index 3a1d8c177..0dcd1da1d 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java @@ -344,6 +344,9 @@ public void onEnable() { // Output a little snippet to show it's enabled. Logging.config("Version %s (API v%s) Enabled - By %s", this.getDescription().getVersion(), PROTOCOL, getAuthors()); + + getLogger().info("Help dumptruckman keep this project alive. Become a patron! https://www.patreon.com/dumptruckman"); + getLogger().info("One time donations are also appreciated: https://www.paypal.me/dumptruckman"); } /** From 32e72bb355159f6453fa298e5f062f553572c300 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Tue, 25 Jun 2019 13:34:08 -0400 Subject: [PATCH 064/134] Bump version to 4.0.1 for continued development. --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 49b5be7e7..ad6186e66 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.onarandombox.multiversecore Multiverse-Core - 4.0.0 + 4.0.1-SNAPSHOT Multiverse-Core World Management Plugin From 7cb9bd4bc2274e22823d047935d73e494b3cac12 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Tue, 23 Jul 2019 21:46:23 -0400 Subject: [PATCH 065/134] Added message acknowledging deprecated event. --- .../java/com/onarandombox/MultiverseCore/MultiverseCore.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java index 0dcd1da1d..2623416aa 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java @@ -470,6 +470,7 @@ private void registerEvents() { pm.registerEvents(this.entityListener, this); pm.registerEvents(this.weatherListener, this); pm.registerEvents(this.portalListener, this); + log(Level.INFO, "We are aware of the warning about the deprecated event. There is no alternative that allows us to do what we need to do. The performance impact is negligible."); pm.registerEvents(this.worldListener, this); pm.registerEvents(new MVMapListener(this), this); } From 1581e1e009142546b4ea1f824eb3eb524be7df80 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Tue, 23 Jul 2019 21:47:13 -0400 Subject: [PATCH 066/134] Make TravelAgent warning message a debug message. --- .../onarandombox/MultiverseCore/listeners/MVPlayerListener.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/listeners/MVPlayerListener.java b/src/main/java/com/onarandombox/MultiverseCore/listeners/MVPlayerListener.java index 1bda64b87..40c1f51b1 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/listeners/MVPlayerListener.java +++ b/src/main/java/com/onarandombox/MultiverseCore/listeners/MVPlayerListener.java @@ -311,7 +311,7 @@ public void playerPortal(PlayerPortalEvent event) { event.getPortalTravelAgent().setSearchRadius(plugin.getMVConfig().getPortalSearchRadius()); } } catch (ClassNotFoundException ignore) { - plugin.log(Level.WARNING, "TravelAgent not available for PlayerPortalEvent for " + event.getPlayer().getName()); + plugin.log(Level.FINE, "TravelAgent not available for PlayerPortalEvent for " + event.getPlayer().getName()); } } From f595f4cdb9ff23a4b534248f47aad181a8664876 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Tue, 23 Jul 2019 21:47:40 -0400 Subject: [PATCH 067/134] Release version 4.0.1. --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index ad6186e66..b90746aee 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.onarandombox.multiversecore Multiverse-Core - 4.0.1-SNAPSHOT + 4.0.1 Multiverse-Core World Management Plugin From 4de6b9ce4709ee7a75e1476b1144e4fc0a5156df Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Tue, 30 Jul 2019 21:50:37 -0400 Subject: [PATCH 068/134] Bumped version to 4.0.2-SNAPSHOT for continued development. --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index b90746aee..c53118bfd 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.onarandombox.multiversecore Multiverse-Core - 4.0.1 + 4.0.2-SNAPSHOT Multiverse-Core World Management Plugin From 8859fa78fdffce10ea09aa057baff3d8b9cbbea2 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Tue, 30 Jul 2019 22:09:14 -0400 Subject: [PATCH 069/134] Bumped core protocol to 24. --- .../java/com/onarandombox/MultiverseCore/MultiverseCore.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java index 2623416aa..a25cc27dc 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java @@ -127,7 +127,7 @@ * The implementation of the Multiverse-{@link Core}. */ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core { - private static final int PROTOCOL = 23; + private static final int PROTOCOL = 24; // TODO: Investigate if this one is really needed to be static. // Doubt it. -- FernFerret private static Map teleportQueue = new HashMap(); From da6bd20b42303a9f8c84ae0f30a3f8faee3f0d2f Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Tue, 30 Jul 2019 22:10:48 -0400 Subject: [PATCH 070/134] Bumped version to 4.1.0-SNAPSHOT for incoming features. --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index c53118bfd..72749e21e 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.onarandombox.multiversecore Multiverse-Core - 4.0.2-SNAPSHOT + 4.1.0-SNAPSHOT Multiverse-Core World Management Plugin From 38d591791546341d25c77d30fe110f12e7e63e8e Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Tue, 30 Jul 2019 23:03:51 -0400 Subject: [PATCH 071/134] Added debug mode change event. --- .../MultiverseCore/MultiverseCore.java | 8 +++- .../MultiverseCoreConfiguration.java | 3 ++ .../event/MVDebugModeEvent.java | 43 +++++++++++++++++++ 3 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/onarandombox/MultiverseCore/event/MVDebugModeEvent.java diff --git a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java index a25cc27dc..3b3bcd7d2 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java @@ -78,6 +78,7 @@ import com.onarandombox.MultiverseCore.destination.ExactDestination; import com.onarandombox.MultiverseCore.destination.PlayerDestination; import com.onarandombox.MultiverseCore.destination.WorldDestination; +import com.onarandombox.MultiverseCore.event.MVDebugModeEvent; import com.onarandombox.MultiverseCore.event.MVVersionEvent; import com.onarandombox.MultiverseCore.listeners.MVAsyncPlayerChatListener; import com.onarandombox.MultiverseCore.listeners.MVChatListener; @@ -309,7 +310,6 @@ public void onEnable() { // Setup & Load our Configuration files. loadConfigs(); if (this.multiverseConfig != null) { - Logging.setDebugLevel(getMVConfig().getGlobalDebug()); Logging.setShowingConfig(!getMVConfig().getSilentStart()); this.worldManager.loadDefaultWorlds(); this.worldManager.loadWorlds(true); @@ -518,6 +518,12 @@ public void loadConfigs() { // Old Config Format this.migrate22Values(); this.saveMVConfigs(); + + int level = Logging.getDebugLevel(); + Logging.setDebugLevel(getMVConfig().getGlobalDebug()); + if (level != Logging.getDebugLevel()) { + getServer().getPluginManager().callEvent(new MVDebugModeEvent(level)); + } } /** diff --git a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCoreConfiguration.java b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCoreConfiguration.java index 65142f814..1f295dbb9 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCoreConfiguration.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCoreConfiguration.java @@ -2,7 +2,9 @@ import com.dumptruckman.minecraft.util.*; import com.onarandombox.MultiverseCore.api.*; +import com.onarandombox.MultiverseCore.event.MVDebugModeEvent; import me.main__.util.SerializationConfig.*; +import org.bukkit.Bukkit; import java.util.*; @@ -229,6 +231,7 @@ public int getGlobalDebug() { public void setGlobalDebug(int globalDebug) { this.globaldebug = globalDebug; Logging.setDebugLevel(globalDebug); + Bukkit.getPluginManager().callEvent(new MVDebugModeEvent(globalDebug)); } /** diff --git a/src/main/java/com/onarandombox/MultiverseCore/event/MVDebugModeEvent.java b/src/main/java/com/onarandombox/MultiverseCore/event/MVDebugModeEvent.java new file mode 100644 index 000000000..f3c3408b7 --- /dev/null +++ b/src/main/java/com/onarandombox/MultiverseCore/event/MVDebugModeEvent.java @@ -0,0 +1,43 @@ +package com.onarandombox.MultiverseCore.event; + +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +/** + * Called when Core's debug level is changed. + */ +public class MVDebugModeEvent extends Event { + + private static final HandlerList HANDLERS = new HandlerList(); + + private final int level; + + public MVDebugModeEvent(int level) { + this.level = level; + } + + /** + * {@inheritDoc} + */ + @Override + public HandlerList getHandlers() { + return HANDLERS; + } + + /** + * Gets the handler list. This is required by the event system. + * @return A list of HANDLERS. + */ + public static HandlerList getHandlerList() { + return HANDLERS; + } + + /** + * Returns the current debug level of Core. + * + * @return the current debug level of Core. + */ + public int getLevel() { + return level; + } +} From 540b6abcabad1a48c3c90bc0202ae8328bb2dcb0 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Tue, 30 Jul 2019 23:48:32 -0400 Subject: [PATCH 072/134] Now using CommandHandler 11! --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 72749e21e..7ea2849d5 100644 --- a/pom.xml +++ b/pom.xml @@ -275,7 +275,7 @@ com.pneumaticraft.commandhandler CommandHandler - 10 + 11 com.dumptruckman.minecraft From 841598232c2e0c6f7fee45c3b6ae1b03d7095818 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Wed, 31 Jul 2019 00:25:34 -0400 Subject: [PATCH 073/134] Added --include-plugin-list to mv version command. --- .../commands/VersionCommand.java | 30 ++++++++++++++----- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java index 95013ca51..b2ac51e40 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java @@ -16,12 +16,15 @@ import com.onarandombox.MultiverseCore.utils.webpaste.PasteServiceFactory; import com.onarandombox.MultiverseCore.utils.webpaste.PasteServiceType; import com.onarandombox.MultiverseCore.utils.webpaste.URLShortener; +import com.pneumaticraft.commandhandler.CommandHandler; +import org.apache.commons.lang.StringUtils; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; import org.bukkit.permissions.PermissionDefault; import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.StringUtil; import java.io.*; import java.util.HashMap; @@ -37,8 +40,8 @@ public class VersionCommand extends MultiverseCommand { public VersionCommand(MultiverseCore plugin) { super(plugin); this.setName("Multiverse Version"); - this.setCommandUsage("/mv version " + ChatColor.GOLD + "-[bh]"); - this.setArgRange(0, 1); + this.setCommandUsage("/mv version " + ChatColor.GOLD + "-[bh] [--include-plugin-list]"); + this.setArgRange(0, 2); this.addKey("mv version"); this.addKey("mvv"); this.addKey("mvversion"); @@ -149,22 +152,31 @@ public void runCommand(final CommandSender sender, final List args) { final Map files = this.getVersionFiles(); this.plugin.getServer().getPluginManager().callEvent(versionEvent); + String versionInfo = versionEvent.getVersionInfo(); + + if (CommandHandler.hasFlag("--include-plugin-list", args)) { + versionInfo = versionInfo + "\nPlugins: " + getPluginList(); + } + + final String data = versionInfo; + // log to console - final String data = versionEvent.getVersionInfo(); String[] lines = data.split("\n"); for (String line : lines) { - Logging.info(line); + if (!line.isEmpty()) { + Logging.info(line); + } } BukkitRunnable logPoster = new BukkitRunnable() { @Override public void run() { - if (args.size() == 1) { + if (args.size() > 0) { String pasteUrl; - if (args.get(0).equalsIgnoreCase("-b")) { + if (CommandHandler.hasFlag("-b", args)) { // private post to pastebin pasteUrl = postToService(PasteServiceType.PASTEBIN, true, data, files); - } else if (args.get(0).equalsIgnoreCase("-h")) { + } else if (CommandHandler.hasFlag("-h", args)) { // private post to pastebin pasteUrl = postToService(PasteServiceType.HASTEBIN, true, data, files); } else { @@ -208,4 +220,8 @@ private static String postToService(PasteServiceType type, boolean isPrivate, St return "Error posting to service"; } } + + private String getPluginList() { + return StringUtils.join(plugin.getServer().getPluginManager().getPlugins(), ", "); + } } From 926e23bf19fd74542fb7ce671fd781e330d8ba5f Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Fri, 2 Aug 2019 21:49:11 -0400 Subject: [PATCH 074/134] Removed super dated toString in plugin main class. --- .../java/com/onarandombox/MultiverseCore/MultiverseCore.java | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java index 3b3bcd7d2..c1b53f658 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java @@ -177,11 +177,6 @@ public static void addPlayerToTeleportQueue(String teleporter, String teleportee teleportQueue.put(teleportee, teleporter); } - @Override - public String toString() { - return "The Multiverse-Core Plugin"; - } - /** * {@inheritDoc} * @deprecated This is now deprecated, nobody needs it any longer. From 5e2824abebaa1f9807e629da8af7dd92ef4d1745 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Thu, 15 Aug 2019 21:15:45 -0400 Subject: [PATCH 075/134] Prevent importing worlds without .dat file. Fixes #1917. --- .../commands/DeleteCommand.java | 8 ++++-- .../commands/ImportCommand.java | 26 +++++++++++-------- .../MultiverseCore/TestWorldProperties.java | 3 +++ .../MultiverseCore/TestWorldStuff.java | 8 ++++++ .../utils/MockWorldFactory.java | 13 +++++++++- 5 files changed, 44 insertions(+), 14 deletions(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/DeleteCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/DeleteCommand.java index a37bcd116..2e7b3c8b0 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/DeleteCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/DeleteCommand.java @@ -33,9 +33,13 @@ public DeleteCommand(MultiverseCore plugin) { @Override public void runCommand(CommandSender sender, List args) { + String worldName = args.get(0); + Class[] paramTypes = {String.class}; List objectArgs = new ArrayList(args); - this.plugin.getCommandHandler().queueCommand(sender, "mvdelete", "deleteWorld", objectArgs, - paramTypes, ChatColor.GREEN + "World Deleted!", ChatColor.RED + "World could NOT be deleted!"); + this.plugin.getCommandHandler() + .queueCommand(sender, "mvdelete", "deleteWorld", objectArgs, + paramTypes, ChatColor.GREEN + "World '" + worldName + "' Deleted!", + ChatColor.RED + "World '" + worldName + "' could NOT be deleted!"); } } diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/ImportCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/ImportCommand.java index be81297b8..b16bf2398 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/ImportCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/ImportCommand.java @@ -57,7 +57,7 @@ private static boolean checkIfIsWorld(File worldFolder) { File[] files = worldFolder.listFiles(new FilenameFilter() { @Override public boolean accept(File file, String name) { - return name.equalsIgnoreCase("level.dat"); + return name.toLowerCase().endsWith(".dat"); } }); if (files != null && files.length > 0) { @@ -147,21 +147,25 @@ public void runCommand(CommandSender sender, List args) { return; } - if (worldFile.exists() && env != null) { - Command.broadcastCommandMessage(sender, String.format("Starting import of world '%s'...", worldName)); - if (this.worldManager.addWorld(worldName, environment, null, null, null, generator, useSpawnAdjust)) - Command.broadcastCommandMessage(sender, ChatColor.GREEN + "Complete!"); - else - Command.broadcastCommandMessage(sender, ChatColor.RED + "Failed!"); + if (!worldFile.exists()) { + sender.sendMessage(ChatColor.RED + "FAILED."); + String worldList = this.getPotentialWorlds(); + sender.sendMessage("That world folder does not exist. These look like worlds to me:"); + sender.sendMessage(worldList); + } else if (!checkIfIsWorld(worldFile)) { + sender.sendMessage(ChatColor.RED + "FAILED."); + sender.sendMessage(String.format("'%s' does not appear to be a world. It is lacking a .dat file.", + worldName)); } else if (env == null) { sender.sendMessage(ChatColor.RED + "FAILED."); sender.sendMessage("That world environment did not exist."); sender.sendMessage("For a list of available world types, type: " + ChatColor.AQUA + "/mvenv"); } else { - sender.sendMessage(ChatColor.RED + "FAILED."); - String worldList = this.getPotentialWorlds(); - sender.sendMessage("That world folder does not exist. These look like worlds to me:"); - sender.sendMessage(worldList); + Command.broadcastCommandMessage(sender, String.format("Starting import of world '%s'...", worldName)); + if (this.worldManager.addWorld(worldName, environment, null, null, null, generator, useSpawnAdjust)) + Command.broadcastCommandMessage(sender, ChatColor.GREEN + "Complete!"); + else + Command.broadcastCommandMessage(sender, ChatColor.RED + "Failed!"); } } } diff --git a/src/test/java/com/onarandombox/MultiverseCore/TestWorldProperties.java b/src/test/java/com/onarandombox/MultiverseCore/TestWorldProperties.java index 4d61bebbb..c415b3dbb 100644 --- a/src/test/java/com/onarandombox/MultiverseCore/TestWorldProperties.java +++ b/src/test/java/com/onarandombox/MultiverseCore/TestWorldProperties.java @@ -11,6 +11,7 @@ import com.onarandombox.MultiverseCore.api.MultiverseWorld; 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; @@ -90,6 +91,8 @@ public void setUp() throws Exception { assertTrue(creator.setUp()); core = creator.getCore(); mockCommandSender = creator.getCommandSender(); + MockWorldFactory.createWorldDirectory("world"); + MockWorldFactory.createWorldDirectory("world_nether"); } @After diff --git a/src/test/java/com/onarandombox/MultiverseCore/TestWorldStuff.java b/src/test/java/com/onarandombox/MultiverseCore/TestWorldStuff.java index 3920199e2..05957c842 100644 --- a/src/test/java/com/onarandombox/MultiverseCore/TestWorldStuff.java +++ b/src/test/java/com/onarandombox/MultiverseCore/TestWorldStuff.java @@ -9,6 +9,7 @@ import com.onarandombox.MultiverseCore.api.MultiverseWorld; 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; @@ -99,6 +100,10 @@ public void testWorldImportWithNoFolder() { @Test public void testWorldImport() { + MockWorldFactory.createWorldDirectory("world"); + MockWorldFactory.createWorldDirectory("world_nether"); + MockWorldFactory.createWorldDirectory("world_the_end"); + // Pull a core instance from the server. Plugin plugin = mockServer.getPluginManager().getPlugin("Multiverse-Core"); @@ -282,6 +287,9 @@ public void testModifyGameMode() { } private void createInitialWorlds(Plugin plugin, Command command) { + MockWorldFactory.createWorldDirectory("world"); + MockWorldFactory.createWorldDirectory("world_nether"); + MockWorldFactory.createWorldDirectory("world_the_end"); plugin.onCommand(mockCommandSender, command, "", new String[]{ "import", "world", "normal" }); plugin.onCommand(mockCommandSender, command, "", new String[]{ "import", "world_nether", "nether" }); plugin.onCommand(mockCommandSender, command, "", new String[]{ "import", "world_the_end", "end" }); diff --git a/src/test/java/com/onarandombox/MultiverseCore/utils/MockWorldFactory.java b/src/test/java/com/onarandombox/MultiverseCore/utils/MockWorldFactory.java index 79827c62f..7f470fe5b 100644 --- a/src/test/java/com/onarandombox/MultiverseCore/utils/MockWorldFactory.java +++ b/src/test/java/com/onarandombox/MultiverseCore/utils/MockWorldFactory.java @@ -18,6 +18,7 @@ import org.mockito.stubbing.Answer; import java.io.File; +import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -43,7 +44,17 @@ private MockWorldFactory() { private static void registerWorld(World world) { createdWorlds.put(world.getName(), world); worldUIDS.put(world.getUID(), world); - new File(TestInstanceCreator.worldsDirectory, world.getName()).mkdir(); + createWorldDirectory(world.getName()); + } + + public static void createWorldDirectory(String worldName) { + File worldFolder = new File(TestInstanceCreator.worldsDirectory, worldName); + worldFolder.mkdir(); + try { + new File(worldFolder, "level.dat").createNewFile(); + } catch (IOException e) { + throw new RuntimeException(e); + } } private static World basics(String world, World.Environment env, WorldType type) { From d3ff2922fd5ecfacc37bff9efaf18b9ab72cd97d Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Fri, 23 Aug 2019 15:27:45 -0400 Subject: [PATCH 076/134] World cloning should work once again! Resolves #1978. --- .../MultiverseCore/utils/FileUtils.java | 52 +++++-- .../MultiverseCore/utils/FileUtilsTest.java | 138 +++++++++++------- 2 files changed, 126 insertions(+), 64 deletions(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/FileUtils.java b/src/main/java/com/onarandombox/MultiverseCore/utils/FileUtils.java index 18a39d577..ce7933067 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/FileUtils.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/FileUtils.java @@ -7,16 +7,22 @@ package com.onarandombox.MultiverseCore.utils; -import com.dumptruckman.minecraft.util.Logging; +import static java.nio.file.StandardCopyOption.COPY_ATTRIBUTES; import java.io.File; import java.io.IOException; +import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; import java.util.Comparator; +import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Stream; +import com.dumptruckman.minecraft.util.Logging; + /** * File-utilities. */ @@ -69,20 +75,42 @@ public static boolean deleteFolderContents(File file) { * @return if it had success */ public static boolean copyFolder(File source, File target, Logger log) { - Path sourcePath = source.toPath(); - Path destPath = target.toPath(); - try (Stream files = Files.walk(source.toPath())) { - files.forEachOrdered(src -> { - try { - Files.copy(src, sourcePath.resolve(destPath.relativize(src))); - } catch (IOException e) { - log.warning(e.getMessage()); - } - }); + Path sourceDir = source.toPath(); + Path targetDir = target.toPath(); + + try { + Files.walkFileTree(sourceDir, new CopyDirFileVisitor(sourceDir, targetDir)); return true; } catch (IOException e) { - log.warning(e.getMessage()); + log.log(Level.WARNING, "Unable to copy directory", e); return false; } } + + private static class CopyDirFileVisitor extends SimpleFileVisitor { + + private final Path sourceDir; + private final Path targetDir; + + private CopyDirFileVisitor(Path sourceDir, Path targetDir) { + this.sourceDir = sourceDir; + this.targetDir = targetDir; + } + + @Override + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { + Path newDir = targetDir.resolve(sourceDir.relativize(dir)); + if (!Files.isDirectory(newDir)) { + Files.createDirectory(newDir); + } + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + Path targetFile = targetDir.resolve(sourceDir.relativize(file)); + Files.copy(file, targetFile, COPY_ATTRIBUTES); + return FileVisitResult.CONTINUE; + } + } } diff --git a/src/test/java/com/onarandombox/MultiverseCore/utils/FileUtilsTest.java b/src/test/java/com/onarandombox/MultiverseCore/utils/FileUtilsTest.java index b32de6556..0b5da6f02 100644 --- a/src/test/java/com/onarandombox/MultiverseCore/utils/FileUtilsTest.java +++ b/src/test/java/com/onarandombox/MultiverseCore/utils/FileUtilsTest.java @@ -1,54 +1,48 @@ package com.onarandombox.MultiverseCore.utils; -import com.dumptruckman.minecraft.util.Logging; -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.File; import java.io.IOException; import java.nio.file.Files; +import java.nio.file.Path; -import static org.junit.Assert.*; +import com.dumptruckman.minecraft.util.Logging; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; public class FileUtilsTest { - private File parentDir; - private File parentDirFile; - private File childDir; - private File childDirFile; - private File dest; + private Path tempDir; + private Path parentDir; + private Path parentDirFile; + private Path childDir; + private Path childDirFile; + @Before public void setUp() throws Exception { - parentDir = Files.createTempDirectory("parentDir").toFile(); - parentDirFile = new File(parentDir, "parentDirFile.txt"); - parentDirFile.createNewFile(); - childDir = Files.createTempDirectory(parentDir.toPath(), "childDir").toFile(); - childDirFile = new File(childDir, "childDirFile.txt"); - childDirFile.createNewFile(); - dest = Files.createTempDirectory("dest").toFile(); - - assertTrue(parentDir.exists()); - assertTrue(parentDirFile.exists()); - assertTrue(childDir.exists()); - assertTrue(childDirFile.exists()); - assertTrue(dest.exists()); + tempDir = Files.createTempDirectory("testingTempDir"); + + parentDir = Files.createDirectory(tempDir.resolve("parentDir")); + parentDirFile = Files.createFile(parentDir.resolve("parentDirFile.txt")); + + childDir = Files.createDirectory(parentDir.resolve("childDir")); + childDirFile = Files.createFile(childDir.resolve("childDirFile.txt")); + + assertTrue(Files.isDirectory(parentDir)); + assertTrue(Files.isRegularFile(parentDirFile)); + assertTrue(Files.isDirectory(childDir)); + assertTrue(Files.isRegularFile(childDirFile)); } @After public void tearDown() throws Exception { try { - org.apache.commons.io.FileUtils.deleteDirectory(parentDir); - } catch (IOException e) { - if (parentDir.exists()) { - throw e; - } - } - try { - org.apache.commons.io.FileUtils.deleteDirectory(dest); + org.apache.commons.io.FileUtils.deleteDirectory(tempDir.toFile()); } catch (IOException e) { - if (parentDir.exists()) { + if (Files.exists(tempDir)) { throw e; } } @@ -56,30 +50,70 @@ public void tearDown() throws Exception { @Test public void deleteFolder() { - FileUtils.deleteFolder(parentDir); - assertFalse(parentDir.exists()); - assertFalse(parentDirFile.exists()); - assertFalse(childDir.exists()); - assertFalse(childDirFile.exists()); + FileUtils.deleteFolder(parentDir.toFile()); + assertFalse(Files.isDirectory(parentDir)); + assertFalse(Files.isRegularFile(parentDirFile)); + assertFalse(Files.isDirectory(childDir)); + assertFalse(Files.isRegularFile(childDirFile)); } @Test public void deleteFolderContents() { - FileUtils.deleteFolderContents(parentDir); - assertTrue(parentDir.exists()); - assertFalse(parentDirFile.exists()); - assertFalse(childDir.exists()); - assertFalse(childDirFile.exists()); + FileUtils.deleteFolderContents(parentDir.toFile()); + assertTrue(Files.isDirectory(parentDir)); + assertFalse(Files.isRegularFile(parentDirFile)); + assertFalse(Files.isDirectory(childDir)); + assertFalse(Files.isRegularFile(childDirFile)); + } + + @Test + public void copyFolder() throws Exception { + Path targetDir = tempDir.resolve("target"); + Path targetFile = targetDir.resolve("parentDirFile.txt"); + Path targetChildDir = targetDir.resolve("childDir"); + Path targetChildDirFile = targetChildDir.resolve("childDirFile.txt"); + + assertFalse(Files.isDirectory(targetDir)); + assertFalse(Files.isRegularFile(targetFile)); + assertFalse(Files.isDirectory(targetChildDir)); + assertFalse(Files.isRegularFile(targetChildDirFile)); + + assertTrue(FileUtils.copyFolder(parentDir.toFile(), targetDir.toFile(), Logging.getLogger())); + + assertTrue(Files.isDirectory(targetDir)); + assertTrue(Files.isRegularFile(targetFile)); + assertTrue(Files.isDirectory(targetChildDir)); + assertTrue(Files.isRegularFile(targetChildDirFile)); } @Test - public void copyFolder() { - File destFile = new File(dest, "parentDirFile.txt"); - File destChildDir = new File(dest, "childDir"); - File destChildDirFile = new File(destChildDir, "childDirFile.txt"); - assertFalse(destFile.exists()); - assertFalse(destChildDir.exists()); - assertFalse(destChildDirFile.exists()); - FileUtils.copyFolder(parentDir, dest, Logging.getLogger()); + public void copyFolder_intoExistingFolder() throws Exception { + Path targetDir = Files.createDirectory(tempDir.resolve("target")); + Path targetFile = targetDir.resolve("parentDirFile.txt"); + Path targetChildDir = targetDir.resolve("childDir"); + Path targetChildDirFile = targetChildDir.resolve("childDirFile.txt"); + + assertTrue(Files.isDirectory(targetDir)); + assertFalse(Files.isRegularFile(targetFile)); + assertFalse(Files.isDirectory(targetChildDir)); + assertFalse(Files.isRegularFile(targetChildDirFile)); + + assertTrue(FileUtils.copyFolder(parentDir.toFile(), targetDir.toFile(), Logging.getLogger())); + + assertTrue(Files.isDirectory(targetDir)); + assertTrue(Files.isRegularFile(targetFile)); + assertTrue(Files.isDirectory(targetChildDir)); + assertTrue(Files.isRegularFile(targetChildDirFile)); + } + + @Test() + public void copyFolder_intoExistingFolder_whereFileExists() throws Exception { + Path targetDir = Files.createDirectory(tempDir.resolve("target")); + Path targetFile = Files.createFile(targetDir.resolve("parentDirFile.txt")); + + assertTrue(Files.isDirectory(targetDir)); + assertTrue(Files.isRegularFile(targetFile)); + + assertFalse(FileUtils.copyFolder(parentDir.toFile(), targetDir.toFile(), Logging.getLogger())); } -} \ No newline at end of file +} From 6ee0d8a05ec31dd89f14de2b4cfeb4de867c43d6 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Fri, 23 Aug 2019 15:28:06 -0400 Subject: [PATCH 077/134] Release version 4.1.0. --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 7ea2849d5..a3f3da3e6 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.onarandombox.multiversecore Multiverse-Core - 4.1.0-SNAPSHOT + 4.1.0 Multiverse-Core World Management Plugin From 1ba693ffd5fee0528dc2cf10bc388328e8a2f751 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Fri, 23 Aug 2019 15:38:51 -0400 Subject: [PATCH 078/134] Bumped version to 4.1.1-SNAPSHOT for continued development. --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index a3f3da3e6..477573893 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.onarandombox.multiversecore Multiverse-Core - 4.1.0 + 4.1.1-SNAPSHOT Multiverse-Core World Management Plugin From 22ad7214b09dc11a53f61941cf40340ec9a4eb20 Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Mon, 26 Aug 2019 13:47:26 -0400 Subject: [PATCH 079/134] Made the donation messages at startup hidden with silent start. --- .../java/com/onarandombox/MultiverseCore/MultiverseCore.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java index c1b53f658..9693a863e 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java @@ -340,8 +340,8 @@ public void onEnable() { // Output a little snippet to show it's enabled. Logging.config("Version %s (API v%s) Enabled - By %s", this.getDescription().getVersion(), PROTOCOL, getAuthors()); - getLogger().info("Help dumptruckman keep this project alive. Become a patron! https://www.patreon.com/dumptruckman"); - getLogger().info("One time donations are also appreciated: https://www.paypal.me/dumptruckman"); + getLogger().config("Help dumptruckman keep this project alive. Become a patron! https://www.patreon.com/dumptruckman"); + getLogger().config("One time donations are also appreciated: https://www.paypal.me/dumptruckman"); } /** From b4b0940918ce49af28bcb11c8b6ce697dc3947ef Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Mon, 26 Aug 2019 13:47:54 -0400 Subject: [PATCH 080/134] Added additional configuration option to disable the donation messages. --- .../MultiverseCore/MultiverseCore.java | 6 +++-- .../MultiverseCoreConfiguration.java | 25 +++++++++++++++---- .../api/MultiverseCoreConfig.java | 14 +++++++++++ 3 files changed, 38 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java index 9693a863e..dbe1ca568 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java @@ -340,8 +340,10 @@ public void onEnable() { // Output a little snippet to show it's enabled. Logging.config("Version %s (API v%s) Enabled - By %s", this.getDescription().getVersion(), PROTOCOL, getAuthors()); - getLogger().config("Help dumptruckman keep this project alive. Become a patron! https://www.patreon.com/dumptruckman"); - getLogger().config("One time donations are also appreciated: https://www.paypal.me/dumptruckman"); + if (getMVConfig().isShowingDonateMessage()) { + getLogger().config("Help dumptruckman keep this project alive. Become a patron! https://www.patreon.com/dumptruckman"); + getLogger().config("One time donations are also appreciated: https://www.paypal.me/dumptruckman"); + } } /** diff --git a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCoreConfiguration.java b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCoreConfiguration.java index 1f295dbb9..a04a6651a 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCoreConfiguration.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCoreConfiguration.java @@ -1,13 +1,15 @@ package com.onarandombox.MultiverseCore; -import com.dumptruckman.minecraft.util.*; -import com.onarandombox.MultiverseCore.api.*; +import java.util.Map; + +import com.dumptruckman.minecraft.util.Logging; +import com.onarandombox.MultiverseCore.api.MultiverseCoreConfig; import com.onarandombox.MultiverseCore.event.MVDebugModeEvent; -import me.main__.util.SerializationConfig.*; +import me.main__.util.SerializationConfig.NoSuchPropertyException; +import me.main__.util.SerializationConfig.Property; +import me.main__.util.SerializationConfig.SerializationConfig; import org.bukkit.Bukkit; -import java.util.*; - /** * Our configuration. */ @@ -71,6 +73,8 @@ public static MultiverseCoreConfiguration getInstance() { private volatile int portalsearchradius; @Property private volatile boolean autopurge; + @Property + private volatile boolean idonotwanttodonate; public MultiverseCoreConfiguration() { super(); @@ -103,6 +107,7 @@ protected void setDefaults() { defaultportalsearch = false; portalsearchradius = 128; autopurge = true; + idonotwanttodonate = false; // END CHECKSTYLE-SUPPRESSION: MagicNumberCheck } @@ -348,4 +353,14 @@ public boolean isAutoPurgeEnabled() { public void setAutoPurgeEnabled(boolean autopurge) { this.autopurge = autopurge; } + + @Override + public boolean isShowingDonateMessage() { + return !idonotwanttodonate; + } + + @Override + public void setShowDonateMessage(boolean showDonateMessage) { + this.idonotwanttodonate = !showDonateMessage; + } } diff --git a/src/main/java/com/onarandombox/MultiverseCore/api/MultiverseCoreConfig.java b/src/main/java/com/onarandombox/MultiverseCore/api/MultiverseCoreConfig.java index f66922ec3..b5574ff26 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/api/MultiverseCoreConfig.java +++ b/src/main/java/com/onarandombox/MultiverseCore/api/MultiverseCoreConfig.java @@ -213,4 +213,18 @@ public interface MultiverseCoreConfig extends ConfigurationSerializable { * @param autopurge True if automatic purge should be enabled. */ void setAutoPurgeEnabled(boolean autopurge); + + /** + * Gets whether or not the donation/patreon messages are shown. + * + * @return True if donation/patreon messages should be shown. + */ + boolean isShowingDonateMessage(); + + /** + * Sets whether or not the donation/patreon messages are shown. + * + * @param idonotwanttodonate True if donation/patreon messages should be shown. + */ + void setShowDonateMessage(boolean idonotwanttodonate); } From 46f8453b5b83a0c8a14d85f7f0e463aadda41513 Mon Sep 17 00:00:00 2001 From: Niels Boehm Date: Mon, 23 Sep 2019 14:54:35 +0200 Subject: [PATCH 081/134] Ensure archors are saved in a machine-readable way `locationToString()` is primarily used by the AnchorManager to persist anchors to disk (the other use is for logging). In a locale that uses periods as decimal separator, this works fine and the anchors can be loaded when the server restarts. However, in a locale that doesn't use periods (but commas, for instance) this produces an `anchors.yml` that cannot be parsed when loaded. Tying the string formatting in `locationToString()` to an English locale makes it behave as expected, regardless of the external locale setting. --- .../MultiverseCore/utils/SimpleLocationManipulation.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/SimpleLocationManipulation.java b/src/main/java/com/onarandombox/MultiverseCore/utils/SimpleLocationManipulation.java index 3d0436b1e..17f770e17 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/SimpleLocationManipulation.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/SimpleLocationManipulation.java @@ -19,6 +19,7 @@ import java.text.DecimalFormat; import java.util.Collections; import java.util.HashMap; +import java.util.Locale; import java.util.Map; /** @@ -52,7 +53,7 @@ public String locationToString(Location location) { if (location == null) { return ""; } - return String.format("%s:%.2f,%.2f,%.2f:%.2f:%.2f", location.getWorld().getName(), + return String.format(Locale.ENGLISH, "%s:%.2f,%.2f,%.2f:%.2f:%.2f", location.getWorld().getName(), location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch()); } From 9d42a05759228dab197e311242e79750055dd071 Mon Sep 17 00:00:00 2001 From: A248 Date: Thu, 16 Apr 2020 18:31:23 -0400 Subject: [PATCH 082/134] Fix NPE for invalid world argument in gamerule cmd Stumbled upon an NPE when using /mv gamerule. I realised it was because I had specified a nonexistent world. This will fix it. --- .../MultiverseCore/commands/GameruleCommand.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/GameruleCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/GameruleCommand.java index 5cc91d9fa..01eddae6b 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/GameruleCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/GameruleCommand.java @@ -62,6 +62,11 @@ public void runCommand(CommandSender sender, List args) { world = p.getWorld(); } else { world = Bukkit.getWorld(args.get(2)); + if (world == null) { + sender.sendMessage(ChatColor.RED + "Failure!" + ChatColor.WHITE + " World " + ChatColor.AQUA + args.get(2) + + ChatColor.WHITE + " does not exist."); + return; + } } if (world.setGameRuleValue(gameRule, value)) { From c70e254dbfb6fa0bb6128ea3d18121c896d3289a Mon Sep 17 00:00:00 2001 From: wellnesscookie <46493763+wellnesscookie@users.noreply.github.com> Date: Thu, 30 Apr 2020 20:43:11 +0200 Subject: [PATCH 083/134] Fixes alias not clearing after cloning the world This will rather set an alias to an empty string which will automatically be resulted in alias being as same as the name of the cloned world. Previously, it was not working as intended and kept the alias of the oldWorld. --- .../com/onarandombox/MultiverseCore/utils/WorldManager.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/WorldManager.java b/src/main/java/com/onarandombox/MultiverseCore/utils/WorldManager.java index 41cd707e1..d3fcb8c6d 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/WorldManager.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/WorldManager.java @@ -199,7 +199,7 @@ public boolean cloneWorld(String oldName, String newName) { MVWorld newWorld = (MVWorld) this.getMVWorld(newName); newWorld.copyValues(this.worldsFromTheConfig.get(oldName)); // don't keep the alias the same -- that would be useless - newWorld.setAlias(null); + newWorld.setAlias(""); return true; } } From 1fac13247f297a5d6043b475cade3d18f5d54c2b Mon Sep 17 00:00:00 2001 From: nicegamer7 Date: Wed, 6 May 2020 13:07:48 -0400 Subject: [PATCH 084/134] Fix Travis Builds for Pull Requests (#2208) * fix travis * I don't think we need this * we don't use circleci anymore --- .travis.yml | 3 +-- circle.yml | 3 --- 2 files changed, 1 insertion(+), 5 deletions(-) delete mode 100644 circle.yml diff --git a/.travis.yml b/.travis.yml index 1ecfa2d1f..2e7dbb32c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,5 +3,4 @@ jdk: - oraclejdk8 notifications: email: false -before_install: - - sed -i.bak -e 's|https://nexus.codehaus.org/snapshots/|https://oss.sonatype.org/content/repositories/codehaus-snapshots/|g' ~/.m2/settings.xml +dist: trusty diff --git a/circle.yml b/circle.yml deleted file mode 100644 index 593dfcb24..000000000 --- a/circle.yml +++ /dev/null @@ -1,3 +0,0 @@ -machine: - java: - version: oraclejdk8 \ No newline at end of file From 4894abd1f1b66a87f7793487cd772cc5d3b7e0fd Mon Sep 17 00:00:00 2001 From: Kermina Awad Date: Sat, 6 Jun 2020 13:36:53 -0400 Subject: [PATCH 085/134] switch to bStats --- pom.xml | 15 +-- .../MultiverseCore/MultiverseCore.java | 120 +++++------------- 2 files changed, 42 insertions(+), 93 deletions(-) diff --git a/pom.xml b/pom.xml index 477573893..0949061fc 100644 --- a/pom.xml +++ b/pom.xml @@ -33,10 +33,9 @@ minebench-repo https://repo.minebench.de/ - - elmakers-repo - http://maven.elmakers.com/repository/ + CodeMC + https://repo.codemc.org/repository/maven-public @@ -203,8 +202,8 @@ com.onarandombox.buscript - org.mcstats - com.onarandombox.mcstats + org.bstats + com.onarandombox.bstats com.dumptruckman.minecraft.util.Logging @@ -283,9 +282,9 @@ 2.0-SNAPSHOT - org.mcstats.bukkit - metrics - R8-SNAPSHOT + org.bstats + bstats-bukkit + 1.7 org.bukkit diff --git a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java index dbe1ca568..be090a6c1 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java @@ -17,11 +17,9 @@ import java.util.Arrays; import java.util.Collections; import java.util.HashMap; -import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import java.util.Set; import java.util.logging.Level; import buscript.Buscript; @@ -105,11 +103,11 @@ import com.pneumaticraft.commandhandler.CommandHandler; import me.main__.util.SerializationConfig.NoSuchPropertyException; import me.main__.util.SerializationConfig.SerializationConfig; +import org.bstats.bukkit.Metrics; import org.bukkit.ChatColor; import org.bukkit.Difficulty; import org.bukkit.GameMode; import org.bukkit.Location; -import org.bukkit.World.Environment; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.Configuration; @@ -122,7 +120,6 @@ import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPluginLoader; -import org.mcstats.Metrics; /** * The implementation of the Multiverse-{@link Core}. @@ -355,95 +352,48 @@ private void initializeBuscript() { buscript.setScriptVariable("multiverse", this); } - /** - * Plotter for Environment-Values. - */ - private static final class EnvironmentPlotter extends Metrics.Plotter { - private MultiverseCore core; - private final Environment env; - - public EnvironmentPlotter(MultiverseCore core, Environment env) { - super(envToString(env)); - this.core = core; - this.env = env; - } + private void setupMetrics() { + try { + Metrics metrics = new Metrics(this, 7765); + + metrics.addCustomChart(new Metrics.AdvancedPie("custom_generators", () -> { + Map map = new HashMap<>(); + for (MultiverseWorld w : this.getMVWorldManager().getMVWorlds()) { + if (w.getGenerator() != null && !w.getGenerator().equalsIgnoreCase("null")) { + map.putIfAbsent(w.getGenerator(), 0); + map.put(w.getGenerator(), map.get(w.getGenerator()) + 1); + } + } - private static String envToString(Environment env) { - return new StringBuilder().append(env.name().toUpperCase().charAt(0)) - .append(env.name().toLowerCase().substring(1)).toString(); - } + return map; + })); - @Override - public int getValue() { - int count = 0; - for (MultiverseWorld w : core.getMVWorldManager().getMVWorlds()) - if (w.getEnvironment() == env) - count++; - core.log(Level.FINE, String.format("Tracking %d worlds of type %s", count, env)); - return count; - } - } + metrics.addCustomChart(new Metrics.AdvancedPie("environments", () -> { + Map map = new HashMap<>(); + for (MultiverseWorld w : this.getMVWorldManager().getMVWorlds()) { + StringBuilder environment = new StringBuilder(); + String[] environmentArray = w.getEnvironment().name().split("_"); - /** - * Plotter for Generator-Values. - */ - private static final class GeneratorPlotter extends Metrics.Plotter { - private MultiverseCore core; - private final String gen; - - public GeneratorPlotter(MultiverseCore core, String gen) { - super(gen); - this.core = core; - this.gen = gen; - } + for (int i = 0; i < environmentArray.length; i++) { + environment.append(environmentArray[i].substring(0, 1).toUpperCase()); + environment.append(environmentArray[i].substring(1).toLowerCase()); + if (i != environmentArray.length - 1) environment.append(" "); + } - @Override - public int getValue() { - int count = 0; - for (MultiverseWorld w : core.getMVWorldManager().getMVWorlds()) - if (gen.equals(w.getGenerator())) - count++; - core.log(Level.FINE, String.format("Tracking %d worlds of type %s", count, gen)); - return count; - } - } + String e = environment.toString(); + map.putIfAbsent(e, 0); + map.put(e, map.get(e) + 1); + } - private void setupMetrics() { - try { - Metrics m = new Metrics(this); + // TODO: add Worlds vs Loaded Worlds once bStats adds support for multi-line charts - Metrics.Graph envGraph = m.createGraph("Worlds by environment"); - for (Environment env : Environment.values()) - envGraph.addPlotter(new EnvironmentPlotter(this, env)); + return map; + })); - Metrics.Graph loadedWorldsGraph = m.createGraph("Worlds by environment"); - loadedWorldsGraph.addPlotter(new Metrics.Plotter("Loaded worlds") { - @Override - public int getValue() { - return getMVWorldManager().getMVWorlds().size(); - } - }); - loadedWorldsGraph.addPlotter(new Metrics.Plotter("Total number of worlds") { - @Override - public int getValue() { - return getMVWorldManager().getMVWorlds().size() - + getMVWorldManager().getUnloadedWorlds().size(); - } - }); - - Set gens = new HashSet(); - for (MultiverseWorld w : this.getMVWorldManager().getMVWorlds()) - gens.add(w.getGenerator()); - gens.remove(null); - gens.remove("null"); - Metrics.Graph genGraph = m.createGraph("Custom Generators"); - for (String gen : gens) - genGraph.addPlotter(new GeneratorPlotter(this, gen)); - - m.start(); - log(Level.FINE, "Metrics have run!"); + log(Level.FINE, "Metrics were set up!"); } catch (Exception e) { - log(Level.WARNING, "There was an issue while enabling metrics: " + e.getMessage()); + log(Level.WARNING, "There was an issue while enabling metrics:"); + e.printStackTrace(); } } From 1cbe901e4df8e8c66a558b9681008b96a234180c Mon Sep 17 00:00:00 2001 From: Kermina Awad Date: Sat, 6 Jun 2020 13:38:03 -0400 Subject: [PATCH 086/134] lead dev should be the first author listed --- src/main/resources/plugin.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index d65a37791..5a4dfeba3 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,6 +1,6 @@ name: Multiverse-Core main: com.onarandombox.MultiverseCore.MultiverseCore -authors: ['Rigby', 'fernferret', 'lithium3141', 'main--', 'dumptruckman'] +authors: ['dumptruckman', 'Rigby', 'fernferret', 'lithium3141', 'main--'] website: 'https://dev.bukkit.org/projects/multiverse-core' api-version: 1.13 version: maven-version-number From 8983a0c0244acc53a7241604cd341562fae91a5f Mon Sep 17 00:00:00 2001 From: Kermina Awad Date: Sun, 7 Jun 2020 19:31:51 -0400 Subject: [PATCH 087/134] add vault as softdepend --- src/main/resources/plugin.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 5a4dfeba3..5359af214 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -2,6 +2,7 @@ name: Multiverse-Core main: com.onarandombox.MultiverseCore.MultiverseCore authors: ['dumptruckman', 'Rigby', 'fernferret', 'lithium3141', 'main--'] website: 'https://dev.bukkit.org/projects/multiverse-core' +softdepend: ['Vault'] api-version: 1.13 version: maven-version-number commands: From 268c4982c3b392784297725dba1160710797be00 Mon Sep 17 00:00:00 2001 From: Kermina Awad Date: Fri, 12 Jun 2020 23:50:17 -0400 Subject: [PATCH 088/134] update metric implementations --- .../MultiverseCore/MultiverseCore.java | 27 +++++++------------ 1 file changed, 9 insertions(+), 18 deletions(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java index be090a6c1..52b9074af 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java @@ -103,6 +103,7 @@ import com.pneumaticraft.commandhandler.CommandHandler; import me.main__.util.SerializationConfig.NoSuchPropertyException; import me.main__.util.SerializationConfig.SerializationConfig; +import org.apache.commons.lang.StringUtils; import org.bstats.bukkit.Metrics; import org.bukkit.ChatColor; import org.bukkit.Difficulty; @@ -359,10 +360,9 @@ private void setupMetrics() { metrics.addCustomChart(new Metrics.AdvancedPie("custom_generators", () -> { Map map = new HashMap<>(); for (MultiverseWorld w : this.getMVWorldManager().getMVWorlds()) { - if (w.getGenerator() != null && !w.getGenerator().equalsIgnoreCase("null")) { - map.putIfAbsent(w.getGenerator(), 0); - map.put(w.getGenerator(), map.get(w.getGenerator()) + 1); - } + String gen = w.getGenerator() != null ? w.getGenerator() : "N/A"; + map.putIfAbsent(gen, 0); + map.put(gen, map.get(gen) + 1); } return map; @@ -371,25 +371,16 @@ private void setupMetrics() { metrics.addCustomChart(new Metrics.AdvancedPie("environments", () -> { Map map = new HashMap<>(); for (MultiverseWorld w : this.getMVWorldManager().getMVWorlds()) { - StringBuilder environment = new StringBuilder(); - String[] environmentArray = w.getEnvironment().name().split("_"); - - for (int i = 0; i < environmentArray.length; i++) { - environment.append(environmentArray[i].substring(0, 1).toUpperCase()); - environment.append(environmentArray[i].substring(1).toLowerCase()); - if (i != environmentArray.length - 1) environment.append(" "); - } - - String e = environment.toString(); - map.putIfAbsent(e, 0); - map.put(e, map.get(e) + 1); + String env = w.getEnvironment().name().replace('_', ' '); + env = StringUtils.capitalize(env.toLowerCase()); + map.putIfAbsent(env, 0); + map.put(env, map.get(env) + 1); } - // TODO: add Worlds vs Loaded Worlds once bStats adds support for multi-line charts - return map; })); + // TODO: add Worlds vs Loaded Worlds once bStats adds support for multi-line charts log(Level.FINE, "Metrics were set up!"); } catch (Exception e) { log(Level.WARNING, "There was an issue while enabling metrics:"); From 04c65cc59e5949cb2138654e4f7482ba081883ef Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Sat, 13 Jun 2020 00:51:18 -0400 Subject: [PATCH 089/134] Cleanup new metrics implementation. (#2286) * Refactor metrics initialization into its own class. * Simplify the creation of metrics. * Clean up new metrics. * Refactor out duplicate metrics code. --- .../MultiverseCore/MultiverseCore.java | 42 +---------- .../utils/metrics/MetricsConfigurator.java | 71 +++++++++++++++++++ .../utils/metrics/MetricsHelper.java | 26 +++++++ 3 files changed, 100 insertions(+), 39 deletions(-) create mode 100644 src/main/java/com/onarandombox/MultiverseCore/utils/metrics/MetricsConfigurator.java create mode 100644 src/main/java/com/onarandombox/MultiverseCore/utils/metrics/MetricsHelper.java diff --git a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java index 52b9074af..772a4c722 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java @@ -32,7 +32,6 @@ import com.onarandombox.MultiverseCore.api.MVWorldManager; import com.onarandombox.MultiverseCore.api.MultiverseCoreConfig; import com.onarandombox.MultiverseCore.api.MultiverseMessaging; -import com.onarandombox.MultiverseCore.api.MultiverseWorld; import com.onarandombox.MultiverseCore.api.SafeTTeleporter; import com.onarandombox.MultiverseCore.commands.AnchorCommand; import com.onarandombox.MultiverseCore.commands.CheckCommand; @@ -94,6 +93,7 @@ import com.onarandombox.MultiverseCore.utils.MVPermissions; import com.onarandombox.MultiverseCore.utils.MVPlayerSession; import com.onarandombox.MultiverseCore.utils.MaterialConverter; +import com.onarandombox.MultiverseCore.utils.metrics.MetricsConfigurator; import com.onarandombox.MultiverseCore.utils.SimpleBlockSafety; import com.onarandombox.MultiverseCore.utils.SimpleLocationManipulation; import com.onarandombox.MultiverseCore.utils.SimpleSafeTTeleporter; @@ -103,8 +103,6 @@ import com.pneumaticraft.commandhandler.CommandHandler; import me.main__.util.SerializationConfig.NoSuchPropertyException; import me.main__.util.SerializationConfig.SerializationConfig; -import org.apache.commons.lang.StringUtils; -import org.bstats.bukkit.Metrics; import org.bukkit.ChatColor; import org.bukkit.Difficulty; import org.bukkit.GameMode; @@ -333,7 +331,8 @@ public void onEnable() { getServer().getPluginManager().registerEvents(this.chatListener, this); this.initializeBuscript(); - this.setupMetrics(); + + MetricsConfigurator.configureMetrics(this); // Output a little snippet to show it's enabled. Logging.config("Version %s (API v%s) Enabled - By %s", this.getDescription().getVersion(), PROTOCOL, getAuthors()); @@ -353,41 +352,6 @@ private void initializeBuscript() { buscript.setScriptVariable("multiverse", this); } - private void setupMetrics() { - try { - Metrics metrics = new Metrics(this, 7765); - - metrics.addCustomChart(new Metrics.AdvancedPie("custom_generators", () -> { - Map map = new HashMap<>(); - for (MultiverseWorld w : this.getMVWorldManager().getMVWorlds()) { - String gen = w.getGenerator() != null ? w.getGenerator() : "N/A"; - map.putIfAbsent(gen, 0); - map.put(gen, map.get(gen) + 1); - } - - return map; - })); - - metrics.addCustomChart(new Metrics.AdvancedPie("environments", () -> { - Map map = new HashMap<>(); - for (MultiverseWorld w : this.getMVWorldManager().getMVWorlds()) { - String env = w.getEnvironment().name().replace('_', ' '); - env = StringUtils.capitalize(env.toLowerCase()); - map.putIfAbsent(env, 0); - map.put(env, map.get(env) + 1); - } - - return map; - })); - - // TODO: add Worlds vs Loaded Worlds once bStats adds support for multi-line charts - log(Level.FINE, "Metrics were set up!"); - } catch (Exception e) { - log(Level.WARNING, "There was an issue while enabling metrics:"); - e.printStackTrace(); - } - } - private void initializeDestinationFactory() { this.destFactory = new DestinationFactory(this); this.destFactory.registerDestinationType(WorldDestination.class, ""); diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/metrics/MetricsConfigurator.java b/src/main/java/com/onarandombox/MultiverseCore/utils/metrics/MetricsConfigurator.java new file mode 100644 index 000000000..30cc0353e --- /dev/null +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/metrics/MetricsConfigurator.java @@ -0,0 +1,71 @@ +package com.onarandombox.MultiverseCore.utils.metrics; + +import java.util.Map; +import java.util.function.Consumer; + +import com.dumptruckman.minecraft.util.Logging; +import com.onarandombox.MultiverseCore.MultiverseCore; +import com.onarandombox.MultiverseCore.api.MultiverseWorld; +import org.apache.commons.lang.StringUtils; +import org.bstats.bukkit.Metrics; +import org.bukkit.World; + +public class MetricsConfigurator { + + private static final int PLUGIN_ID = 7765; + private static final String NO_GENERATOR_NAME = "N/A"; + + public static void configureMetrics(MultiverseCore plugin) { + MetricsConfigurator configurator = new MetricsConfigurator(plugin); + configurator.initMetrics(); + } + + private final MultiverseCore plugin; + private final Metrics metrics; + + private MetricsConfigurator(MultiverseCore plugin) { + this.plugin = plugin; + this.metrics = new Metrics(plugin, PLUGIN_ID); + } + + private void initMetrics() { + try { + addCustomGeneratorsMetric(); + createEnvironmentsMetric(); + + Logging.fine("Metrics enabled."); + } catch (Exception e) { + Logging.warning("There was an issue while enabling metrics:"); + e.printStackTrace(); + } + } + + private void addCustomGeneratorsMetric() { + addAdvancedPieMetric("custom_generators", map -> { + for (MultiverseWorld w : plugin.getMVWorldManager().getMVWorlds()) { + MetricsHelper.incrementCount(map, getGeneratorName(w)); + } + }); + } + + private String getGeneratorName(MultiverseWorld world) { + return world.getGenerator() != null ? world.getGenerator() : NO_GENERATOR_NAME; + } + + private void createEnvironmentsMetric() { + addAdvancedPieMetric("environments", map -> { + for (MultiverseWorld w : plugin.getMVWorldManager().getMVWorlds()) { + MetricsHelper.incrementCount(map, titleCaseEnv(w.getEnvironment())); + } + }); + } + + private String titleCaseEnv(World.Environment env) { + String envName = env.name().replaceAll("_+", " "); + return StringUtils.capitalize(envName.toLowerCase()); + } + + private void addAdvancedPieMetric(String chartId, Consumer> metricsFunc) { + metrics.addCustomChart(MetricsHelper.createAdvancedPieChart(chartId, metricsFunc)); + } +} diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/metrics/MetricsHelper.java b/src/main/java/com/onarandombox/MultiverseCore/utils/metrics/MetricsHelper.java new file mode 100644 index 000000000..b7a92a5e2 --- /dev/null +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/metrics/MetricsHelper.java @@ -0,0 +1,26 @@ +package com.onarandombox.MultiverseCore.utils.metrics; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.Consumer; + +import org.bstats.bukkit.Metrics; + +enum MetricsHelper { + ; + + /** + * Adds one to the value in the given map with the given key. If the key does not exist in the map, it will be added with a value of 1. + */ + static void incrementCount(Map map, String key) { + Integer count = map.getOrDefault(key, 0); + map.put(key, count + 1); + } + + static Metrics.AdvancedPie createAdvancedPieChart(String chartId, Consumer> metricsFunc) { + Map map = new HashMap<>(); + metricsFunc.accept(map); + return new Metrics.AdvancedPie(chartId, () -> map); + } + +} From 582d6bef1aea750e1f802e45c13102e13c4fbc6f Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Sat, 13 Jun 2020 01:17:00 -0400 Subject: [PATCH 090/134] Readd world count metric as multiline chart (for future use). --- .../utils/metrics/MetricsConfigurator.java | 31 ++++++++++++++++--- .../utils/metrics/MetricsHelper.java | 6 ++++ 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/metrics/MetricsConfigurator.java b/src/main/java/com/onarandombox/MultiverseCore/utils/metrics/MetricsConfigurator.java index 30cc0353e..25aaf009f 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/metrics/MetricsConfigurator.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/metrics/MetricsConfigurator.java @@ -1,10 +1,12 @@ package com.onarandombox.MultiverseCore.utils.metrics; +import java.util.Collection; import java.util.Map; import java.util.function.Consumer; import com.dumptruckman.minecraft.util.Logging; import com.onarandombox.MultiverseCore.MultiverseCore; +import com.onarandombox.MultiverseCore.api.MVWorldManager; import com.onarandombox.MultiverseCore.api.MultiverseWorld; import org.apache.commons.lang.StringUtils; import org.bstats.bukkit.Metrics; @@ -28,10 +30,19 @@ private MetricsConfigurator(MultiverseCore plugin) { this.metrics = new Metrics(plugin, PLUGIN_ID); } + private MVWorldManager getWorldManager() { + return plugin.getMVWorldManager(); + } + + private Collection getMVWorlds() { + return getWorldManager().getMVWorlds(); + } + private void initMetrics() { try { addCustomGeneratorsMetric(); - createEnvironmentsMetric(); + addEnvironmentsMetric(); + addWorldCountMetric(); Logging.fine("Metrics enabled."); } catch (Exception e) { @@ -42,7 +53,7 @@ private void initMetrics() { private void addCustomGeneratorsMetric() { addAdvancedPieMetric("custom_generators", map -> { - for (MultiverseWorld w : plugin.getMVWorldManager().getMVWorlds()) { + for (MultiverseWorld w : getMVWorlds()) { MetricsHelper.incrementCount(map, getGeneratorName(w)); } }); @@ -52,9 +63,9 @@ private String getGeneratorName(MultiverseWorld world) { return world.getGenerator() != null ? world.getGenerator() : NO_GENERATOR_NAME; } - private void createEnvironmentsMetric() { + private void addEnvironmentsMetric() { addAdvancedPieMetric("environments", map -> { - for (MultiverseWorld w : plugin.getMVWorldManager().getMVWorlds()) { + for (MultiverseWorld w : getMVWorlds()) { MetricsHelper.incrementCount(map, titleCaseEnv(w.getEnvironment())); } }); @@ -65,7 +76,19 @@ private String titleCaseEnv(World.Environment env) { return StringUtils.capitalize(envName.toLowerCase()); } + private void addWorldCountMetric() { + addMultiLineMetric("world_count", map -> { + int loadedWorldsCount = getMVWorlds().size(); + map.put("Loaded worlds", loadedWorldsCount); + map.put("Total number of worlds", loadedWorldsCount + getWorldManager().getUnloadedWorlds().size()); + }); + } + private void addAdvancedPieMetric(String chartId, Consumer> metricsFunc) { metrics.addCustomChart(MetricsHelper.createAdvancedPieChart(chartId, metricsFunc)); } + + private void addMultiLineMetric(String chartId, Consumer> metricsFunc) { + metrics.addCustomChart(MetricsHelper.createMultiLineChart(chartId, metricsFunc)); + } } diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/metrics/MetricsHelper.java b/src/main/java/com/onarandombox/MultiverseCore/utils/metrics/MetricsHelper.java index b7a92a5e2..23fb6eba6 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/metrics/MetricsHelper.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/metrics/MetricsHelper.java @@ -23,4 +23,10 @@ static Metrics.AdvancedPie createAdvancedPieChart(String chartId, Consumer map); } + static Metrics.MultiLineChart createMultiLineChart(String chartId, Consumer> metricsFunc) { + Map map = new HashMap<>(); + metricsFunc.accept(map); + return new Metrics.MultiLineChart(chartId, () -> map); + } + } From b3f23278b1323fd204b59c6043ad5220397af9fc Mon Sep 17 00:00:00 2001 From: Jeremy Wood Date: Sat, 13 Jun 2020 01:33:22 -0400 Subject: [PATCH 091/134] Yay for tests that use method names in strings. -.- --- .../com/onarandombox/MultiverseCore/MultiverseCore.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java index 772a4c722..43820a5af 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java @@ -331,8 +331,7 @@ public void onEnable() { getServer().getPluginManager().registerEvents(this.chatListener, this); this.initializeBuscript(); - - MetricsConfigurator.configureMetrics(this); + this.setupMetrics(); // Output a little snippet to show it's enabled. Logging.config("Version %s (API v%s) Enabled - By %s", this.getDescription().getVersion(), PROTOCOL, getAuthors()); @@ -343,6 +342,10 @@ public void onEnable() { } } + private void setupMetrics() { + MetricsConfigurator.configureMetrics(this); + } + /** * Initializes the buscript javascript library. */ From f570c813663d7017b3be2c8704ab40d76d4ecf76 Mon Sep 17 00:00:00 2001 From: Kermina Awad Date: Fri, 5 Jun 2020 20:00:00 -0400 Subject: [PATCH 092/134] update version command --- .../commands/VersionCommand.java | 123 +++++++++--------- .../utils/webpaste/HastebinPasteService.java | 1 - 2 files changed, 62 insertions(+), 62 deletions(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java index b2ac51e40..146d91ee2 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java @@ -24,9 +24,12 @@ import org.bukkit.entity.Player; import org.bukkit.permissions.PermissionDefault; import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.util.StringUtil; -import java.io.*; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -50,79 +53,74 @@ public VersionCommand(MultiverseCore plugin) { } private String getLegacyString() { - StringBuilder legacyFile = new StringBuilder(); - legacyFile.append("[Multiverse-Core] Multiverse-Core Version: ").append(this.plugin.getDescription().getVersion()).append('\n'); - legacyFile.append("[Multiverse-Core] Bukkit Version: ").append(this.plugin.getServer().getVersion()).append('\n'); - legacyFile.append("[Multiverse-Core] Loaded Worlds: ").append(this.plugin.getMVWorldManager().getMVWorlds()).append('\n'); - legacyFile.append("[Multiverse-Core] Multiverse Plugins Loaded: ").append(this.plugin.getPluginCount()).append('\n'); - legacyFile.append("[Multiverse-Core] Economy being used: ").append(plugin.getEconomist().getEconomyName()).append('\n'); - legacyFile.append("[Multiverse-Core] Permissions Plugin: ").append(this.plugin.getMVPerms().getType()).append('\n'); - legacyFile.append("[Multiverse-Core] Dumping Config Values: (version ") - .append(this.plugin.getMVConfig().getVersion()).append(")").append('\n'); - legacyFile.append("[Multiverse-Core] messagecooldown: ").append(plugin.getMessaging().getCooldown()).append('\n'); - legacyFile.append("[Multiverse-Core] teleportcooldown: ").append(plugin.getMVConfig().getTeleportCooldown()).append('\n'); - legacyFile.append("[Multiverse-Core] worldnameprefix: ").append(plugin.getMVConfig().getPrefixChat()).append('\n'); - legacyFile.append("[Multiverse-Core] worldnameprefixFormat: ").append(plugin.getMVConfig().getPrefixChatFormat()).append('\n'); - legacyFile.append("[Multiverse-Core] enforceaccess: ").append(plugin.getMVConfig().getEnforceAccess()).append('\n'); - legacyFile.append("[Multiverse-Core] displaypermerrors: ").append(plugin.getMVConfig().getDisplayPermErrors()).append('\n'); - legacyFile.append("[Multiverse-Core] teleportintercept: ").append(plugin.getMVConfig().getTeleportIntercept()).append('\n'); - legacyFile.append("[Multiverse-Core] firstspawnoverride: ").append(plugin.getMVConfig().getFirstSpawnOverride()).append('\n'); - legacyFile.append("[Multiverse-Core] firstspawnworld: ").append(plugin.getMVConfig().getFirstSpawnWorld()).append('\n'); - legacyFile.append("[Multiverse-Core] debug: ").append(plugin.getMVConfig().getGlobalDebug()).append('\n'); - legacyFile.append("[Multiverse-Core] Special Code: FRN002").append('\n'); - return legacyFile.toString(); + return "[Multiverse-Core] Multiverse-Core Version: " + this.plugin.getDescription().getVersion() + System.lineSeparator() + + "[Multiverse-Core] Bukkit Version: " + this.plugin.getServer().getVersion() + System.lineSeparator() + + "[Multiverse-Core] Loaded Worlds: " + this.plugin.getMVWorldManager().getMVWorlds() + System.lineSeparator() + + "[Multiverse-Core] Multiverse Plugins Loaded: " + this.plugin.getPluginCount() + System.lineSeparator() + + "[Multiverse-Core] Economy being used: " + plugin.getEconomist().getEconomyName() + System.lineSeparator() + + "[Multiverse-Core] Permissions Plugin: " + this.plugin.getMVPerms().getType() + System.lineSeparator() + + "[Multiverse-Core] Dumping Config Values: (version " + this.plugin.getMVConfig().getVersion() + ")" + System.lineSeparator() + + "[Multiverse-Core] messagecooldown: " + plugin.getMessaging().getCooldown() + System.lineSeparator() + + "[Multiverse-Core] teleportcooldown: " + plugin.getMVConfig().getTeleportCooldown() + System.lineSeparator() + + "[Multiverse-Core] worldnameprefix: " + plugin.getMVConfig().getPrefixChat() + System.lineSeparator() + + "[Multiverse-Core] worldnameprefixFormat: " + plugin.getMVConfig().getPrefixChatFormat() + System.lineSeparator() + + "[Multiverse-Core] enforceaccess: " + plugin.getMVConfig().getEnforceAccess() + System.lineSeparator() + + "[Multiverse-Core] displaypermerrors: " + plugin.getMVConfig().getDisplayPermErrors() + System.lineSeparator() + + "[Multiverse-Core] teleportintercept: " + plugin.getMVConfig().getTeleportIntercept() + System.lineSeparator() + + "[Multiverse-Core] firstspawnoverride: " + plugin.getMVConfig().getFirstSpawnOverride() + System.lineSeparator() + + "[Multiverse-Core] firstspawnworld: " + plugin.getMVConfig().getFirstSpawnWorld() + System.lineSeparator() + + "[Multiverse-Core] debug: " + plugin.getMVConfig().getGlobalDebug() + System.lineSeparator() + + "[Multiverse-Core] Special Code: FRN002" + System.lineSeparator(); } private String getMarkdownString() { - StringBuilder markdownString = new StringBuilder(); - markdownString.append("# Multiverse-Core\n"); - markdownString.append("## Overview\n"); - markdownString.append("| Name | Value |\n"); - markdownString.append("| --- | --- |\n"); - markdownString.append("| Multiverse-Core Version | `").append(this.plugin.getDescription().getVersion()).append("` |\n"); - markdownString.append("| Bukkit Version | `").append(this.plugin.getServer().getVersion()).append("` |\n"); - //markdownString.append("| Loaded Worlds | `").append(this.plugin.getMVWorldManager().getMVWorlds()).append("` |\n"); - markdownString.append("| Multiverse Plugins Loaded | `").append(this.plugin.getPluginCount()).append("` |\n"); - markdownString.append("| Economy being used | `").append(plugin.getEconomist().getEconomyName()).append("` |\n"); - markdownString.append("| Permissions Plugin | `").append(this.plugin.getMVPerms().getType()).append("` |\n"); - markdownString.append("## Parsed Config\n"); - markdownString.append("These are what Multiverse thought the in-memory values of the config were.\n\n"); - markdownString.append("| Config Key | Value |\n"); - markdownString.append("| --- | --- |\n"); - markdownString.append("| version | `").append(this.plugin.getMVConfig().getVersion()).append("` |\n"); - markdownString.append("| messagecooldown | `").append(plugin.getMessaging().getCooldown()).append("` |\n"); - markdownString.append("| teleportcooldown | `").append(plugin.getMVConfig().getTeleportCooldown()).append("` |\n"); - markdownString.append("| worldnameprefix | `").append(plugin.getMVConfig().getPrefixChat()).append("` |\n"); - markdownString.append("| worldnameprefixFormat | `").append(plugin.getMVConfig().getPrefixChatFormat()).append("` |\n"); - markdownString.append("| enforceaccess | `").append(plugin.getMVConfig().getEnforceAccess()).append("` |\n"); - markdownString.append("| displaypermerrors | `").append(plugin.getMVConfig().getDisplayPermErrors()).append("` |\n"); - markdownString.append("| teleportintercept | `").append(plugin.getMVConfig().getTeleportIntercept()).append("` |\n"); - markdownString.append("| firstspawnoverride | `").append(plugin.getMVConfig().getFirstSpawnOverride()).append("` |\n"); - markdownString.append("| firstspawnworld | `").append(plugin.getMVConfig().getFirstSpawnWorld()).append("` |\n"); - markdownString.append("| debug | `").append(plugin.getMVConfig().getGlobalDebug()).append("` |\n"); - return markdownString.toString(); + return "# Multiverse-Core" + System.lineSeparator() + + "## Overview" + System.lineSeparator() + + "| Name | Value |" + System.lineSeparator() + + "| --- | --- |" + System.lineSeparator() + + "| Multiverse-Core Version | `" + this.plugin.getDescription().getVersion() + "` |" + System.lineSeparator() + + "| Bukkit Version | `" + this.plugin.getServer().getVersion() + "` |" + System.lineSeparator() + + //"| Loaded Worlds | `" + this.plugin.getMVWorldManager().getMVWorlds() + "` |" + System.lineSeparator() + + "| Multiverse Plugins Loaded | `" + this.plugin.getPluginCount() + "` |" + System.lineSeparator() + + "| Economy being used | `" + plugin.getEconomist().getEconomyName() + "` |" + System.lineSeparator() + + "| Permissions Plugin | `" + this.plugin.getMVPerms().getType() + "` |" + System.lineSeparator() + + "## Parsed Config" + System.lineSeparator() + + "These are what Multiverse thought the in-memory values of the config were." + System.lineSeparator() + System.lineSeparator() + + "| Config Key | Value |" + System.lineSeparator() + + "| --- | --- |" + System.lineSeparator() + + "| version | `" + this.plugin.getMVConfig().getVersion() + "` |" + System.lineSeparator() + + "| messagecooldown | `" + plugin.getMessaging().getCooldown() + "` |" + System.lineSeparator() + + "| teleportcooldown | `" + plugin.getMVConfig().getTeleportCooldown() + "` |" + System.lineSeparator() + + "| worldnameprefix | `" + plugin.getMVConfig().getPrefixChat() + "` |" + System.lineSeparator() + + "| worldnameprefixFormat | `" + plugin.getMVConfig().getPrefixChatFormat() + "` |" + System.lineSeparator() + + "| enforceaccess | `" + plugin.getMVConfig().getEnforceAccess() + "` |" + System.lineSeparator() + + "| displaypermerrors | `" + plugin.getMVConfig().getDisplayPermErrors() + "` |" + System.lineSeparator() + + "| teleportintercept | `" + plugin.getMVConfig().getTeleportIntercept() + "` |" + System.lineSeparator() + + "| firstspawnoverride | `" + plugin.getMVConfig().getFirstSpawnOverride() + "` |" + System.lineSeparator() + + "| firstspawnworld | `" + plugin.getMVConfig().getFirstSpawnWorld() + "` |" + System.lineSeparator() + + "| debug | `" + plugin.getMVConfig().getGlobalDebug() + "` |" + System.lineSeparator(); } private String readFile(final String filename) { - String result; + StringBuilder result; try { FileReader reader = new FileReader(filename); BufferedReader bufferedReader = new BufferedReader(reader); String line; - result = ""; + result = new StringBuilder(); while ((line = bufferedReader.readLine()) != null) { - result += line + '\n'; + result.append(line).append(System.lineSeparator()); } } catch (FileNotFoundException e) { Logging.severe("Unable to find %s. Here's the traceback: %s", filename, e.getMessage()); e.printStackTrace(); - result = String.format("ERROR: Could not load: %s", filename); + result = new StringBuilder(String.format("ERROR: Could not load: %s", filename)); } catch (IOException e) { Logging.severe("Something bad happend when reading %s. Here's the traceback: %s", filename, e.getMessage()); e.printStackTrace(); - result = String.format("ERROR: Could not load: %s", filename); + result = new StringBuilder(String.format("ERROR: Could not load: %s", filename)); } - return result; + return result.toString(); } private Map getVersionFiles() { @@ -155,13 +153,13 @@ public void runCommand(final CommandSender sender, final List args) { String versionInfo = versionEvent.getVersionInfo(); if (CommandHandler.hasFlag("--include-plugin-list", args)) { - versionInfo = versionInfo + "\nPlugins: " + getPluginList(); + versionInfo = versionInfo + System.lineSeparator() + "Plugins: " + getPluginList(); } final String data = versionInfo; // log to console - String[] lines = data.split("\n"); + String[] lines = data.split(System.lineSeparator()); for (String line : lines) { if (!line.isEmpty()) { Logging.info(line); @@ -177,7 +175,7 @@ public void run() { // private post to pastebin pasteUrl = postToService(PasteServiceType.PASTEBIN, true, data, files); } else if (CommandHandler.hasFlag("-h", args)) { - // private post to pastebin + // private post to hastebin pasteUrl = postToService(PasteServiceType.HASTEBIN, true, data, files); } else { return; @@ -216,8 +214,11 @@ private static String postToService(PasteServiceType type, boolean isPrivate, St } return SHORTENER.shorten(result); } catch (PasteFailedException e) { - System.out.print(e); - return "Error posting to service"; + e.printStackTrace(); + return "Error posting to service."; + } catch (NullPointerException e) { + e.printStackTrace(); + return "That service isn't supported yet."; } } diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HastebinPasteService.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HastebinPasteService.java index 69438cfd7..590c521e3 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HastebinPasteService.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HastebinPasteService.java @@ -1,6 +1,5 @@ package com.onarandombox.MultiverseCore.utils.webpaste; -import com.google.gson.JsonElement; import com.google.gson.JsonParser; import java.io.BufferedReader; From eb91eefc80ddf3b267e2813313740aa46e3cb156 Mon Sep 17 00:00:00 2001 From: Kermina Awad Date: Fri, 5 Jun 2020 21:22:14 -0400 Subject: [PATCH 093/134] fix BitlyURLShortener --- .../MultiverseCore/utils/webpaste/BitlyURLShortener.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/BitlyURLShortener.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/BitlyURLShortener.java index e700c2e32..ea52cbccd 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/BitlyURLShortener.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/BitlyURLShortener.java @@ -23,7 +23,7 @@ public BitlyURLShortener() { public String shorten(String longUrl) { try { String result = this.exec(longUrl); - if (!result.startsWith("http://j.mp/")) // ... then it's failed :/ + if (!result.startsWith("https://j.mp/")) // ... then it's failed :/ throw new IOException(result); return result; } catch (IOException e) { From d69c492577eaebbd9fff7f7958528125fd6f5436 Mon Sep 17 00:00:00 2001 From: Kermina Awad Date: Fri, 5 Jun 2020 22:09:08 -0400 Subject: [PATCH 094/134] cleanup GitHub and Pastebin paste services --- .../utils/webpaste/GithubPasteService.java | 6 +++--- .../utils/webpaste/PastebinPasteService.java | 11 +++++------ 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/GithubPasteService.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/GithubPasteService.java index 6d8409692..fe7fafc4e 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/GithubPasteService.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/GithubPasteService.java @@ -49,7 +49,9 @@ public String encodeData(Map files) { public URL getPostURL() { try { return new URL("https://api.github.com/gists"); - //return new URL("http://jsonplaceholder.typicode.com/posts"); + + // the following can be used for testing purposes + // return new URL("http://jsonplaceholder.typicode.com/posts"); } catch (MalformedURLException e) { return null; // should never hit here } @@ -68,8 +70,6 @@ public String postData(String encodedData, URL url) throws PasteFailedException rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; - String pastieUrl = ""; - //Pattern pastiePattern = this.getURLMatchingPattern(); StringBuilder responseString = new StringBuilder(); while ((line = rd.readLine()) != null) { diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PastebinPasteService.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PastebinPasteService.java index 3f06f612e..7aeba7979 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PastebinPasteService.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PastebinPasteService.java @@ -40,12 +40,11 @@ public URL getPostURL() { @Override public String encodeData(String data) { try { - String encData = URLEncoder.encode("api_dev_key", "UTF-8") + "=" + URLEncoder.encode("d61d68d31e8e0392b59b50b277411c71", "UTF-8"); - encData += "&" + URLEncoder.encode("api_option", "UTF-8") + "=" + URLEncoder.encode("paste", "UTF-8"); - encData += "&" + URLEncoder.encode("api_paste_code", "UTF-8") + "=" + URLEncoder.encode(data, "UTF-8"); - encData += "&" + URLEncoder.encode("api_paste_private", "UTF-8") + "=" + URLEncoder.encode(this.isPrivate ? "1" : "0", "UTF-8"); - encData += "&" + URLEncoder.encode("api_paste_format", "UTF-8") + "=" + URLEncoder.encode("yaml", "UTF-8"); - return encData; + return URLEncoder.encode("api_dev_key", "UTF-8") + "=" + URLEncoder.encode("d61d68d31e8e0392b59b50b277411c71", "UTF-8") + + "&" + URLEncoder.encode("api_option", "UTF-8") + "=" + URLEncoder.encode("paste", "UTF-8") + + "&" + URLEncoder.encode("api_paste_code", "UTF-8") + "=" + URLEncoder.encode(data, "UTF-8") + + "&" + URLEncoder.encode("api_paste_private", "UTF-8") + "=" + URLEncoder.encode(this.isPrivate ? "1" : "0", "UTF-8") + + "&" + URLEncoder.encode("api_paste_format", "UTF-8") + "=" + URLEncoder.encode("yaml", "UTF-8"); } catch (UnsupportedEncodingException e) { return ""; // should never hit here } From e821611744208ec90a787ed380e8428c8a5632d7 Mon Sep 17 00:00:00 2001 From: Kermina Awad Date: Sat, 6 Jun 2020 20:05:33 -0400 Subject: [PATCH 095/134] fix pasting to hastebin --- .../utils/webpaste/HastebinPasteService.java | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HastebinPasteService.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HastebinPasteService.java index 590c521e3..407ec354b 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HastebinPasteService.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HastebinPasteService.java @@ -9,6 +9,7 @@ import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; +import java.nio.charset.StandardCharsets; import java.util.Map; /** @@ -43,14 +44,19 @@ public String postData(String encodedData, URL url) throws PasteFailedException URLConnection conn = url.openConnection(); conn.setDoOutput(true); - wr = new OutputStreamWriter(conn.getOutputStream()); - rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); + // hastebin needs a user-agent + conn.addRequestProperty("User-Agent", "placeholder"); + // this isn't required, but is technically correct + conn.addRequestProperty("Content-Type", "text/plain; charset=utf-8"); + wr = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8.newEncoder()); wr.write(encodedData); wr.flush(); String line; StringBuilder responseString = new StringBuilder(); + // this has to be initialized AFTER the data has been flushed! + rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)); while ((line = rd.readLine()) != null) { responseString.append(line); } From 676c3a2e3d338c1789172f57edb804ac353ff057 Mon Sep 17 00:00:00 2001 From: Kermina Awad Date: Sat, 6 Jun 2020 20:16:42 -0400 Subject: [PATCH 096/134] make pasting more system agnostic --- ...ithubPasteService.java => GitHubPasteService.java} | 11 ++++++++--- .../MultiverseCore/utils/webpaste/HttpAPIClient.java | 5 +++-- .../utils/webpaste/PastebinPasteService.java | 10 ++++++++-- 3 files changed, 19 insertions(+), 7 deletions(-) rename src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/{GithubPasteService.java => GitHubPasteService.java} (88%) diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/GithubPasteService.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/GitHubPasteService.java similarity index 88% rename from src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/GithubPasteService.java rename to src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/GitHubPasteService.java index fe7fafc4e..f098e2957 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/GithubPasteService.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/GitHubPasteService.java @@ -11,6 +11,7 @@ import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; +import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; @@ -64,14 +65,18 @@ public String postData(String encodedData, URL url) throws PasteFailedException try { URLConnection conn = url.openConnection(); conn.setDoOutput(true); - wr = new OutputStreamWriter(conn.getOutputStream()); + + // this isn't required, but is technically correct + conn.addRequestProperty("Content-Type", "application/json; charset=utf-8"); + + wr = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8); wr.write(encodedData); wr.flush(); - rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; StringBuilder responseString = new StringBuilder(); - + // this has to be initialized AFTER the data has been flushed! + rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)); while ((line = rd.readLine()) != null) { responseString.append(line); } diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HttpAPIClient.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HttpAPIClient.java index 55d69c5c0..962fa3564 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HttpAPIClient.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HttpAPIClient.java @@ -5,6 +5,7 @@ import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; +import java.nio.charset.StandardCharsets; /** * HTTP API-client. @@ -32,11 +33,11 @@ protected final String exec(Object... args) throws IOException { StringBuilder ret = new StringBuilder(); BufferedReader reader = null; try { - reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); + reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)); while (!reader.ready()); // wait until reader is ready, may not be necessary, SUPPRESS CHECKSTYLE: EmptyStatement while (reader.ready()) { - ret.append(reader.readLine()).append('\n'); + ret.append(reader.readLine()).append(System.lineSeparator()); } } finally { if (reader != null) { diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PastebinPasteService.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PastebinPasteService.java index 7aeba7979..c370c1d24 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PastebinPasteService.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PastebinPasteService.java @@ -9,6 +9,7 @@ import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.util.Map; /** @@ -65,13 +66,18 @@ public String postData(String encodedData, URL url) throws PasteFailedException try { URLConnection conn = url.openConnection(); conn.setDoOutput(true); - wr = new OutputStreamWriter(conn.getOutputStream()); + + // this isn't required, but is technically correct + conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); + + wr = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8); wr.write(encodedData); wr.flush(); - rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; String pastebinUrl = ""; + // this has to be initialized AFTER the data has been flushed! + rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)); while ((line = rd.readLine()) != null) { pastebinUrl = line; } From e17e9c8ce9658ae5b88ceb272be319e3ab77fc38 Mon Sep 17 00:00:00 2001 From: Kermina Awad Date: Sat, 6 Jun 2020 20:17:05 -0400 Subject: [PATCH 097/134] rename GithubPasteService as GitHubPasteService --- .../MultiverseCore/utils/webpaste/GitHubPasteService.java | 4 ++-- .../MultiverseCore/utils/webpaste/PasteServiceFactory.java | 2 +- .../MultiverseCore/utils/webpaste/PasteServiceType.java | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/GitHubPasteService.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/GitHubPasteService.java index f098e2957..6c0b98908 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/GitHubPasteService.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/GitHubPasteService.java @@ -15,11 +15,11 @@ import java.util.HashMap; import java.util.Map; -public class GithubPasteService implements PasteService { +public class GitHubPasteService implements PasteService { private final boolean isPrivate; - public GithubPasteService(boolean isPrivate) { + public GitHubPasteService(boolean isPrivate) { this.isPrivate = isPrivate; } diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceFactory.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceFactory.java index df4fb8315..2275dc580 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceFactory.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceFactory.java @@ -19,7 +19,7 @@ public static PasteService getService(PasteServiceType type, boolean isPrivate) case HASTEBIN: return new HastebinPasteService(); case GITHUB: - return new GithubPasteService(isPrivate); + return new GitHubPasteService(isPrivate); default: return null; } diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceType.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceType.java index 0bd93e635..6b6d7a48d 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceType.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceType.java @@ -16,7 +16,7 @@ public enum PasteServiceType { */ HASTEBIN, /** - * @see GithubPasteService + * @see GitHubPasteService */ GITHUB } From 343695e23e0200f7cb12b781247a9fbdfc6feb07 Mon Sep 17 00:00:00 2001 From: Kermina Awad Date: Sat, 6 Jun 2020 20:20:54 -0400 Subject: [PATCH 098/134] add notice as to why pasting to GitHub is disabled --- .../MultiverseCore/commands/VersionCommand.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java index 146d91ee2..ef6eabed8 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java @@ -174,7 +174,15 @@ public void run() { if (CommandHandler.hasFlag("-b", args)) { // private post to pastebin pasteUrl = postToService(PasteServiceType.PASTEBIN, true, data, files); - } else if (CommandHandler.hasFlag("-h", args)) { + } + + // pasting to GitHub now requires an account, so we've disabled it + /* else if (CommandHandler.hasFlag("-g", args)) { + // private post to github + pasteUrl = postToService(PasteServiceType.GITHUB, true, data, files); + } */ + + else if (CommandHandler.hasFlag("-h", args)) { // private post to hastebin pasteUrl = postToService(PasteServiceType.HASTEBIN, true, data, files); } else { From a53c4214f09b8810b5d7886527381ae196b2e2bd Mon Sep 17 00:00:00 2001 From: Kermina Awad Date: Sat, 6 Jun 2020 20:23:25 -0400 Subject: [PATCH 099/134] add extra space for readability --- .../commands/VersionCommand.java | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java index ef6eabed8..9d9f78ced 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java @@ -60,16 +60,16 @@ private String getLegacyString() { "[Multiverse-Core] Economy being used: " + plugin.getEconomist().getEconomyName() + System.lineSeparator() + "[Multiverse-Core] Permissions Plugin: " + this.plugin.getMVPerms().getType() + System.lineSeparator() + "[Multiverse-Core] Dumping Config Values: (version " + this.plugin.getMVConfig().getVersion() + ")" + System.lineSeparator() + - "[Multiverse-Core] messagecooldown: " + plugin.getMessaging().getCooldown() + System.lineSeparator() + - "[Multiverse-Core] teleportcooldown: " + plugin.getMVConfig().getTeleportCooldown() + System.lineSeparator() + - "[Multiverse-Core] worldnameprefix: " + plugin.getMVConfig().getPrefixChat() + System.lineSeparator() + - "[Multiverse-Core] worldnameprefixFormat: " + plugin.getMVConfig().getPrefixChatFormat() + System.lineSeparator() + - "[Multiverse-Core] enforceaccess: " + plugin.getMVConfig().getEnforceAccess() + System.lineSeparator() + - "[Multiverse-Core] displaypermerrors: " + plugin.getMVConfig().getDisplayPermErrors() + System.lineSeparator() + - "[Multiverse-Core] teleportintercept: " + plugin.getMVConfig().getTeleportIntercept() + System.lineSeparator() + - "[Multiverse-Core] firstspawnoverride: " + plugin.getMVConfig().getFirstSpawnOverride() + System.lineSeparator() + - "[Multiverse-Core] firstspawnworld: " + plugin.getMVConfig().getFirstSpawnWorld() + System.lineSeparator() + - "[Multiverse-Core] debug: " + plugin.getMVConfig().getGlobalDebug() + System.lineSeparator() + + "[Multiverse-Core] messagecooldown: " + plugin.getMessaging().getCooldown() + System.lineSeparator() + + "[Multiverse-Core] teleportcooldown: " + plugin.getMVConfig().getTeleportCooldown() + System.lineSeparator() + + "[Multiverse-Core] worldnameprefix: " + plugin.getMVConfig().getPrefixChat() + System.lineSeparator() + + "[Multiverse-Core] worldnameprefixFormat: " + plugin.getMVConfig().getPrefixChatFormat() + System.lineSeparator() + + "[Multiverse-Core] enforceaccess: " + plugin.getMVConfig().getEnforceAccess() + System.lineSeparator() + + "[Multiverse-Core] displaypermerrors: " + plugin.getMVConfig().getDisplayPermErrors() + System.lineSeparator() + + "[Multiverse-Core] teleportintercept: " + plugin.getMVConfig().getTeleportIntercept() + System.lineSeparator() + + "[Multiverse-Core] firstspawnoverride: " + plugin.getMVConfig().getFirstSpawnOverride() + System.lineSeparator() + + "[Multiverse-Core] firstspawnworld: " + plugin.getMVConfig().getFirstSpawnWorld() + System.lineSeparator() + + "[Multiverse-Core] debug: " + plugin.getMVConfig().getGlobalDebug() + System.lineSeparator() + "[Multiverse-Core] Special Code: FRN002" + System.lineSeparator(); } From b9267a3dfc099230db7a2a40c54891963d794e38 Mon Sep 17 00:00:00 2001 From: Kermina Awad Date: Sat, 6 Jun 2020 20:25:12 -0400 Subject: [PATCH 100/134] update version command description --- .../onarandombox/MultiverseCore/commands/VersionCommand.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java index 9d9f78ced..f8435d730 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java @@ -49,7 +49,7 @@ public VersionCommand(MultiverseCore plugin) { this.addKey("mvv"); this.addKey("mvversion"); this.setPermission("multiverse.core.version", - "Dumps version info to the console, optionally to pastie.org with -p or pastebin.com with a -b.", PermissionDefault.TRUE); + "Dumps version info to the console, optionally to pastebin.com with -b, or to hastebin.com using -h.", PermissionDefault.TRUE); } private String getLegacyString() { From 4f41b7aa6e3fb24f20e3f76fa032ffcb9b498ec6 Mon Sep 17 00:00:00 2001 From: Kermina Awad Date: Tue, 9 Jun 2020 14:20:53 -0400 Subject: [PATCH 101/134] rework webpaste package --- pom.xml | 53 +++++++-- .../commands/VersionCommand.java | 26 +++-- .../utils/webpaste/BitlyURLShortener.java | 46 +++++--- .../utils/webpaste/GitHubPasteService.java | 92 +++++----------- .../utils/webpaste/HastebinPasteService.java | 74 +++++-------- .../utils/webpaste/HttpAPIClient.java | 102 ++++++++++++++---- .../utils/webpaste/PasteService.java | 42 +++----- .../utils/webpaste/PastebinPasteService.java | 86 +++++---------- .../utils/webpaste/URLShortener.java | 10 +- .../utils/webpaste/URLShortenerFactory.java | 23 ++++ .../utils/webpaste/URLShortenerType.java | 14 +++ 11 files changed, 311 insertions(+), 257 deletions(-) create mode 100644 src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/URLShortenerFactory.java create mode 100644 src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/URLShortenerType.java diff --git a/pom.xml b/pom.xml index 0949061fc..9c04f1e21 100644 --- a/pom.xml +++ b/pom.xml @@ -9,6 +9,7 @@ UTF-8 UNKNOWN + bitly-access-token @@ -69,6 +70,17 @@ ${env.BUILD_NUMBER} + + bitly + + + env.BITLY_ACCESS_TOKEN + + + + ${env.BITLY_ACCESS_TOKEN} + + @@ -90,21 +102,44 @@ 1.4.1 + replace-bitly-access-token + generate-sources + + replace + + + ${project.build.sourceDirectory} + + com/onarandombox/MultiverseCore/utils/webpaste/BitlyURLShortener.java + + + + bitly-access-token + ${project.bitly-access-token} + + + + + + replace-maven-version-number prepare-package replace + + ${project.build.directory}/classes + + plugin.yml + + + + maven-version-number + ${project.version}-b${project.build.number} + + + - - target/classes/plugin.yml - - - maven-version-number - ${project.version}-b${project.build.number} - - - diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java index f8435d730..c2665ca62 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java @@ -10,12 +10,13 @@ import com.dumptruckman.minecraft.util.Logging; import com.onarandombox.MultiverseCore.MultiverseCore; import com.onarandombox.MultiverseCore.event.MVVersionEvent; -import com.onarandombox.MultiverseCore.utils.webpaste.BitlyURLShortener; import com.onarandombox.MultiverseCore.utils.webpaste.PasteFailedException; import com.onarandombox.MultiverseCore.utils.webpaste.PasteService; import com.onarandombox.MultiverseCore.utils.webpaste.PasteServiceFactory; import com.onarandombox.MultiverseCore.utils.webpaste.PasteServiceType; import com.onarandombox.MultiverseCore.utils.webpaste.URLShortener; +import com.onarandombox.MultiverseCore.utils.webpaste.URLShortenerFactory; +import com.onarandombox.MultiverseCore.utils.webpaste.URLShortenerType; import com.pneumaticraft.commandhandler.CommandHandler; import org.apache.commons.lang.StringUtils; import org.bukkit.ChatColor; @@ -38,7 +39,7 @@ * Dumps version info to the console. */ public class VersionCommand extends MultiverseCommand { - private static final URLShortener SHORTENER = new BitlyURLShortener(); + private static final URLShortener SHORTENER = URLShortenerFactory.getService(URLShortenerType.BITLY); public VersionCommand(MultiverseCore plugin) { super(plugin); @@ -174,15 +175,10 @@ public void run() { if (CommandHandler.hasFlag("-b", args)) { // private post to pastebin pasteUrl = postToService(PasteServiceType.PASTEBIN, true, data, files); - } - - // pasting to GitHub now requires an account, so we've disabled it - /* else if (CommandHandler.hasFlag("-g", args)) { + } else if (CommandHandler.hasFlag("-g", args)) { // private post to github pasteUrl = postToService(PasteServiceType.GITHUB, true, data, files); - } */ - - else if (CommandHandler.hasFlag("-h", args)) { + } else if (CommandHandler.hasFlag("-h", args)) { // private post to hastebin pasteUrl = postToService(PasteServiceType.HASTEBIN, true, data, files); } else { @@ -210,17 +206,19 @@ else if (CommandHandler.hasFlag("-h", args)) { * @param pasteFiles Map of filenames/contents of debug info. * @return URL of visible paste */ - private static String postToService(PasteServiceType type, boolean isPrivate, String pasteData, - Map pasteFiles) { + private static String postToService(PasteServiceType type, boolean isPrivate, String pasteData, Map pasteFiles) { PasteService ps = PasteServiceFactory.getService(type, isPrivate); + try { String result; if (ps.supportsMultiFile()) { - result = ps.postData(ps.encodeData(pasteFiles), ps.getPostURL()); + result = ps.postData(pasteFiles); } else { - result = ps.postData(ps.encodeData(pasteData), ps.getPostURL()); + result = ps.postData(pasteData); } - return SHORTENER.shorten(result); + + if (SHORTENER != null) return SHORTENER.shorten(result); + return result; } catch (PasteFailedException e) { e.printStackTrace(); return "Error posting to service."; diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/BitlyURLShortener.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/BitlyURLShortener.java index ea52cbccd..882c37906 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/BitlyURLShortener.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/BitlyURLShortener.java @@ -1,19 +1,41 @@ package com.onarandombox.MultiverseCore.utils.webpaste; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + import java.io.IOException; +import java.util.Map; /** * An {@link URLShortener} using {@code bit.ly}. */ -public class BitlyURLShortener extends HttpAPIClient implements URLShortener { - private static final String GENERIC_BITLY_REQUEST_FORMAT = "https://api-ssl.bitly.com/v3/shorten?format=txt&apiKey=%s&login=%s&longUrl=%s"; - - // I think it's no problem that these are public - private static final String USERNAME = "multiverse2"; - private static final String API_KEY = "R_9dbff4862a3bc0c4218a7d78cc10d0e0"; +class BitlyURLShortener extends URLShortener { + private static final String ACCESS_TOKEN = "Bearer bitly-access-token"; + private static final String BITLY_POST_REQUEST = "https://api-ssl.bitly.com/v4/shorten"; public BitlyURLShortener() { - super(String.format(GENERIC_BITLY_REQUEST_FORMAT, API_KEY, USERNAME, "%s")); + super(BITLY_POST_REQUEST, ACCESS_TOKEN); + if (ACCESS_TOKEN.endsWith("access-token")) throw new UnsupportedOperationException(); + } + + /** + * {@inheritDoc} + */ + @Override + protected String encodeData(String data) { + JSONObject json = new JSONObject(); + json.put("domain", "j.mp"); + json.put("long_url", data); + return json.toJSONString(); + } + + /** + * {@inheritDoc} + */ + @Override + protected String encodeData(Map data) { + throw new UnsupportedOperationException(); } /** @@ -22,13 +44,11 @@ public BitlyURLShortener() { @Override public String shorten(String longUrl) { try { - String result = this.exec(longUrl); - if (!result.startsWith("https://j.mp/")) // ... then it's failed :/ - throw new IOException(result); - return result; - } catch (IOException e) { + String stringJSON = this.exec(encodeData(longUrl), ContentType.JSON); + return (String) ((JSONObject) new JSONParser().parse(stringJSON)).get("link"); + } catch (IOException | ParseException e) { e.printStackTrace(); - return longUrl; // sorry ... + return longUrl; } } } diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/GitHubPasteService.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/GitHubPasteService.java index 6c0b98908..0370a7ca0 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/GitHubPasteService.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/GitHubPasteService.java @@ -1,26 +1,23 @@ package com.onarandombox.MultiverseCore.utils.webpaste; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.google.gson.JsonPrimitive; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; -import java.io.BufferedReader; import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; -import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; -public class GitHubPasteService implements PasteService { - +public class GitHubPasteService extends PasteService { private final boolean isPrivate; + // this access token must have the "gist" OAuth scope + private static final String ACCESS_TOKEN = "token github-access-token"; + private static final String GITHUB_POST_REQUEST = "https://api.github.com/gists"; public GitHubPasteService(boolean isPrivate) { + super(GITHUB_POST_REQUEST, ACCESS_TOKEN); this.isPrivate = isPrivate; + if (ACCESS_TOKEN.endsWith("access-token")) throw new UnsupportedOperationException(); } @Override @@ -32,68 +29,37 @@ public String encodeData(String data) { @Override public String encodeData(Map files) { - JsonObject root = new JsonObject(); - root.add("description", new JsonPrimitive("Multiverse-Core Debug Info")); - root.add("public", new JsonPrimitive(!this.isPrivate)); - JsonObject fileList = new JsonObject(); - for (Map.Entry entry : files.entrySet()) - { - JsonObject fileObject = new JsonObject(); - fileObject.add("content", new JsonPrimitive(entry.getValue())); - fileList.add(entry.getKey(), fileObject); + JSONObject root = new JSONObject(); + root.put("description", "Multiverse-Core Debug Info"); + root.put("public", !this.isPrivate); + JSONObject fileList = new JSONObject(); + for (Map.Entry entry : files.entrySet()) { + JSONObject fileObject = new JSONObject(); + fileObject.put("content", entry.getValue()); + fileList.put(entry.getKey(), fileObject); } - root.add("files", fileList); - return root.toString(); + + root.put("files", fileList); + return root.toJSONString(); } @Override - public URL getPostURL() { + public String postData(String data) throws PasteFailedException { try { - return new URL("https://api.github.com/gists"); - - // the following can be used for testing purposes - // return new URL("http://jsonplaceholder.typicode.com/posts"); - } catch (MalformedURLException e) { - return null; // should never hit here + String stringJSON = this.exec(encodeData(data), ContentType.JSON); + return (String) ((JSONObject) new JSONParser().parse(stringJSON)).get("html_url"); + } catch (IOException | ParseException e) { + throw new PasteFailedException(e); } } @Override - public String postData(String encodedData, URL url) throws PasteFailedException { - OutputStreamWriter wr = null; - BufferedReader rd = null; + public String postData(Map data) throws PasteFailedException { try { - URLConnection conn = url.openConnection(); - conn.setDoOutput(true); - - // this isn't required, but is technically correct - conn.addRequestProperty("Content-Type", "application/json; charset=utf-8"); - - wr = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8); - wr.write(encodedData); - wr.flush(); - - String line; - StringBuilder responseString = new StringBuilder(); - // this has to be initialized AFTER the data has been flushed! - rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)); - while ((line = rd.readLine()) != null) { - responseString.append(line); - } - return new JsonParser().parse(responseString.toString()).getAsJsonObject().get("html_url").getAsString(); - } catch (Exception e) { + String stringJSON = this.exec(encodeData(data), ContentType.JSON); + return (String) ((JSONObject) new JSONParser().parse(stringJSON)).get("html_url"); + } catch (IOException | ParseException e) { throw new PasteFailedException(e); - } finally { - if (wr != null) { - try { - wr.close(); - } catch (IOException ignore) { } - } - if (rd != null) { - try { - rd.close(); - } catch (IOException ignore) { } - } } } diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HastebinPasteService.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HastebinPasteService.java index 407ec354b..c77e1f7bc 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HastebinPasteService.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HastebinPasteService.java @@ -1,81 +1,55 @@ package com.onarandombox.MultiverseCore.utils.webpaste; -import com.google.gson.JsonParser; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; -import java.io.BufferedReader; import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; -import java.nio.charset.StandardCharsets; import java.util.Map; /** * Pastes to {@code hastebin.com}. */ -public class HastebinPasteService implements PasteService { +class HastebinPasteService extends PasteService { + private static final String HASTEBIN_POST_REQUEST = "https://hastebin.com/documents"; + public HastebinPasteService() { + super(HASTEBIN_POST_REQUEST, null); + } + + /** + * {@inheritDoc} + */ @Override public String encodeData(String data) { return data; } + /** + * {@inheritDoc} + */ @Override public String encodeData(Map data) { throw new UnsupportedOperationException(); } @Override - public URL getPostURL() { + public String postData(String data) throws PasteFailedException { try { - return new URL("https://hastebin.com/documents"); - } catch (MalformedURLException e) { - return null; // should never hit here + String stringJSON = this.exec(encodeData(data), ContentType.PLAINTEXT); + return "https://hastebin.com/" + ((JSONObject) new JSONParser().parse(stringJSON)).get("key"); + } catch (IOException | ParseException e) { + throw new PasteFailedException(e); } } @Override - public String postData(String encodedData, URL url) throws PasteFailedException { - OutputStreamWriter wr = null; - BufferedReader rd = null; + public String postData(Map data) throws PasteFailedException { try { - URLConnection conn = url.openConnection(); - conn.setDoOutput(true); - - // hastebin needs a user-agent - conn.addRequestProperty("User-Agent", "placeholder"); - // this isn't required, but is technically correct - conn.addRequestProperty("Content-Type", "text/plain; charset=utf-8"); - - wr = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8.newEncoder()); - wr.write(encodedData); - wr.flush(); - - String line; - StringBuilder responseString = new StringBuilder(); - // this has to be initialized AFTER the data has been flushed! - rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)); - while ((line = rd.readLine()) != null) { - responseString.append(line); - } - String key = new JsonParser().parse(responseString.toString()).getAsJsonObject().get("key").getAsString(); - - return "https://hastebin.com/" + key; - } catch (Exception e) { + String stringJSON = this.exec(encodeData(data), ContentType.PLAINTEXT); + return "https://hastebin.com/" + ((JSONObject) new JSONParser().parse(stringJSON)).get("key"); + } catch (IOException | ParseException e) { throw new PasteFailedException(e); - } finally { - if (wr != null) { - try { - wr.close(); - } catch (IOException ignore) { } - } - if (rd != null) { - try { - rd.close(); - } catch (IOException ignore) { } - } } } diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HttpAPIClient.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HttpAPIClient.java index 962fa3564..c8c4b2bfc 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HttpAPIClient.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HttpAPIClient.java @@ -1,51 +1,115 @@ package com.onarandombox.MultiverseCore.utils.webpaste; +import javax.net.ssl.HttpsURLConnection; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; +import java.io.OutputStreamWriter; import java.net.URL; -import java.net.URLConnection; import java.nio.charset.StandardCharsets; +import java.util.Map; /** * HTTP API-client. */ public abstract class HttpAPIClient { /** - * The URL for this API-request. + * The URL for this API-request, and if necessary, the access token. + * If an access token is not necessary, it should be set to null. */ - protected final String urlFormat; + private final String url; + private final String accessToken; - public HttpAPIClient(String urlFormat) { - this.urlFormat = urlFormat; + /** + * Types of data that can be sent. + */ + protected enum ContentType { + JSON, + PLAINTEXT, + URLENCODED + } + + public HttpAPIClient(String url, String accessToken) { + this.url = url; + this.accessToken = accessToken; + } + + private String getContentHeader(ContentType type) { + switch (type) { + case JSON: + return "application/json; charset=utf-8"; + case PLAINTEXT: + return "text/plain; charset=utf-8"; + case URLENCODED: + return "application/x-www-form-urlencoded; charset=utf-8"; + default: + throw new IllegalStateException("Unexpected value: " + type); + } } + /** + * Encode the given String data into a format suitable for transmission in an HTTP request. + * + * @param data The raw data to encode. + * @return A URL-encoded string. + */ + protected abstract String encodeData(String data); + + /** + * Encode the given Map data into a format suitable for transmission in an HTTP request. + * + * @param data The raw data to encode. + * @return A URL-encoded string. + */ + protected abstract String encodeData(Map data); + /** * Executes this API-Request. - * @param args Format-args. + * @param payload The data that will be sent. + * @param type The type of data that will be sent. * @return The result (as text). * @throws IOException When the I/O-operation failed. */ - protected final String exec(Object... args) throws IOException { + protected final String exec(String payload, ContentType type) throws IOException { + BufferedReader rd = null; + OutputStreamWriter wr = null; - URLConnection conn = new URL(String.format(this.urlFormat, args)).openConnection(); - conn.connect(); - StringBuilder ret = new StringBuilder(); - BufferedReader reader = null; try { - reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)); - while (!reader.ready()); // wait until reader is ready, may not be necessary, SUPPRESS CHECKSTYLE: EmptyStatement + HttpsURLConnection conn = (HttpsURLConnection) new URL(this.url).openConnection(); + conn.setRequestMethod("POST"); + conn.setDoOutput(true); - while (reader.ready()) { - ret.append(reader.readLine()).append(System.lineSeparator()); - } + // we can receive anything! + conn.addRequestProperty("Accept", "*/*"); + // set a dummy User-Agent + conn.addRequestProperty("User-Agent", "placeholder"); + // this isn't required, but is technically correct + conn.addRequestProperty("Content-Type", getContentHeader(type)); + // only some API requests require an access token + if (this.accessToken != null) conn.addRequestProperty("Authorization", this.accessToken); + + wr = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8.newEncoder()); + wr.write(payload); + wr.flush(); + + String line; + StringBuilder responseString = new StringBuilder(); + // this has to be initialized AFTER the data has been flushed! + rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)); + + while ((line = rd.readLine()) != null) responseString.append(line); + return responseString.toString(); } finally { - if (reader != null) { + if (wr != null) { + try { + wr.close(); + } catch (IOException ignore) { } + } + if (rd != null) { try { - reader.close(); + rd.close(); } catch (IOException ignore) { } } } - return ret.toString(); } } diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteService.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteService.java index 403f5ab83..1b3830eac 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteService.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteService.java @@ -1,6 +1,5 @@ package com.onarandombox.MultiverseCore.utils.webpaste; -import java.net.URL; import java.util.Map; /** @@ -15,41 +14,30 @@ * should implement a custom constructor that specifies which kind the PasteService * instance is submitting; an example of this is the PastebinPasteService class. */ -public interface PasteService { +public abstract class PasteService extends HttpAPIClient { + public PasteService(String url, String accessToken) { + super(url, accessToken); + } /** - * Encode the given String data into a format suitable for transmission in an HTTP request. + * Post data to the Web. * - * @param data The raw data to encode. - * @return A URL-encoded string. - */ - String encodeData(String data); - - /** - * Encode the given Map data into a format suitable for transmission in an HTTP request. - * - * @param data The raw data to encode. - * @return A URL-encoded string. - */ - String encodeData(Map data); - - /** - * Get the URL to which this paste service sends new pastes. - * - * @return The URL that will be accessed to complete the paste. + * @param data A URL-encoded String containing the full request to post to + * the given URL. Can be the result of calling #encodeData(). + * @throws PasteFailedException When pasting/posting the data failed. + * @return The URL at which the new paste is visible. */ - URL getPostURL(); + public abstract String postData(String data) throws PasteFailedException; /** - * Post encoded data to the Web. + * Post data to the Web. * - * @param encodedData A URL-encoded String containing the full request to post to - * the given URL. Can be the result of calling #encodeData(). - * @param url The URL to which to paste. Can be the result of calling #getPostURL(). + * @param data A URL-encoded Map containing the full request to post to + * the given URL. Can be the result of calling #encodeData(). * @throws PasteFailedException When pasting/posting the data failed. * @return The URL at which the new paste is visible. */ - String postData(String encodedData, URL url) throws PasteFailedException; + public abstract String postData(Map data) throws PasteFailedException; /** * Does this service support uploading multiple files. @@ -59,5 +47,5 @@ public interface PasteService { * * @return True if this service supports multiple file upload. */ - boolean supportsMultiFile(); + public abstract boolean supportsMultiFile(); } diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PastebinPasteService.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PastebinPasteService.java index c370c1d24..85af5a473 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PastebinPasteService.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PastebinPasteService.java @@ -1,40 +1,22 @@ package com.onarandombox.MultiverseCore.utils.webpaste; -import java.io.BufferedReader; import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; import java.util.Map; /** * Pastes to {@code pastebin.com}. */ -public class PastebinPasteService implements PasteService { - - private boolean isPrivate; +class PastebinPasteService extends PasteService { + private final boolean isPrivate; + private static final String PASTEBIN_POST_REQUEST = "https://pastebin.com/api/api_post.php"; public PastebinPasteService(boolean isPrivate) { + super(PASTEBIN_POST_REQUEST, null); this.isPrivate = isPrivate; } - /** - * {@inheritDoc} - */ - @Override - public URL getPostURL() { - try { - return new URL("http://pastebin.com/api/api_post.php"); - } catch (MalformedURLException e) { - return null; // should never hit here - } - } - /** * {@inheritDoc} */ @@ -42,59 +24,45 @@ public URL getPostURL() { public String encodeData(String data) { try { return URLEncoder.encode("api_dev_key", "UTF-8") + "=" + URLEncoder.encode("d61d68d31e8e0392b59b50b277411c71", "UTF-8") + - "&" + URLEncoder.encode("api_option", "UTF-8") + "=" + URLEncoder.encode("paste", "UTF-8") + - "&" + URLEncoder.encode("api_paste_code", "UTF-8") + "=" + URLEncoder.encode(data, "UTF-8") + - "&" + URLEncoder.encode("api_paste_private", "UTF-8") + "=" + URLEncoder.encode(this.isPrivate ? "1" : "0", "UTF-8") + - "&" + URLEncoder.encode("api_paste_format", "UTF-8") + "=" + URLEncoder.encode("yaml", "UTF-8"); + "&" + URLEncoder.encode("api_option", "UTF-8") + "=" + URLEncoder.encode("paste", "UTF-8") + + "&" + URLEncoder.encode("api_paste_code", "UTF-8") + "=" + URLEncoder.encode(data, "UTF-8") + + "&" + URLEncoder.encode("api_paste_private", "UTF-8") + "=" + URLEncoder.encode(this.isPrivate ? "1" : "0", "UTF-8") + + "&" + URLEncoder.encode("api_paste_format", "UTF-8") + "=" + URLEncoder.encode("yaml", "UTF-8") + + "&" + URLEncoder.encode("api_paste_name", "UTF-8") + "=" + URLEncoder.encode("Multiverse-Core Debug Info", "UTF-8"); } catch (UnsupportedEncodingException e) { return ""; // should never hit here } } + /** + * {@inheritDoc} + */ @Override public String encodeData(Map data) { - return null; + throw new UnsupportedOperationException(); } /** * {@inheritDoc} */ @Override - public String postData(String encodedData, URL url) throws PasteFailedException { - OutputStreamWriter wr = null; - BufferedReader rd = null; + public String postData(String data) throws PasteFailedException { try { - URLConnection conn = url.openConnection(); - conn.setDoOutput(true); - - // this isn't required, but is technically correct - conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); - - wr = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8); - wr.write(encodedData); - wr.flush(); + return this.exec(encodeData(data), ContentType.URLENCODED); + } catch (IOException e) { + throw new PasteFailedException(e); + } + } - String line; - String pastebinUrl = ""; - // this has to be initialized AFTER the data has been flushed! - rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)); - while ((line = rd.readLine()) != null) { - pastebinUrl = line; - } - return pastebinUrl; - } catch (Exception e) { + /** + * {@inheritDoc} + */ + @Override + public String postData(Map data) throws PasteFailedException { + try { + return this.exec(encodeData(data), ContentType.URLENCODED); + } catch (IOException e) { throw new PasteFailedException(e); - } finally { - if (wr != null) { - try { - wr.close(); - } catch (IOException ignore) { } - } - if (rd != null) { - try { - rd.close(); - } catch (IOException ignore) { } - } } } diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/URLShortener.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/URLShortener.java index 75d50f634..0c6f592ce 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/URLShortener.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/URLShortener.java @@ -3,11 +3,15 @@ /** * URL-Shortener. */ -public interface URLShortener { +public abstract class URLShortener extends HttpAPIClient { + public URLShortener(String url, String accessToken) { + super(url, accessToken); + } + /** - * Shorten an URL. + * Shorten a URL. * @param longUrl The long form. * @return The shortened URL. */ - String shorten(String longUrl); + public abstract String shorten(String longUrl); } diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/URLShortenerFactory.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/URLShortenerFactory.java new file mode 100644 index 000000000..c0f3cafac --- /dev/null +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/URLShortenerFactory.java @@ -0,0 +1,23 @@ +package com.onarandombox.MultiverseCore.utils.webpaste; + +/** + * Used to construct {@link URLShortener}s. + */ +public class URLShortenerFactory { + private URLShortenerFactory() { } + + /** + * Constructs a new {@link URLShortener}. + * @param type The {@link URLShortenerType}. + * @return The newly created {@link URLShortener}. + */ + public static URLShortener getService(URLShortenerType type) { + if (type == URLShortenerType.BITLY) { + try { + return new BitlyURLShortener(); + } catch (UnsupportedOperationException ignored) {} + } + + return null; + } +} \ No newline at end of file diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/URLShortenerType.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/URLShortenerType.java new file mode 100644 index 000000000..d2c809f51 --- /dev/null +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/URLShortenerType.java @@ -0,0 +1,14 @@ +package com.onarandombox.MultiverseCore.utils.webpaste; + +/** + * An enum containing all known {@link URLShortener}s. + * + * @see URLShortener + * @see URLShortenerFactory + */ +public enum URLShortenerType { + /** + * @see BitlyURLShortener + */ + BITLY +} From b4a4519876a440ae19377f527c91f16cd13ae875 Mon Sep 17 00:00:00 2001 From: Kermina Awad Date: Tue, 9 Jun 2020 23:23:42 -0400 Subject: [PATCH 102/134] no need for protected access modifier --- .../MultiverseCore/utils/webpaste/BitlyURLShortener.java | 4 ++-- .../MultiverseCore/utils/webpaste/GitHubPasteService.java | 4 ++-- .../utils/webpaste/HastebinPasteService.java | 4 ++-- .../MultiverseCore/utils/webpaste/HttpAPIClient.java | 8 ++++---- .../utils/webpaste/PastebinPasteService.java | 4 ++-- 5 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/BitlyURLShortener.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/BitlyURLShortener.java index 882c37906..904723441 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/BitlyURLShortener.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/BitlyURLShortener.java @@ -23,7 +23,7 @@ public BitlyURLShortener() { * {@inheritDoc} */ @Override - protected String encodeData(String data) { + String encodeData(String data) { JSONObject json = new JSONObject(); json.put("domain", "j.mp"); json.put("long_url", data); @@ -34,7 +34,7 @@ protected String encodeData(String data) { * {@inheritDoc} */ @Override - protected String encodeData(Map data) { + String encodeData(Map data) { throw new UnsupportedOperationException(); } diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/GitHubPasteService.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/GitHubPasteService.java index 0370a7ca0..32aeaf539 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/GitHubPasteService.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/GitHubPasteService.java @@ -21,14 +21,14 @@ public GitHubPasteService(boolean isPrivate) { } @Override - public String encodeData(String data) { + String encodeData(String data) { Map mapData = new HashMap(); mapData.put("multiverse.txt", data); return this.encodeData(mapData); } @Override - public String encodeData(Map files) { + String encodeData(Map files) { JSONObject root = new JSONObject(); root.put("description", "Multiverse-Core Debug Info"); root.put("public", !this.isPrivate); diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HastebinPasteService.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HastebinPasteService.java index c77e1f7bc..da0dcba8f 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HastebinPasteService.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HastebinPasteService.java @@ -21,7 +21,7 @@ public HastebinPasteService() { * {@inheritDoc} */ @Override - public String encodeData(String data) { + String encodeData(String data) { return data; } @@ -29,7 +29,7 @@ public String encodeData(String data) { * {@inheritDoc} */ @Override - public String encodeData(Map data) { + String encodeData(Map data) { throw new UnsupportedOperationException(); } diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HttpAPIClient.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HttpAPIClient.java index c8c4b2bfc..353565d75 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HttpAPIClient.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HttpAPIClient.java @@ -23,7 +23,7 @@ public abstract class HttpAPIClient { /** * Types of data that can be sent. */ - protected enum ContentType { + enum ContentType { JSON, PLAINTEXT, URLENCODED @@ -53,7 +53,7 @@ private String getContentHeader(ContentType type) { * @param data The raw data to encode. * @return A URL-encoded string. */ - protected abstract String encodeData(String data); + abstract String encodeData(String data); /** * Encode the given Map data into a format suitable for transmission in an HTTP request. @@ -61,7 +61,7 @@ private String getContentHeader(ContentType type) { * @param data The raw data to encode. * @return A URL-encoded string. */ - protected abstract String encodeData(Map data); + abstract String encodeData(Map data); /** * Executes this API-Request. @@ -70,7 +70,7 @@ private String getContentHeader(ContentType type) { * @return The result (as text). * @throws IOException When the I/O-operation failed. */ - protected final String exec(String payload, ContentType type) throws IOException { + final String exec(String payload, ContentType type) throws IOException { BufferedReader rd = null; OutputStreamWriter wr = null; diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PastebinPasteService.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PastebinPasteService.java index 85af5a473..30c346bab 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PastebinPasteService.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PastebinPasteService.java @@ -21,7 +21,7 @@ public PastebinPasteService(boolean isPrivate) { * {@inheritDoc} */ @Override - public String encodeData(String data) { + String encodeData(String data) { try { return URLEncoder.encode("api_dev_key", "UTF-8") + "=" + URLEncoder.encode("d61d68d31e8e0392b59b50b277411c71", "UTF-8") + "&" + URLEncoder.encode("api_option", "UTF-8") + "=" + URLEncoder.encode("paste", "UTF-8") + @@ -38,7 +38,7 @@ public String encodeData(String data) { * {@inheritDoc} */ @Override - public String encodeData(Map data) { + String encodeData(Map data) { throw new UnsupportedOperationException(); } From 707eae92a80ecf7729e22de0b16dcf530ab34a6c Mon Sep 17 00:00:00 2001 From: Kermina Awad Date: Wed, 10 Jun 2020 00:05:22 -0400 Subject: [PATCH 103/134] improve javadocs, also, no need to make implementations public --- .../utils/webpaste/BitlyURLShortener.java | 4 ++-- .../utils/webpaste/GitHubPasteService.java | 24 ++++++++++++++++--- .../utils/webpaste/HastebinPasteService.java | 11 ++++++++- .../utils/webpaste/HttpAPIClient.java | 9 +++++-- .../utils/webpaste/PasteFailedException.java | 2 +- .../utils/webpaste/PasteService.java | 23 ++++++++---------- .../utils/webpaste/PastebinPasteService.java | 5 +++- .../utils/webpaste/URLShortener.java | 10 ++++++-- 8 files changed, 63 insertions(+), 25 deletions(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/BitlyURLShortener.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/BitlyURLShortener.java index 904723441..96fadd226 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/BitlyURLShortener.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/BitlyURLShortener.java @@ -8,13 +8,13 @@ import java.util.Map; /** - * An {@link URLShortener} using {@code bit.ly}. + * A {@link URLShortener} using {@code bit.ly}. Requires an access token. */ class BitlyURLShortener extends URLShortener { private static final String ACCESS_TOKEN = "Bearer bitly-access-token"; private static final String BITLY_POST_REQUEST = "https://api-ssl.bitly.com/v4/shorten"; - public BitlyURLShortener() { + BitlyURLShortener() { super(BITLY_POST_REQUEST, ACCESS_TOKEN); if (ACCESS_TOKEN.endsWith("access-token")) throw new UnsupportedOperationException(); } diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/GitHubPasteService.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/GitHubPasteService.java index 32aeaf539..717ac3c4a 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/GitHubPasteService.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/GitHubPasteService.java @@ -8,18 +8,24 @@ import java.util.HashMap; import java.util.Map; -public class GitHubPasteService extends PasteService { +/** + * Pastes to {@code gist.github.com}. Requires an access token with the {@code gist} scope. + */ +class GitHubPasteService extends PasteService { private final boolean isPrivate; - // this access token must have the "gist" OAuth scope + // this access token must have the "gist" scope private static final String ACCESS_TOKEN = "token github-access-token"; private static final String GITHUB_POST_REQUEST = "https://api.github.com/gists"; - public GitHubPasteService(boolean isPrivate) { + GitHubPasteService(boolean isPrivate) { super(GITHUB_POST_REQUEST, ACCESS_TOKEN); this.isPrivate = isPrivate; if (ACCESS_TOKEN.endsWith("access-token")) throw new UnsupportedOperationException(); } + /** + * {@inheritDoc} + */ @Override String encodeData(String data) { Map mapData = new HashMap(); @@ -27,6 +33,9 @@ String encodeData(String data) { return this.encodeData(mapData); } + /** + * {@inheritDoc} + */ @Override String encodeData(Map files) { JSONObject root = new JSONObject(); @@ -43,6 +52,9 @@ String encodeData(Map files) { return root.toJSONString(); } + /** + * {@inheritDoc} + */ @Override public String postData(String data) throws PasteFailedException { try { @@ -53,6 +65,9 @@ public String postData(String data) throws PasteFailedException { } } + /** + * {@inheritDoc} + */ @Override public String postData(Map data) throws PasteFailedException { try { @@ -63,6 +78,9 @@ public String postData(Map data) throws PasteFailedException { } } + /** + * {@inheritDoc} + */ @Override public boolean supportsMultiFile() { return true; diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HastebinPasteService.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HastebinPasteService.java index da0dcba8f..46af2d29c 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HastebinPasteService.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HastebinPasteService.java @@ -13,7 +13,7 @@ class HastebinPasteService extends PasteService { private static final String HASTEBIN_POST_REQUEST = "https://hastebin.com/documents"; - public HastebinPasteService() { + HastebinPasteService() { super(HASTEBIN_POST_REQUEST, null); } @@ -33,6 +33,9 @@ String encodeData(Map data) { throw new UnsupportedOperationException(); } + /** + * {@inheritDoc} + */ @Override public String postData(String data) throws PasteFailedException { try { @@ -43,6 +46,9 @@ public String postData(String data) throws PasteFailedException { } } + /** + * {@inheritDoc} + */ @Override public String postData(Map data) throws PasteFailedException { try { @@ -53,6 +59,9 @@ public String postData(Map data) throws PasteFailedException { } } + /** + * {@inheritDoc} + */ @Override public boolean supportsMultiFile() { return false; diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HttpAPIClient.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HttpAPIClient.java index 353565d75..8e423fcce 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HttpAPIClient.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/HttpAPIClient.java @@ -12,7 +12,7 @@ /** * HTTP API-client. */ -public abstract class HttpAPIClient { +abstract class HttpAPIClient { /** * The URL for this API-request, and if necessary, the access token. * If an access token is not necessary, it should be set to null. @@ -29,11 +29,16 @@ enum ContentType { URLENCODED } - public HttpAPIClient(String url, String accessToken) { + HttpAPIClient(String url, String accessToken) { this.url = url; this.accessToken = accessToken; } + /** + * Returns the HTTP Content-Type header that corresponds with each ContentType. + * @param type The type of data. + * @return The HTTP Content-Type header that corresponds with the type of data. + */ private String getContentHeader(ContentType type) { switch (type) { case JSON: diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteFailedException.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteFailedException.java index 85a803a4b..82792f499 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteFailedException.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteFailedException.java @@ -1,7 +1,7 @@ package com.onarandombox.MultiverseCore.utils.webpaste; /** - * Thrown when pasting failed. + * Thrown when pasting fails. */ public class PasteFailedException extends Exception { public PasteFailedException() { diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteService.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteService.java index 1b3830eac..0c474c9e8 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteService.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteService.java @@ -3,27 +3,25 @@ import java.util.Map; /** - * An interface to a web-based text-pasting service. Classes implementing this - * interface should implement its methods to send data to an online text-sharing - * service, such as pastebin.com. Conventionally, a paste is accomplished by (given - * some PasteService instance ps): + * An interface to a web-based text-pasting service. Classes extending this + * should implement its methods to send data to an online text-sharing service, + * such as pastebin.com. Given some PasteService instance ps, a paste is accomplished by: * - * {@code ps.postData(ps.encodeData(someString), ps.getPostURL());} + * {@code ps.postData(someString);} * * Services that provide a distinction between "public" and "private" pastes - * should implement a custom constructor that specifies which kind the PasteService + * should implement a constructor that specifies which kind the PasteService * instance is submitting; an example of this is the PastebinPasteService class. */ public abstract class PasteService extends HttpAPIClient { - public PasteService(String url, String accessToken) { + PasteService(String url, String accessToken) { super(url, accessToken); } /** * Post data to the Web. * - * @param data A URL-encoded String containing the full request to post to - * the given URL. Can be the result of calling #encodeData(). + * @param data A String to post to the web. * @throws PasteFailedException When pasting/posting the data failed. * @return The URL at which the new paste is visible. */ @@ -32,8 +30,7 @@ public PasteService(String url, String accessToken) { /** * Post data to the Web. * - * @param data A URL-encoded Map containing the full request to post to - * the given URL. Can be the result of calling #encodeData(). + * @param data A Map to post to the web. * @throws PasteFailedException When pasting/posting the data failed. * @return The URL at which the new paste is visible. */ @@ -42,8 +39,8 @@ public PasteService(String url, String accessToken) { /** * Does this service support uploading multiple files. * - * Newer services like gist support multi-file which allows us to upload configs - * in addition to the standard logs. + * Newer services like GitHub's Gist support multi-file pastes, + * which allows us to upload configs in addition to the standard logs. * * @return True if this service supports multiple file upload. */ diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PastebinPasteService.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PastebinPasteService.java index 30c346bab..ce7a44532 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PastebinPasteService.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PastebinPasteService.java @@ -12,7 +12,7 @@ class PastebinPasteService extends PasteService { private final boolean isPrivate; private static final String PASTEBIN_POST_REQUEST = "https://pastebin.com/api/api_post.php"; - public PastebinPasteService(boolean isPrivate) { + PastebinPasteService(boolean isPrivate) { super(PASTEBIN_POST_REQUEST, null); this.isPrivate = isPrivate; } @@ -66,6 +66,9 @@ public String postData(Map data) throws PasteFailedException { } } + /** + * {@inheritDoc} + */ @Override public boolean supportsMultiFile() { return false; diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/URLShortener.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/URLShortener.java index 0c6f592ce..be3d61b18 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/URLShortener.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/URLShortener.java @@ -1,10 +1,16 @@ package com.onarandombox.MultiverseCore.utils.webpaste; /** - * URL-Shortener. + * An interface to a web-based URL Shortener. Classes extending this should + * implement its methods to shorten links using the service. Given some + * URLShortener instance us, a URL is shortened by: + * + * {@code us.shorten(longUrl);} + * + * An example of this, is the BitlyURLShortener. */ public abstract class URLShortener extends HttpAPIClient { - public URLShortener(String url, String accessToken) { + URLShortener(String url, String accessToken) { super(url, accessToken); } From 94ca18e95c5fbfcf9f0f82654a7e72d79928c19a Mon Sep 17 00:00:00 2001 From: Kermina Awad Date: Sat, 13 Jun 2020 14:20:36 -0400 Subject: [PATCH 104/134] correct some metrics --- .../MultiverseCore/utils/metrics/MetricsConfigurator.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/metrics/MetricsConfigurator.java b/src/main/java/com/onarandombox/MultiverseCore/utils/metrics/MetricsConfigurator.java index 25aaf009f..fd3470a60 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/metrics/MetricsConfigurator.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/metrics/MetricsConfigurator.java @@ -8,7 +8,7 @@ import com.onarandombox.MultiverseCore.MultiverseCore; import com.onarandombox.MultiverseCore.api.MVWorldManager; import com.onarandombox.MultiverseCore.api.MultiverseWorld; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.WordUtils; import org.bstats.bukkit.Metrics; import org.bukkit.World; @@ -60,7 +60,8 @@ private void addCustomGeneratorsMetric() { } private String getGeneratorName(MultiverseWorld world) { - return world.getGenerator() != null ? world.getGenerator() : NO_GENERATOR_NAME; + String gen = world.getGenerator(); + return (gen != null && !gen.equalsIgnoreCase("null")) ? gen : NO_GENERATOR_NAME; } private void addEnvironmentsMetric() { @@ -73,7 +74,7 @@ private void addEnvironmentsMetric() { private String titleCaseEnv(World.Environment env) { String envName = env.name().replaceAll("_+", " "); - return StringUtils.capitalize(envName.toLowerCase()); + return WordUtils.capitalizeFully(envName); } private void addWorldCountMetric() { From e01c646562d62c6d533cc84dfe10f3a90351a4e0 Mon Sep 17 00:00:00 2001 From: Kermina Awad Date: Sun, 14 Jun 2020 16:04:17 -0400 Subject: [PATCH 105/134] add paste.gg paste service --- .../commands/VersionCommand.java | 7 +- .../utils/webpaste/PasteGGPasteService.java | 90 +++++++++++++++++++ .../utils/webpaste/PasteServiceFactory.java | 2 + .../utils/webpaste/PasteServiceType.java | 4 + 4 files changed, 101 insertions(+), 2 deletions(-) create mode 100644 src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteGGPasteService.java diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java index c2665ca62..00912846a 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java @@ -44,13 +44,13 @@ public class VersionCommand extends MultiverseCommand { public VersionCommand(MultiverseCore plugin) { super(plugin); this.setName("Multiverse Version"); - this.setCommandUsage("/mv version " + ChatColor.GOLD + "-[bh] [--include-plugin-list]"); + this.setCommandUsage("/mv version " + ChatColor.GOLD + "-[bhp] [--include-plugin-list]"); this.setArgRange(0, 2); this.addKey("mv version"); this.addKey("mvv"); this.addKey("mvversion"); this.setPermission("multiverse.core.version", - "Dumps version info to the console, optionally to pastebin.com with -b, or to hastebin.com using -h.", PermissionDefault.TRUE); + "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() { @@ -181,6 +181,9 @@ public void run() { } else if (CommandHandler.hasFlag("-h", args)) { // private post to hastebin pasteUrl = postToService(PasteServiceType.HASTEBIN, true, data, files); + } else if (CommandHandler.hasFlag("-p", args)) { + // private post to paste.gg + pasteUrl = postToService(PasteServiceType.PASTEGG, true, data, files); } else { return; } diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteGGPasteService.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteGGPasteService.java new file mode 100644 index 000000000..179bba003 --- /dev/null +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteGGPasteService.java @@ -0,0 +1,90 @@ +package com.onarandombox.MultiverseCore.utils.webpaste; + +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +/** + * Pastes to {@code paste.gg}. + */ +class PasteGGPasteService extends PasteService { + private final boolean isPrivate; + private static final String PASTEGG_POST_REQUEST = "https://api.paste.gg/v1/pastes"; + + PasteGGPasteService(boolean isPrivate) { + super(PASTEGG_POST_REQUEST, null); + this.isPrivate = isPrivate; + } + + /** + * {@inheritDoc} + */ + @Override + String encodeData(String data) { + Map mapData = new HashMap(); + mapData.put("multiverse.txt", data); + return this.encodeData(mapData); + } + + /** + * {@inheritDoc} + */ + @Override + String encodeData(Map files) { + JSONObject root = new JSONObject(); + root.put("name", "Multiverse-Core Debug Info"); + root.put("visibility", this.isPrivate ? "unlisted" : "public"); + JSONArray fileList = new JSONArray(); + for (Map.Entry entry : files.entrySet()) { + JSONObject fileObject = new JSONObject(); + JSONObject contentObject = new JSONObject(); + fileObject.put("name", entry.getKey()); + fileObject.put("content", contentObject); + contentObject.put("format", "text"); + contentObject.put("value", entry.getValue()); + fileList.add(fileObject); + } + + root.put("files", fileList); + return root.toJSONString(); + } + + /** + * {@inheritDoc} + */ + @Override + public String postData(String data) throws PasteFailedException { + try { + String stringJSON = this.exec(encodeData(data), ContentType.JSON); + return (String) ((JSONObject) ((JSONObject) new JSONParser().parse(stringJSON)).get("result")).get("id"); + } catch (IOException | ParseException e) { + throw new PasteFailedException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public String postData(Map data) throws PasteFailedException { + try { + String stringJSON = this.exec(encodeData(data), ContentType.JSON); + return "https://paste.gg/" + ((JSONObject) ((JSONObject) new JSONParser().parse(stringJSON)).get("result")).get("id"); + } catch (IOException | ParseException e) { + throw new PasteFailedException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean supportsMultiFile() { + return true; + } +} diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceFactory.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceFactory.java index 2275dc580..f6f63a1ce 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceFactory.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceFactory.java @@ -14,6 +14,8 @@ private PasteServiceFactory() { } */ public static PasteService getService(PasteServiceType type, boolean isPrivate) { switch(type) { + case PASTEGG: + return new PasteGGPasteService(isPrivate); case PASTEBIN: return new PastebinPasteService(isPrivate); case HASTEBIN: diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceType.java b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceType.java index 6b6d7a48d..09424c0b5 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceType.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/webpaste/PasteServiceType.java @@ -7,6 +7,10 @@ * @see PasteServiceFactory */ public enum PasteServiceType { + /** + * @see PasteGGPasteService + */ + PASTEGG, /** * @see PastebinPasteService */ From 058c0837f0455d4a967d18dc22290d145482e701 Mon Sep 17 00:00:00 2001 From: Kermina Awad Date: Sun, 14 Jun 2020 16:04:58 -0400 Subject: [PATCH 106/134] bring multi-file pastes to parity with single file pastes --- .../MultiverseCore/commands/VersionCommand.java | 7 ++++--- .../MultiverseCore/event/MVVersionEvent.java | 9 +++++++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java index 00912846a..3f4b26f52 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java @@ -81,7 +81,7 @@ private String getMarkdownString() { "| --- | --- |" + System.lineSeparator() + "| Multiverse-Core Version | `" + this.plugin.getDescription().getVersion() + "` |" + System.lineSeparator() + "| Bukkit Version | `" + this.plugin.getServer().getVersion() + "` |" + System.lineSeparator() + - //"| Loaded Worlds | `" + this.plugin.getMVWorldManager().getMVWorlds() + "` |" + System.lineSeparator() + + "| Loaded Worlds | `" + this.plugin.getMVWorldManager().getMVWorlds() + "` |" + System.lineSeparator() + "| Multiverse Plugins Loaded | `" + this.plugin.getPluginCount() + "` |" + System.lineSeparator() + "| Economy being used | `" + plugin.getEconomist().getEconomyName() + "` |" + System.lineSeparator() + "| Permissions Plugin | `" + this.plugin.getMVPerms().getType() + "` |" + System.lineSeparator() + @@ -134,7 +134,7 @@ private Map getVersionFiles() { File configFile = new File(this.plugin.getDataFolder(), "config.yml"); files.put(configFile.getName(), this.readFile(configFile.getAbsolutePath())); - // Add the config.yml + // Add the worlds.yml File worldConfig = new File(this.plugin.getDataFolder(), "worlds.yml"); files.put(worldConfig.getName(), this.readFile(worldConfig.getAbsolutePath())); return files; @@ -148,13 +148,14 @@ public void runCommand(final CommandSender sender, final List args) { } MVVersionEvent versionEvent = new MVVersionEvent(this.getLegacyString(), this.getVersionFiles()); - final Map files = this.getVersionFiles(); this.plugin.getServer().getPluginManager().callEvent(versionEvent); String versionInfo = versionEvent.getVersionInfo(); + Map files = versionEvent.getDetailedVersionInfo(); if (CommandHandler.hasFlag("--include-plugin-list", args)) { versionInfo = versionInfo + System.lineSeparator() + "Plugins: " + getPluginList(); + files.put("plugins.txt", "Plugins: " + getPluginList()); } final String data = versionInfo; diff --git a/src/main/java/com/onarandombox/MultiverseCore/event/MVVersionEvent.java b/src/main/java/com/onarandombox/MultiverseCore/event/MVVersionEvent.java index 43c1ddfc1..a63d7020a 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/event/MVVersionEvent.java +++ b/src/main/java/com/onarandombox/MultiverseCore/event/MVVersionEvent.java @@ -66,4 +66,13 @@ public Map getDetailedVersionInfo() { public void appendVersionInfo(String moreVersionInfo) { this.versionInfoBuilder.append(moreVersionInfo); } + + /** + * Adds a file to to the detailed version-info currently saved in this event. + * @param filename The name of the file. + * @param text The file's content. + */ + public void putDetailedVersionInfo(String filename, String text) { + this.detailedVersionInfo.put(filename, text); + } } From d5013546d13c54a9a605bca19b1bf65ab52bcb73 Mon Sep 17 00:00:00 2001 From: Kermina Awad Date: Mon, 29 Jun 2020 11:40:01 -0400 Subject: [PATCH 107/134] don't report generator settings --- .../MultiverseCore/utils/metrics/MetricsConfigurator.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/metrics/MetricsConfigurator.java b/src/main/java/com/onarandombox/MultiverseCore/utils/metrics/MetricsConfigurator.java index fd3470a60..5b34acad2 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/metrics/MetricsConfigurator.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/metrics/MetricsConfigurator.java @@ -61,7 +61,7 @@ private void addCustomGeneratorsMetric() { private String getGeneratorName(MultiverseWorld world) { String gen = world.getGenerator(); - return (gen != null && !gen.equalsIgnoreCase("null")) ? gen : NO_GENERATOR_NAME; + return (gen != null && !gen.equalsIgnoreCase("null")) ? gen.split(":")[0] : NO_GENERATOR_NAME; } private void addEnvironmentsMetric() { From 05cf0522044a7a25254ed84d636a9f15181c76b8 Mon Sep 17 00:00:00 2001 From: benwoo1110 <30431861+benwoo1110@users.noreply.github.com> Date: Thu, 27 Aug 2020 01:34:37 +0800 Subject: [PATCH 108/134] Add GitHub issue templates (#2385) * Added issue templates * Fixed a typo * Added more details to template Added dev build link Need to enter `/server` output Declaration that issue is reproducible with only mv plugins * Added capitalization to issue title --- .github/ISSUE_TEMPLATE/help.md | 53 +++++++++++++++++++ .github/ISSUE_TEMPLATE/report-a-bug.md | 56 +++++++++++++++++++++ .github/ISSUE_TEMPLATE/request-a-feature.md | 51 +++++++++++++++++++ 3 files changed, 160 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/help.md create mode 100644 .github/ISSUE_TEMPLATE/report-a-bug.md create mode 100644 .github/ISSUE_TEMPLATE/request-a-feature.md diff --git a/.github/ISSUE_TEMPLATE/help.md b/.github/ISSUE_TEMPLATE/help.md new file mode 100644 index 000000000..b9aded2f0 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/help.md @@ -0,0 +1,53 @@ +--- +name: Help! +about: Encountered a problem with Multiverse-Core? Not sure how to fix it? + +--- + + + +### Information + +* **Server version:** + +* **Full output of `/mv version -b`:** + +* **Server log:** + +### Help request + +**Problem** + + +**What I have tried** + + +**Screenshots** + \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/report-a-bug.md b/.github/ISSUE_TEMPLATE/report-a-bug.md new file mode 100644 index 000000000..36c8ca05a --- /dev/null +++ b/.github/ISSUE_TEMPLATE/report-a-bug.md @@ -0,0 +1,56 @@ +--- +name: Report a Bug +about: Report an Multiverse-Core bug. Only use this if you're 100% sure it's something wrong with Multiverse-Core - otherwise, try "Help!". + +--- + + + +### Information + +* **Server version:** + +* **Full output of `/mv version -b`:** + +* **Server log:** + +### Details +I was **``** to reproduce my issue on a freshly setup and up-to-date server with the latest version of Multiverse plugins with no other plugins and with no kinds of other server or client mods. + +**Description** + + +**Steps to reproduce** + + +**Expected behavior** + + +**Screenshots** + \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/request-a-feature.md b/.github/ISSUE_TEMPLATE/request-a-feature.md new file mode 100644 index 000000000..28f8fdd94 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/request-a-feature.md @@ -0,0 +1,51 @@ +--- +name: Request a Feature +about: Suggest a feature you want to see in Multiverse-Core! + +--- + + + +### Feature request + +**Feature description** + + +**How the feature is useful** + \ No newline at end of file From e1494808f3b2aa0fd667e339aa35a571aeab2783 Mon Sep 17 00:00:00 2001 From: benwoo1110 <30431861+benwoo1110@users.noreply.github.com> Date: Thu, 27 Aug 2020 20:47:57 +0800 Subject: [PATCH 109/134] Fixed inability to clone due to unable to copy session.lock (#2392) * Added ability to exclude files when copying folders * Remove wildcard imports * Added unit testing for ignoring files as well Co-authored-by: wben1110 (desktop) --- .../MultiverseCore/utils/FileUtils.java | 29 ++++++++++++++--- .../MultiverseCore/utils/WorldManager.java | 12 +++---- .../MultiverseCore/utils/FileUtilsTest.java | 31 +++++++++++++++++++ 3 files changed, 60 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/FileUtils.java b/src/main/java/com/onarandombox/MultiverseCore/utils/FileUtils.java index ce7933067..47fa80ed7 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/FileUtils.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/FileUtils.java @@ -16,7 +16,9 @@ import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; +import java.util.Arrays; import java.util.Comparator; +import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Stream; @@ -72,14 +74,27 @@ public static boolean deleteFolderContents(File file) { * @param target Target-File * @param log A logger that logs the operation * - * @return if it had success + * @return true if it had success */ public static boolean copyFolder(File source, File target, Logger log) { + return copyFolder(source, target, null, log); + } + + /** + * Helper method to copy the world-folder. + * @param source Source-File + * @param target Target-File + * @param excludeFiles files to ignore and not copy over to Target-File + * @param log A logger that logs the operation + * + * @return true if it had success + */ + public static boolean copyFolder(File source, File target, List excludeFiles, Logger log) { Path sourceDir = source.toPath(); Path targetDir = target.toPath(); try { - Files.walkFileTree(sourceDir, new CopyDirFileVisitor(sourceDir, targetDir)); + Files.walkFileTree(sourceDir, new CopyDirFileVisitor(sourceDir, targetDir, excludeFiles)); return true; } catch (IOException e) { log.log(Level.WARNING, "Unable to copy directory", e); @@ -91,10 +106,12 @@ private static class CopyDirFileVisitor extends SimpleFileVisitor { private final Path sourceDir; private final Path targetDir; + private final List excludeFiles; - private CopyDirFileVisitor(Path sourceDir, Path targetDir) { + private CopyDirFileVisitor(Path sourceDir, Path targetDir, List excludeFiles) { this.sourceDir = sourceDir; this.targetDir = targetDir; + this.excludeFiles = excludeFiles; } @Override @@ -108,9 +125,13 @@ public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) th @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + // Pass files that are set to ignore + if (excludeFiles != null && excludeFiles.contains(file.getFileName().toString())) + return FileVisitResult.CONTINUE; + // Copy the files Path targetFile = targetDir.resolve(sourceDir.relativize(file)); Files.copy(file, targetFile, COPY_ATTRIBUTES); return FileVisitResult.CONTINUE; } } -} +} \ No newline at end of file diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/WorldManager.java b/src/main/java/com/onarandombox/MultiverseCore/utils/WorldManager.java index d3fcb8c6d..fb72d8107 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/WorldManager.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/WorldManager.java @@ -43,6 +43,7 @@ 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; @@ -127,6 +128,7 @@ public boolean cloneWorld(String oldName, String newName) { final File oldWorldFile = new File(this.plugin.getServer().getWorldContainer(), oldName); final File newWorldFile = new File(this.plugin.getServer().getWorldContainer(), newName); + final List ignoreFiles = new ArrayList<>(Arrays.asList("session.lock", "uid.dat")); // Make sure the new world doesn't exist outside of multiverse. if (newWorldFile.exists()) { @@ -177,20 +179,14 @@ public boolean cloneWorld(String oldName, String newName) { oldWorld.getCBWorld().save(); } Logging.config("Copying files for world '%s'", oldName); - if (!FileUtils.copyFolder(oldWorldFile, newWorldFile, Logging.getLogger())) { + if (!FileUtils.copyFolder(oldWorldFile, newWorldFile, ignoreFiles, Logging.getLogger())) { Logging.warning("Failed to copy files for world '%s', see the log info", newName); return false; } if (oldWorld != null && wasAutoSave) { oldWorld.getCBWorld().setAutoSave(true); } - - File uidFile = new File(newWorldFile, "uid.dat"); - if (uidFile.exists() && !uidFile.delete()) { - Logging.warning("Failed to delete unique ID file for world '%s'", newName); - return false; - } - + if (newWorldFile.exists()) { Logging.fine("Succeeded at copying files"); if (this.addWorld(newName, environment, seedString, worldType, generateStructures, generator, useSpawnAdjust)) { diff --git a/src/test/java/com/onarandombox/MultiverseCore/utils/FileUtilsTest.java b/src/test/java/com/onarandombox/MultiverseCore/utils/FileUtilsTest.java index 0b5da6f02..015d25426 100644 --- a/src/test/java/com/onarandombox/MultiverseCore/utils/FileUtilsTest.java +++ b/src/test/java/com/onarandombox/MultiverseCore/utils/FileUtilsTest.java @@ -6,6 +6,9 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import com.dumptruckman.minecraft.util.Logging; import org.junit.After; @@ -86,6 +89,34 @@ public void copyFolder() throws Exception { assertTrue(Files.isRegularFile(targetChildDirFile)); } + @Test + public void copyFolder_excludingSomeFiles() throws Exception { + Path targetDir = tempDir.resolve("target"); + Path targetFile = targetDir.resolve("parentDirFile.txt"); + Path targetIgnoreFile = targetDir.resolve("parentIgnoreFile.txt"); + Path targetChildDir = targetDir.resolve("childDir"); + Path targetChildDirFile = targetChildDir.resolve("childDirFile.txt"); + Path targetChildIgnoreFile = targetChildDir.resolve("childIgnoreFile.txt"); + + List excludeFiles = new ArrayList<>(Arrays.asList("parentIgnoreFile.txt", "childIgnoreFile.txt")); + + assertFalse(Files.isDirectory(targetDir)); + assertFalse(Files.isRegularFile(targetFile)); + assertFalse(Files.isRegularFile(targetIgnoreFile)); + assertFalse(Files.isDirectory(targetChildDir)); + assertFalse(Files.isRegularFile(targetChildDirFile)); + assertFalse(Files.isRegularFile(targetChildIgnoreFile)); + + assertTrue(FileUtils.copyFolder(parentDir.toFile(), targetDir.toFile(), excludeFiles, Logging.getLogger())); + + assertTrue(Files.isDirectory(targetDir)); + assertTrue(Files.isRegularFile(targetFile)); + assertFalse(Files.isRegularFile(targetIgnoreFile)); + assertTrue(Files.isDirectory(targetChildDir)); + assertTrue(Files.exists(targetChildDirFile)); + assertFalse(Files.isRegularFile(targetChildIgnoreFile)); + } + @Test public void copyFolder_intoExistingFolder() throws Exception { Path targetDir = Files.createDirectory(tempDir.resolve("target")); From faf20ee36eb92127862433950a3807bf935666e2 Mon Sep 17 00:00:00 2001 From: Jad Date: Thu, 10 Sep 2020 18:09:58 -0500 Subject: [PATCH 110/134] A, not an :P --- .github/ISSUE_TEMPLATE/report-a-bug.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/report-a-bug.md b/.github/ISSUE_TEMPLATE/report-a-bug.md index 36c8ca05a..9d69d3c01 100644 --- a/.github/ISSUE_TEMPLATE/report-a-bug.md +++ b/.github/ISSUE_TEMPLATE/report-a-bug.md @@ -1,6 +1,6 @@ --- name: Report a Bug -about: Report an Multiverse-Core bug. Only use this if you're 100% sure it's something wrong with Multiverse-Core - otherwise, try "Help!". +about: Report a Multiverse-Core bug. Only use this if you're 100% sure it's something wrong with Multiverse-Core - otherwise, try "Help!". --- @@ -53,4 +53,4 @@ I was **``** to reproduce my issue on a freshly setup and up-to **Screenshots** - \ No newline at end of file + From 51e035eb3e8b9a125654c25ce27509d14a4a58ca Mon Sep 17 00:00:00 2001 From: nicegamer7 Date: Tue, 22 Sep 2020 15:02:03 -0400 Subject: [PATCH 111/134] Update GameMode command and increase Java support. (#2279) * update gamerule command * fix NPE in gamerules command and remove deprecated method * catch buscript initialization errors * update gamerule command to be more descriptive * undo GameruleCommand style changes * update legacy version reporting to include all config options * use LF line ending for files being pasted to the web * avoid duplicate code --- .../MultiverseCore/MultiverseCore.java | 11 ++-- .../commands/GameruleCommand.java | 50 ++++++++++++++++--- .../commands/GamerulesCommand.java | 8 ++- .../commands/ScriptCommand.java | 4 ++ .../commands/VersionCommand.java | 20 +++++--- 5 files changed, 75 insertions(+), 18 deletions(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java index 43820a5af..b4168ae02 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java @@ -350,9 +350,14 @@ private void setupMetrics() { * Initializes the buscript javascript library. */ private void initializeBuscript() { - buscript = new Buscript(this); - // Add global variable "multiverse" to javascript environment - buscript.setScriptVariable("multiverse", this); + try { + buscript = new Buscript(this); + // Add global variable "multiverse" to javascript environment + buscript.setScriptVariable("multiverse", this); + } catch (NullPointerException e) { + buscript = null; + Logging.warning("Buscript failed to load! The script command will be disabled!"); + } } private void initializeDestinationFactory() { diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/GameruleCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/GameruleCommand.java index 01eddae6b..ca0e1e076 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/GameruleCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/GameruleCommand.java @@ -10,6 +10,7 @@ import com.onarandombox.MultiverseCore.MultiverseCore; import org.bukkit.Bukkit; import org.bukkit.ChatColor; +import org.bukkit.GameRule; import org.bukkit.World; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -55,7 +56,7 @@ public void runCommand(CommandSender sender, List args) { return; } - final String gameRule = args.get(0); + final GameRule gameRule = GameRule.getByName(args.get(0)); final String value = args.get(1); final World world; if (args.size() == 2) { @@ -64,17 +65,52 @@ public void runCommand(CommandSender sender, List args) { world = Bukkit.getWorld(args.get(2)); if (world == null) { sender.sendMessage(ChatColor.RED + "Failure!" + ChatColor.WHITE + " World " + ChatColor.AQUA + args.get(2) - + ChatColor.WHITE + " does not exist."); + + ChatColor.WHITE + " does not exist."); return; } } - if (world.setGameRuleValue(gameRule, value)) { - sender.sendMessage(ChatColor.GREEN + "Success!" + ChatColor.WHITE + " Gamerule " + ChatColor.AQUA + gameRule - + ChatColor.WHITE + " was set to " + ChatColor.GREEN + value); + if (gameRule == null) { + sender.sendMessage(ChatColor.RED + "Failure! " + ChatColor.AQUA + args.get(0) + ChatColor.WHITE + + " is not a valid gamerule."); } else { - sender.sendMessage(ChatColor.RED + "Failure!" + ChatColor.WHITE + " Gamerule " + ChatColor.AQUA + gameRule - + ChatColor.WHITE + " cannot be set to " + ChatColor.RED + value); + if (gameRule.getType() == Boolean.class) { + boolean booleanValue; + if (value.equalsIgnoreCase("true")) { + booleanValue = true; + } else if (value.equalsIgnoreCase("false")) { + booleanValue = false; + } else { + sender.sendMessage(getErrorMessage(gameRule.getName(), value) + "it can only be set to true or false."); + return; + } + + if (!world.setGameRule(gameRule, booleanValue)) { + sender.sendMessage(getErrorMessage(gameRule.getName(), value) + "something went wrong."); + return; + } + } else if (gameRule.getType() == Integer.class) { + try { + if (!world.setGameRule(gameRule, Integer.parseInt(value))) { + throw new NumberFormatException(); + } + } catch (NumberFormatException e) { + sender.sendMessage(getErrorMessage(gameRule.getName(), value) + "it can only be set to a positive integer."); + return; + } + } else { + sender.sendMessage(ChatColor.RED + "Failure!" + ChatColor.WHITE + " Gamerule " + ChatColor.AQUA + gameRule.getName() + + ChatColor.WHITE + " isn't supported yet, please let us know about it."); + return; + } + + sender.sendMessage(ChatColor.GREEN + "Success!" + ChatColor.WHITE + " Gamerule " + ChatColor.AQUA + gameRule.getName() + + ChatColor.WHITE + " was set to " + ChatColor.GREEN + value + ChatColor.WHITE + "."); } } + + private String getErrorMessage(String gameRule, String value) { + return ChatColor.RED + "Failure!" + ChatColor.WHITE + " Gamerule " + ChatColor.AQUA + gameRule + + ChatColor.WHITE + " could not be set to " + ChatColor.RED + value + ChatColor.WHITE + ", "; + } } diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/GamerulesCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/GamerulesCommand.java index 321ac0907..62b3e0607 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/GamerulesCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/GamerulesCommand.java @@ -10,6 +10,7 @@ import com.onarandombox.MultiverseCore.MultiverseCore; import org.bukkit.Bukkit; import org.bukkit.ChatColor; +import org.bukkit.GameRule; import org.bukkit.World; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -60,6 +61,11 @@ public void runCommand(CommandSender sender, List args) { world = p.getWorld(); } else { world = Bukkit.getWorld(args.get(0)); + if (world == null) { + sender.sendMessage(ChatColor.RED + "Failure!" + ChatColor.WHITE + " World " + ChatColor.AQUA + args.get(0) + + ChatColor.WHITE + " does not exist."); + return; + } } final StringBuilder gameRules = new StringBuilder(); @@ -68,7 +74,7 @@ public void runCommand(CommandSender sender, List args) { gameRules.append(ChatColor.WHITE).append(", "); } gameRules.append(ChatColor.AQUA).append(gameRule).append(ChatColor.WHITE).append(": "); - gameRules.append(ChatColor.GREEN).append(world.getGameRuleValue(gameRule)); + gameRules.append(ChatColor.GREEN).append(world.getGameRuleValue(GameRule.getByName(gameRule))); } sender.sendMessage("=== Gamerules for " + ChatColor.AQUA + world.getName() + ChatColor.WHITE + " ==="); sender.sendMessage(gameRules.toString()); diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/ScriptCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/ScriptCommand.java index 2896a8e70..665f6aa71 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/ScriptCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/ScriptCommand.java @@ -35,6 +35,10 @@ public ScriptCommand(MultiverseCore plugin) { @Override public void runCommand(CommandSender sender, List args) { + if (plugin.getScriptAPI() == null) { + sender.sendMessage("Buscript failed to load while the server was starting. Scripts cannot be run."); + return; + } File file = new File(plugin.getScriptAPI().getScriptFolder(), args.get(0)); if (!file.exists()) { sender.sendMessage("That script file does not exist in the Multiverse-Core scripts directory!"); diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java index 3f4b26f52..29ac54d43 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java @@ -61,16 +61,22 @@ private String getLegacyString() { "[Multiverse-Core] Economy being used: " + plugin.getEconomist().getEconomyName() + System.lineSeparator() + "[Multiverse-Core] Permissions Plugin: " + this.plugin.getMVPerms().getType() + System.lineSeparator() + "[Multiverse-Core] Dumping Config Values: (version " + this.plugin.getMVConfig().getVersion() + ")" + System.lineSeparator() + - "[Multiverse-Core] messagecooldown: " + plugin.getMessaging().getCooldown() + System.lineSeparator() + - "[Multiverse-Core] teleportcooldown: " + plugin.getMVConfig().getTeleportCooldown() + System.lineSeparator() + - "[Multiverse-Core] worldnameprefix: " + plugin.getMVConfig().getPrefixChat() + System.lineSeparator() + - "[Multiverse-Core] worldnameprefixFormat: " + plugin.getMVConfig().getPrefixChatFormat() + System.lineSeparator() + "[Multiverse-Core] enforceaccess: " + plugin.getMVConfig().getEnforceAccess() + System.lineSeparator() + - "[Multiverse-Core] displaypermerrors: " + plugin.getMVConfig().getDisplayPermErrors() + System.lineSeparator() + + "[Multiverse-Core] prefixchat: " + plugin.getMVConfig().getPrefixChat() + System.lineSeparator() + + "[Multiverse-Core] prefixchatformat: " + plugin.getMVConfig().getPrefixChatFormat() + System.lineSeparator() + + "[Multiverse-Core] useasyncchat: " + plugin.getMVConfig().getUseAsyncChat() + System.lineSeparator() + "[Multiverse-Core] teleportintercept: " + plugin.getMVConfig().getTeleportIntercept() + System.lineSeparator() + "[Multiverse-Core] firstspawnoverride: " + plugin.getMVConfig().getFirstSpawnOverride() + System.lineSeparator() + + "[Multiverse-Core] displaypermerrors: " + plugin.getMVConfig().getDisplayPermErrors() + System.lineSeparator() + + "[Multiverse-Core] globaldebug: " + plugin.getMVConfig().getGlobalDebug() + System.lineSeparator() + + "[Multiverse-Core] silentstart: " + plugin.getMVConfig().getSilentStart() + System.lineSeparator() + + "[Multiverse-Core] messagecooldown: " + plugin.getMessaging().getCooldown() + System.lineSeparator() + + "[Multiverse-Core] version: " + plugin.getMVConfig().getVersion() + System.lineSeparator() + "[Multiverse-Core] firstspawnworld: " + plugin.getMVConfig().getFirstSpawnWorld() + System.lineSeparator() + - "[Multiverse-Core] debug: " + plugin.getMVConfig().getGlobalDebug() + System.lineSeparator() + + "[Multiverse-Core] teleportcooldown: " + plugin.getMVConfig().getTeleportCooldown() + System.lineSeparator() + + "[Multiverse-Core] defaultportalsearch: " + plugin.getMVConfig().isUsingDefaultPortalSearch() + System.lineSeparator() + + "[Multiverse-Core] portalsearchradius: " + plugin.getMVConfig().getPortalSearchRadius() + System.lineSeparator() + + "[Multiverse-Core] autopurge: " + plugin.getMVConfig().isAutoPurgeEnabled() + System.lineSeparator() + "[Multiverse-Core] Special Code: FRN002" + System.lineSeparator(); } @@ -110,7 +116,7 @@ private String readFile(final String filename) { String line; result = new StringBuilder(); while ((line = bufferedReader.readLine()) != null) { - result.append(line).append(System.lineSeparator()); + result.append(line).append("\n"); } } catch (FileNotFoundException e) { Logging.severe("Unable to find %s. Here's the traceback: %s", filename, e.getMessage()); From b8acd339b3e3b56ec48f590782a2a5ca5d081672 Mon Sep 17 00:00:00 2001 From: Robert Timm Date: Fri, 14 Aug 2020 00:10:54 +0200 Subject: [PATCH 112/134] load cloned world with doLoad() instead of addWorld() (fixes #2378) --- .../MultiverseCore/utils/WorldManager.java | 31 ++++++++++++++----- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/WorldManager.java b/src/main/java/com/onarandombox/MultiverseCore/utils/WorldManager.java index d3fcb8c6d..ef8e75b9b 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/WorldManager.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/WorldManager.java @@ -193,16 +193,31 @@ public boolean cloneWorld(String oldName, String newName) { if (newWorldFile.exists()) { Logging.fine("Succeeded at copying files"); - if (this.addWorld(newName, environment, seedString, worldType, generateStructures, generator, useSpawnAdjust)) { - // getMVWorld() doesn't actually return an MVWorld - Logging.fine("Succeeded at importing world"); - MVWorld newWorld = (MVWorld) this.getMVWorld(newName); - newWorld.copyValues(this.worldsFromTheConfig.get(oldName)); - // don't keep the alias the same -- that would be useless - newWorld.setAlias(""); - return true; + + // initialize new properties with old ones + WorldProperties newProps = new WorldProperties(); + newProps.copyValues(this.worldsFromTheConfig.get(oldName)); + // don't keep the alias the same -- that would be useless + newProps.setAlias(""); + // store the new properties in worlds config map + this.worldsFromTheConfig.put(newName, newProps); + + // save the worlds config to disk (worlds.yml) + if (!saveWorldsConfig()) { + this.plugin.log(Level.SEVERE, "Failed to save worlds.yml"); + return false; + } + + // actually load the world + if (doLoad(newName)) { + this.plugin.log(Level.FINE, "Succeeded at loading cloned world '" + newName + "'"); + return true; } + + this.plugin.log(Level.SEVERE, "Failed to load the cloned world '" + newName + "'"); + return false; } + Logging.warning("Failed to copy files for world '%s', see the log info", newName); return false; } From 9159dfbb7dd833c31f13755c564929201daeefff Mon Sep 17 00:00:00 2001 From: benwoo1110 Date: Mon, 5 Oct 2020 00:28:48 +0800 Subject: [PATCH 113/134] Updated plugin.yml commands and some missing alias --- .../MultiverseCore/commands/ListCommand.java | 2 +- .../commands/ReloadCommand.java | 1 + .../commands/SetSpawnCommand.java | 1 + .../commands/TeleportCommand.java | 2 +- .../commands/VersionCommand.java | 3 +- src/main/resources/plugin.yml | 174 +++++++----------- 6 files changed, 68 insertions(+), 115 deletions(-) diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/ListCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/ListCommand.java index e63ea4f2f..d702bf93e 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/ListCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/ListCommand.java @@ -26,7 +26,7 @@ public class ListCommand extends PaginatedCoreCommand { public ListCommand(MultiverseCore plugin) { super(plugin); this.setName("World Listing"); - this.setCommandUsage("/mv list"); + this.setCommandUsage("/mv list [page]"); this.setArgRange(0, 2); this.addKey("mvlist"); this.addKey("mvl"); diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/ReloadCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/ReloadCommand.java index 3481a4ea8..abe2b0a64 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/ReloadCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/ReloadCommand.java @@ -27,6 +27,7 @@ public ReloadCommand(MultiverseCore plugin) { this.setCommandUsage("/mv reload"); this.setArgRange(0, 0); this.addKey("mvreload"); + this.addKey("mvr"); this.addKey("mv reload"); this.addCommandExample("/mv reload"); this.setPermission("multiverse.core.reload", "Reloads worlds.yml and config.yml.", PermissionDefault.OP); diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/SetSpawnCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/SetSpawnCommand.java index 2c3c25a87..26dad442c 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/SetSpawnCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/SetSpawnCommand.java @@ -30,6 +30,7 @@ public SetSpawnCommand(MultiverseCore plugin) { this.setCommandUsage("/mv setspawn"); this.setArgRange(0, 6); this.addKey("mvsetspawn"); + this.addKey("mvsets"); this.addKey("mvss"); this.addKey("mv set spawn"); this.addKey("mv setspawn"); diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/TeleportCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/TeleportCommand.java index 847aa6d47..6f8264f49 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/TeleportCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/TeleportCommand.java @@ -40,7 +40,7 @@ public TeleportCommand(MultiverseCore plugin) { Permission menu = new Permission("multiverse.teleport.*", "Allows you to display the teleport menu.", PermissionDefault.OP); this.setName("Teleport"); - this.setCommandUsage("/mv tp " + ChatColor.GOLD + "[PLAYER]" + ChatColor.GREEN + " {WORLD}"); + this.setCommandUsage("/mv tp " + ChatColor.GOLD + "[PLAYER]" + ChatColor.GREEN + " {DESTINATION}"); this.setArgRange(1, 2); this.addKey("mvtp"); this.addKey("mv tp"); diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java index 29ac54d43..9145a0c78 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/VersionCommand.java @@ -44,9 +44,10 @@ public class VersionCommand extends MultiverseCommand { public VersionCommand(MultiverseCore plugin) { super(plugin); this.setName("Multiverse Version"); - this.setCommandUsage("/mv version " + ChatColor.GOLD + "-[bhp] [--include-plugin-list]"); + this.setCommandUsage("/mv version " + ChatColor.GOLD + "[-b|-h|-p] [--include-plugin-list]"); this.setArgRange(0, 2); this.addKey("mv version"); + this.addKey("mvver"); this.addKey("mvv"); this.addKey("mvversion"); this.setPermission("multiverse.core.version", diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 5359af214..d46f0fd7e 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -11,34 +11,24 @@ commands: usage: / mvcreate: description: World create command - usage: | - / - / creative normal -- Creates a world called 'creative' with a NORMAL environment. - / hellworld nether -- Creates a world called 'hellworld' with a NETHER environment. - mvc: - description: World create command + aliases: [mvc] usage: | / / creative normal -- Creates a world called 'creative' with a NORMAL environment. / hellworld nether -- Creates a world called 'hellworld' with a NETHER environment. mvimport: description: World import command + aliases: [mvim] usage: | - / - / creative normal -- Imports an existing world called 'creative' with a NORMAL environment. - / hellworld nether -- Imports an existing world called 'hellworld' with a NETHER environment. - mvim: - description: World import command - usage: | - / - / creative normal -- Imports an existing world called 'creative' with a NORMAL environment. - / hellworld nether -- Imports an existing world called 'hellworld' with a NETHER environment. + / [-g generator[:id]] [-n] + / creative normal -- Imports an existing world called 'creative' with a NORMAL environment. + / hellworld nether -- Imports an existing world called 'hellworld' with a NETHER environment. mvremove: - description: World remove command + description: Remove world from multiverse command usage: | / mvdelete: - description: World delete command + description: Delete world from server folders command usage: | / mvunload: @@ -47,103 +37,75 @@ commands: / mvmodify: description: Modify the settings of an existing world + aliases: [mvm] usage: | - /