Compare commits

...
131 Commits
Author SHA1 Message Date
main() 57b3370381 Fixed unit test 2012-11-05 16:30:19 +01:00
main() 9d213fbc0a Merge branch 'master' of github.com:Multiverse/Multiverse-Core into localization
Conflicts:
	src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java
	src/main/java/com/onarandombox/MultiverseCore/MultiverseCoreConfiguration.java
	src/main/java/com/onarandombox/MultiverseCore/api/MultiverseCoreConfig.java
2012-11-05 16:26:49 +01:00
main() 0c638035f2 Moving strings, part 2 2012-11-05 16:22:16 +01:00
Jeremy Wood 63f8811b67 Fixed #942. 2012-11-05 09:05:11 -05:00
Jeremy Wood d01ce71343 Fixed #935. 2012-10-31 08:31:07 -04:00
Jeremy Wood fe00aae7e3 Fixes #934 - Vault dependency issue. 2012-10-30 08:45:05 -04:00
Jeremy Wood d4347d0cff Fixed incorrect log level. 2012-10-25 15:48:28 -03:00
Jeremy Wood b033d59b8a Optimized some log messages and change some Level.INFO messages to Level.CONFIG for the new silent start mode. Fixes #697. 2012-10-25 14:36:44 -04:00
Jeremy Wood aedbfd7bab Added command "mv silent [on|off]" for enabling silent startup mode. 2012-10-25 14:35:22 -04:00
Jeremy Wood b93822502e Reverted debug command. 2012-10-25 14:02:01 -04:00
Jeremy Wood f053f0546b Now using Logging 1.0.9! 2012-10-25 13:56:57 -04:00
Jeremy Wood af3b3d0fab Added ability to set debug level to -1 to disable common startup messages. 2012-10-25 10:43:57 -04:00
Jeremy Wood b1fa677330 Now using Logging 1.0.8 2012-10-25 10:35:27 -04:00
main() 9691a0f978 Merge pull request #931 from ammaraskar/limit
Add player limit per world. Closes #727.
2012-10-25 02:11:29 -07:00
Ammar Askar 0b1a387003 Add player limit per world. Addresses #727 2012-10-25 14:02:27 +05:00
main() fb6a031860 Localization should now be thread-safe. 2012-10-24 16:58:43 +02:00
main() 703707a39b Improved localization loading on startup. 2012-10-24 16:58:04 +02:00
main() 0b7b91a081 Merge branch 'master' of github.com:Multiverse/Multiverse-Core into localization
Conflicts:
	src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java
2012-10-24 16:54:02 +02:00
Jeremy Wood 4ce503f55e Cow using EnumSet for maximum performance!!!! 2012-10-23 14:26:09 -04:00
main() 74947a7efd Fixed all other style warnings 2012-10-23 16:58:16 +02:00
main() 85cd71cb8a Fixed high priority style warnings 2012-10-23 16:49:08 +02:00
Jeremy Wood 3ad7d86f74 Deprecated DebugLog. 2012-10-22 17:40:39 -04:00
Jeremy Wood ac9194ec87 Now building with SerializationConfig 1.6c, finally fixes weird config exception messages. 2012-10-22 17:35:06 -04:00
main() 96e8208f3d Merge branch 'ammaraskar_folder' 2012-10-22 19:08:15 +02:00
Ammar Askar 895360ce8b Only delete world folder contents on mv regen, fixes #767 2012-10-22 19:06:19 +02:00
main() 59e34ef353 Merge pull request #925 from ammaraskar/entities
Add golems to animals fixes #891
2012-10-22 08:39:44 -07:00
Ammar Askar 11e556c099 Add golems to animals fixes #891 2012-10-22 20:34:01 +05:00
main() a9579a6594 Merge pull request #922 from ammaraskar/spawn
Added configurable animal and monster ticks per spawn setting. Fixes #519
2012-10-22 04:12:42 -07:00
Ammar Askar 5a1fe2a9e5 Added configurable animal and monster ticks per spawn setting. Fixes #519 2012-10-22 13:20:09 +05:00
Eric Stokes 1c5c792cf3 A broadcast is not needed if we're not doing anything 2012-10-21 18:57:54 -06:00
Eric Stokes dbe9494dbf Fixed Bed Spawns
This fixes #652 and fixes #916
This also fixes some other issues with NullPointerExceptions when trying to teleport to a bed if it was invalid.
2012-10-21 18:49:48 -06:00
Jeremy Wood b116effa2b Using HashSet instead of ArrayList for better contains() efficiency. 2012-10-21 17:55:41 -04:00
Jeremy Wood d361ceb45b Increased efficiency/safety of recent /mv who changes. 2012-10-21 17:49:51 -04:00
Eric Stokes 35709f5389 Tell user when creating a duplicate world
Fixes #921
2012-10-21 14:49:56 -06:00
Eric Stokes b45a4cf20a Fix NPCs Showing up in mv who
This fixes #501. FINALLY!

If anyone wants NPCs back, open a ticket, and I'll add a flag, but this is now the default behavior.
2012-10-21 14:22:12 -06:00
Eric Stokes 009ceeeede Fixed #918, Update to RB
Also added a test for #918, I probably need one more (to test that generators DO work) but I just tested that ingame this time.
2012-10-21 13:38:36 -06:00
Jeremy Wood 19fb9df5cf Added online player count / max players to /mv who header 2012-10-21 00:39:13 -04:00
Jeremy Wood 0829df01aa Readded the accidently removed shading of AllPay! 2012-10-20 20:55:56 -04:00
Jeremy Wood 78ac068a3f Fixed world's not charging correctly. Fixes #893. Fixes #777. Possibly fixes #723. That's a 3fer, good buddy. 2012-10-20 20:49:15 -04:00
Jeremy Wood 57da3df860 Added in Vault as the prefered method for checking economy stuff. Will defer to AllPay for item based world costs. 2012-10-20 20:43:58 -04:00
Jeremy Wood 74241e3d9c Updated protocol to 18 for Vault. 2012-10-20 20:12:42 -04:00
Jeremy Wood 6a4921d7d1 MVWorld.toString() now outputs JSON data. 2012-10-20 12:44:50 -04:00
Jeremy Wood 271e5f339e Version command now outputs world information instead of juts count. 2012-10-20 12:44:29 -04:00
Eric Stokes ec89db1bed Update MCSTATS to 1.2-SNAPSHOT
1.0-SNAPSHOT is gone from the repo :(
2012-10-19 23:35:48 -06:00
Jeremy Wood 7346cbe48c Actually enables debug logging when enabled via command. 2012-10-19 15:11:02 -04:00
Jeremy Wood ac3049f3ab Now properly enables debug logging on startup if debug logging should be enabled. 2012-10-19 15:10:36 -04:00
Jeremy Wood e82db95bbc Now using Logging 1.0.6! 2012-10-19 15:10:02 -04:00
Jeremy Wood 0d0f167396 Stopped trying to replace the old DebugLog. 2012-10-18 21:39:43 -04:00
Jeremy Wood b35a0325b8 Now using Logging 1.0.4 2012-10-18 21:19:33 -04:00
Jeremy Wood 3572d3fbe7 Now using Logging 1.0.3! 2012-10-18 15:17:52 -04:00
Jeremy Wood 7304269866 Upgraded to testificated Logging 1.0.2! 2012-10-18 14:46:25 -04:00
Jeremy Wood d7535b0551 replaced logging with com.dumptruckman.minecraft:Logging lib. 2012-10-17 14:23:00 -04:00
main() 21b997c1a2 Moving strings, part 1 2012-10-17 15:43:41 +02:00
main() 0437a4bd92 Why is/was this "Multiverse-Adventure"... 2012-10-17 14:26:40 +02:00
main() 7031e9e58b Now saving the Locale in the new config 2012-10-16 20:38:55 +02:00
main() 322acbc636 Fixed possible stream leak
Thanks, eclipse!
2012-10-16 20:10:37 +02:00
main() 256d4b0abd Now building the color char regex dynamically.
The regex is now built from values in org.bukkit.ChatColor!
2012-10-16 20:04:44 +02:00
main() 88088548f8 Merge branch 'master' of github.com:Multiverse/Multiverse-Core into localization
Conflicts:
	src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java
	src/test/java/com/onarandombox/MultiverseCore/test/utils/TestInstanceCreator.java
2012-10-16 19:38:04 +02:00
main() d881908ecc Made entity listener use the world purger's logic
This should fix #872 and most other spawning issues.
2012-09-20 20:01:55 +02:00
Jeremy Wood 3715bc8bc5 Should now detect Async chat availability for even better backwards compatibility. 2012-09-05 20:53:59 -04:00
main() a9f00a46f5 Fixed #859
The WhoCommand was handling invisible players incorrectly
2012-08-26 14:47:01 +02:00
Jeremy Wood d9a7275682 Stop checking for null worlds. 2012-08-21 15:06:55 -04:00
Jeremy Wood 80f6a0159c Now using ConcurrentHashMap instead of ReentrantLock for caching player world. 2012-08-21 15:06:33 -04:00
Jeremy Wood f2e1053b88 Now using ConcurrentHashMap instead of locks for worlds Map. 2012-08-21 14:54:49 -04:00
Jeremy Wood e975968637 MVWorld properties now volatile instead of using thread lock. 2012-08-21 14:25:11 -04:00
Jeremy Wood a778d353c4 Config now volatile instead of using thread lock. 2012-08-21 14:19:05 -04:00
Jeremy Wood d40e67b47d Config properties now volatile instead of using thread lock. 2012-08-21 14:17:24 -04:00
Jeremy Wood 9196973d1c Fixed NPE in world loading.. Thanks Grimlock257 for spotting this. 2012-08-21 13:20:13 -04:00
Jeremy Wood 242d20884c Now building against Bukkit 1.3.1-R2.1-SNAPSHOT 2012-08-21 09:16:28 -04:00
main() b909af873d Should fix #847
(NPE in the GeneratorPlotter for worlds with a null generator)
2012-08-20 10:22:39 +02:00
main() e6f7ba5ac9 Fixed the tests 2012-08-18 15:17:17 +02:00
main() 4ecb28b3bb Less duplicate code ... I think. 2012-08-18 15:13:09 +02:00
main() d0ea4168bc Style! 2012-08-18 14:54:18 +02:00
main() fd9464ced1 More anchor permissions (as suggested in #831) 2012-08-18 14:45:15 +02:00
Jeremy Wood 49eb93af2e Once again prints debug mode output to the console 2012-08-15 11:33:16 -04:00
Jeremy Wood 9274570fa4 Added config option for setting whether or not to use async chat. (Default true (uses async)) 2012-08-15 09:27:52 -04:00
Jeremy Wood 319a701a16 Modifying world values now persists again! (When the hell did this break???) 2012-08-14 15:00:08 -04:00
Jeremy Wood 807c8d0f2c Debug setting saves to config now. 2012-08-13 13:52:25 -04:00
Jeremy Wood 29d97274fe Stopped being dumb and denying bukkit of it's precious invisible constraints for ConfigurationSerializable. Fixes #827. 2012-08-13 13:51:42 -04:00
Jeremy Wood eb1dc502cd Now using ReentrantLock instead of synchronized blocks. Should help debug lag issue. 2012-08-11 23:21:58 -04:00
Jeremy Wood 622fb19c4a Using logging instead of System.out... 2012-08-09 09:18:06 -04:00
Jeremy Wood 5705b5b6a0 Added missing import... 2012-08-09 09:15:07 -04:00
main() 1d1a2213c1 Merge branch 'metrics' 2012-08-09 13:43:07 +02:00
Jeremy Wood 4dd3df26a5 Now building against Bukkit-1.3.1-R1.0 2012-08-08 10:56:22 -04:00
main() 39293482d2 Removed duplicate maven source plugin 2012-08-06 18:44:42 +02:00
main() 9813e5f531 MBot's ?internalerror is useful but this is better 2012-08-06 18:41:02 +02:00
main() 48adbec011 dat style
CheckStyle is merciless!
2012-08-06 15:34:01 +02:00
main() a9a5d7467a Fixed world regeneration 2012-08-06 15:17:14 +02:00
main() b8a0891c4c Fixed again... 2012-08-06 12:06:50 +02:00
main() 53567d4646 Hopefully fixed the tests 2012-08-06 11:54:54 +02:00
main() 3395f3d7c7 We shouldn't try to load deleted worlds 2012-08-06 11:29:54 +02:00
Jeremy Wood e197091bb2 Added better support for large biomes. 2012-08-05 15:40:58 -04:00
Jeremy Wood ede0395d39 Mapping the known world of players for Async chat event. 2012-08-05 14:58:24 -04:00
Jeremy Wood 17963964c7 Minor test update. 2012-08-05 14:53:41 -04:00
Jeremy Wood bb0e2e4a2d Tests now using AsyncPlayerChatEvent. 2012-08-05 00:28:00 -04:00
Jeremy Wood ce4e608cf4 MultiverseCoreConfiguration.setDefaults() now protected as it should be. 2012-08-05 00:27:33 -04:00
Jeremy Wood 944f961ee5 Removed synchronization from setDefaults() due to how SerializationConfig operates. 2012-08-05 00:26:55 -04:00
Jeremy Wood 5335e73707 Now using AsyncPlayerChatEvent... let's hope for the best! 2012-08-05 00:11:39 -04:00
Jeremy Wood d05e2b500f Synchronized world properties required by Async chat event. 2012-08-05 00:11:13 -04:00
Jeremy Wood b2f3b74062 Synchronized all access to worlds map in WorldManager. 2012-08-05 00:00:46 -04:00
Jeremy Wood 16e42f6469 Finalized some object in MultiverseCore to help with thread-safe migration. 2012-08-04 23:51:43 -04:00
Jeremy Wood a31dc83635 Synchronized getting/setting of mv config object. 2012-08-04 23:50:01 -04:00
Jeremy Wood 7b99130bfa Synchronized config values to be used in new Async chat event. 2012-08-04 23:43:09 -04:00
Matt H f57468126a Added '/mv clone' command to clone a world. 2012-08-04 14:29:13 -06:00
Jeremy Wood d17fee6b7c Now building against Bukkit 1.3.1-R0.1-SNAPSHOT. 2012-08-03 13:29:55 -04:00
Jeremy Wood 1a943e42a9 Added maven source and javadoc plugins. 2012-08-03 13:28:32 -04:00
Jeremy Wood 2b80ca80ae Bumped protocol from 16 to 17. 2012-07-25 22:10:06 -04:00
Jeremy Wood 24e26bb7d7 Added buscript Javascript library. 2012-07-25 22:09:28 -04:00
Jeremy Wood 6133cf6bdf Bumped protocol from 15 to 16 2012-07-19 21:10:51 -04:00
Jeremy Wood 085c7a1ccc Migrated Multiverse-Adventure's copyFolder() into core. 2012-07-19 21:08:39 -04:00
main() dd0b2137d6 Changes... 2012-07-12 17:34:25 +02:00
main() 8a4ba2a66c Metrics! 2012-07-12 17:24:23 +02:00
main() affc96f2e2 Merge branch 'master' into localization 2012-05-17 15:26:06 +02:00
main() f3830390f6 Merge branch 'master' into localization
Conflicts:
	src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java
2012-02-26 16:47:31 +01:00
main() 8b224349e6 Seriously? Where does this come from? 2012-02-04 20:09:11 +01:00
main() b51e26bcf1 Merge branch 'master' of github.com:Multiverse/Multiverse-Core into localization
Conflicts:
	src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java
	src/main/resources/defaults/config.yml
2012-02-04 20:06:45 +01:00
Eric Stokes 49ffb4dcec Merge changes from master into localization 2012-01-24 20:44:19 -07:00
main() a66a5eaeb3 Merge branch 'master' of github.com:Multiverse/Multiverse-Core into localization
Conflicts:
	src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java
	src/main/java/com/onarandombox/MultiverseCore/commands/ListCommand.java
	src/main/resources/defaults/config.yml
2012-01-07 16:26:41 +01:00
main() ba6f580fd8 Added test for SimpleMessageProvider.format(String, Object...). 2012-01-06 17:11:30 +01:00
main() e6c36be019 Improved ChatColor-support. 2012-01-06 17:10:37 +01:00
dumptruckman 3e4b042de8 Added args for String.format()
( cherry-picked by @main-- )
2012-01-06 16:53:18 +01:00
main() 451955f858 Reordered strings in the enum 2011-12-11 11:13:28 +01:00
Eric Stokes 8e5d96309f Load locale before erring, add more generic locale messages. 2011-12-10 17:34:29 -07:00
Eric Stokes 970692d228 Apparently these didn't get smashed... 2011-12-10 17:30:44 -07:00
Eric Stokes 91a5d6c1c5 Fixed all merge badness... Sorry. 2011-12-10 17:20:09 -07:00
Eric Stokes 7668d14613 Pull import changes from master 2011-12-10 17:15:53 -07:00
Eric Stokes 38ce30f981 Fix not quoting a string that had a ':' in it. 2011-12-10 17:10:07 -07:00
Eric Stokes abb58b0563 Pull changes from master. 2011-12-10 17:03:36 -07:00
main() 22a7c5ae94 Fixed some nasty bugs 2011-12-02 18:39:05 +01:00
main() 303bbc317b Initialize the messageProvider only once, not on every onEnable() 2011-12-02 14:32:35 +01:00
main() 3531bd6432 Made a first working version of localization. 2011-12-01 20:36:12 +01:00
73 changed files with 2909 additions and 601 deletions

No files matched your search

+95 -11
View File
@@ -20,6 +20,16 @@
<id>Bukkit Official</id>
<url>http://repo.bukkit.org/content/repositories/public</url>
</repository>
<!-- Required for Metrics -->
<repository>
<id>mcstats</id>
<url>http://repo.mcstats.org/content/repositories/snapshots</url>
</repository>
<!-- Required for Vault -->
<repository>
<id>herocraft</id>
<url>http://ci.herocraftonline.com/plugin/repository/everything/</url>
</repository>
</repositories>
<pluginRepositories>
@@ -101,12 +111,6 @@
</archive>
</configuration>
</plugin>
<!-- Maven Source Plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.1.2</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
@@ -136,6 +140,33 @@
<configLocation>${project.basedir}/config/mv_checks.xml</configLocation>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.1.2</version>
<executions>
<execution>
<id>attach-sources</id>
<phase>package</phase>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.8.1</version>
<executions>
<execution>
<id>javadoc-jar</id>
<phase>verify</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
@@ -150,8 +181,11 @@
<artifactSet>
<includes>
<include>me.main__.util:SerializationConfig</include>
<include>com.fernferret.allpay:AllPay</include>
<include>com.pneumaticraft.commandhandler:CommandHandler</include>
<include>com.dumptruckman.minecraft:buscript</include>
<include>org.mcstats:metrics</include>
<include>com.dumptruckman.minecraft:Logging</include>
<include>com.fernferret.allpay:AllPay</include>
</includes>
</artifactSet>
<relocations>
@@ -167,6 +201,22 @@
<pattern>com.pneumaticraft.commandhandler</pattern>
<shadedPattern>com.pneumaticraft.commandhandler.multiverse</shadedPattern>
</relocation>
<relocation>
<pattern>buscript</pattern>
<shadedPattern>buscript.multiverse</shadedPattern>
</relocation>
<relocation>
<pattern>org.mcstats</pattern>
<shadedPattern>org.mcstats.multiverse</shadedPattern>
</relocation>
<relocation>
<pattern>com.dumptruckman.minecraft.util.Logging</pattern>
<shadedPattern>com.onarandombox.MultiverseCore.utils.CoreLogging</shadedPattern>
</relocation>
<relocation>
<pattern>com.dumptruckman.minecraft.util.DebugLog</pattern>
<shadedPattern>com.onarandombox.MultiverseCore.utils.DebugFileLogger</shadedPattern>
</relocation>
</relocations>
</configuration>
</execution>
@@ -180,7 +230,7 @@
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.2.5-R1.0</version>
<version>1.3.2-R2.1-SNAPSHOT</version>
<!-- If you want the lates, use this -->
<!-- <version>LATEST</version> -->
<type>jar</type>
@@ -198,12 +248,12 @@
<dependency>
<groupId>me.main__.util</groupId>
<artifactId>SerializationConfig</artifactId>
<version>1.6b</version>
<version>1.6c</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- End of SerializationConfig Dependency -->
<!-- Start of AllPay Dependency -->
<!-- Start of Economy Dependency -->
<dependency>
<groupId>com.fernferret.allpay</groupId>
<artifactId>AllPay</artifactId>
@@ -211,7 +261,14 @@
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- End of AllPay Dependency -->
<dependency>
<groupId>net.milkbowl.vault</groupId>
<artifactId>Vault</artifactId>
<version>1.2.19-SNAPSHOT</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- End of Economy Dependency -->
<!-- Start of CommandHandler Dependency -->
<dependency>
<groupId>com.pneumaticraft.commandhandler</groupId>
@@ -221,6 +278,33 @@
<scope>compile</scope>
</dependency>
<!-- End of CommandHandler Dependency -->
<!-- Start of Buscript Dependency -->
<dependency>
<groupId>com.dumptruckman.minecraft</groupId>
<artifactId>buscript</artifactId>
<version>1.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- End of Buscript Dependency -->
<!-- Start of Metrics Dependency -->
<dependency>
<groupId>org.mcstats</groupId>
<artifactId>metrics</artifactId>
<version>1.2-SNAPSHOT</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- End of Metrics Dependency -->
<!-- Start of Logging Dependency -->
<dependency>
<groupId>com.dumptruckman.minecraft</groupId>
<artifactId>Logging</artifactId>
<version>1.0.9</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- End of Logging Dependency -->
<!-- Start of Test Dependencies -->
<dependency>
<groupId>junit</groupId>
@@ -7,6 +7,7 @@
package com.onarandombox.MultiverseCore;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.api.BlockSafety;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.api.SafeTTeleporter;
@@ -39,6 +40,7 @@ import org.bukkit.entity.Player;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionDefault;
import org.bukkit.util.Vector;
import org.json.simple.JSONObject;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
@@ -60,23 +62,26 @@ public class MVWorld extends SerializationConfig implements MultiverseWorld {
private static final int SPAWN_LOCATION_SEARCH_TOLERANCE = 16;
private static final int SPAWN_LOCATION_SEARCH_RADIUS = 16;
private static Map<String, String> propertyAliases;
private static final Map<String, String> PROPERTY_ALIASES;
static {
propertyAliases = new HashMap<String, String>();
propertyAliases.put("curr", "currency");
propertyAliases.put("scaling", "scale");
propertyAliases.put("aliascolor", "color");
propertyAliases.put("heal", "autoHeal");
propertyAliases.put("storm", "allowWeather");
propertyAliases.put("weather", "allowWeather");
propertyAliases.put("spawnmemory", "keepSpawnInMemory");
propertyAliases.put("memory", "keepSpawnInMemory");
propertyAliases.put("mode", "gameMode");
propertyAliases.put("diff", "difficulty");
propertyAliases.put("spawnlocation", "spawn");
propertyAliases.put("animals", "spawning.animals.spawn");
propertyAliases.put("monsters", "spawning.monsters.spawn");
PROPERTY_ALIASES = new HashMap<String, String>();
PROPERTY_ALIASES.put("curr", "currency");
PROPERTY_ALIASES.put("scaling", "scale");
PROPERTY_ALIASES.put("aliascolor", "color");
PROPERTY_ALIASES.put("heal", "autoHeal");
PROPERTY_ALIASES.put("storm", "allowWeather");
PROPERTY_ALIASES.put("weather", "allowWeather");
PROPERTY_ALIASES.put("spawnmemory", "keepSpawnInMemory");
PROPERTY_ALIASES.put("memory", "keepSpawnInMemory");
PROPERTY_ALIASES.put("mode", "gameMode");
PROPERTY_ALIASES.put("diff", "difficulty");
PROPERTY_ALIASES.put("spawnlocation", "spawn");
PROPERTY_ALIASES.put("limit", "playerLimit");
PROPERTY_ALIASES.put("animals", "spawning.animals.spawn");
PROPERTY_ALIASES.put("monsters", "spawning.monsters.spawn");
PROPERTY_ALIASES.put("animalsrate", "spawning.animals.spawnrate");
PROPERTY_ALIASES.put("monstersrate", "spawning.monsters.spawnrate");
}
/*
* We have to use setCBWorld(), setPlugin() and initPerms() to prepare this object for use.
@@ -87,7 +92,7 @@ public class MVWorld extends SerializationConfig implements MultiverseWorld {
private MultiverseCore plugin; // Hold the Plugin Instance.
private Reference<World> world = new WeakReference<World>(null); // A reference to the World Instance.
private volatile Reference<World> world = new WeakReference<World>(null); // A reference to the World Instance.
private String name; // The Worlds Name, EG its folder name.
/**
@@ -232,6 +237,12 @@ public class MVWorld extends SerializationConfig implements MultiverseWorld {
} else {
allowMonsters = true;
}
if (MVWorld.this.spawning.getAnimalSettings().getSpawnRate() != -1) {
world.get().setTicksPerAnimalSpawns(MVWorld.this.spawning.getAnimalSettings().getSpawnRate());
}
if (MVWorld.this.spawning.getMonsterSettings().getSpawnRate() != -1) {
world.get().setTicksPerMonsterSpawns(MVWorld.this.spawning.getMonsterSettings().getSpawnRate());
}
world.get().setSpawnFlags(allowMonsters, allowAnimals);
plugin.getMVWorldManager().getTheWorldPurger().purgeWorld(MVWorld.this);
return super.validateChange(property, newValue, oldValue, object);
@@ -353,15 +364,15 @@ public class MVWorld extends SerializationConfig implements MultiverseWorld {
// --------------------------------------------------------------
// Begin properties
@Property(description = "Sorry, 'hidden' must either be: true or false.")
private boolean hidden;
private volatile boolean hidden;
@Property(description = "Alias must be a valid string.")
private String alias;
private volatile String alias;
@Property(serializor = EnumPropertySerializor.class, description = "Sorry, 'color' must be a valid color-name.")
private EnglishChatColor color;
private volatile EnglishChatColor color;
@Property(serializor = EnumPropertySerializor.class, description = "Sorry, 'style' must be a valid style-name.")
private EnglishChatStyle style;
private volatile EnglishChatStyle style;
@Property(description = "Sorry, 'pvp' must either be: true or false.", virtualType = Boolean.class, persistVirtual = true)
private VirtualProperty<Boolean> pvp = new VirtualProperty<Boolean>() {
private volatile VirtualProperty<Boolean> pvp = new VirtualProperty<Boolean>() {
@Override
public void set(Boolean newValue) {
world.get().setPVP(newValue);
@@ -373,14 +384,14 @@ public class MVWorld extends SerializationConfig implements MultiverseWorld {
}
};
@Property(validator = ScalePropertyValidator.class, description = "Scale must be a positive double value. ex: 2.3")
private double scale;
private volatile double scale;
@Property(validator = RespawnWorldPropertyValidator.class, description = "You must set this to the NAME not alias of a world.")
private String respawnWorld;
private volatile String respawnWorld;
@Property(validator = AllowWeatherPropertyValidator.class, description = "Sorry, this must either be: true or false.")
private boolean allowWeather;
private volatile boolean allowWeather;
@Property(serializor = DifficultyPropertySerializor.class, virtualType = Difficulty.class, persistVirtual = true,
description = "Difficulty must be set as one of the following: peaceful easy normal hard")
private VirtualProperty<Difficulty> difficulty = new VirtualProperty<Difficulty>() {
private volatile VirtualProperty<Difficulty> difficulty = new VirtualProperty<Difficulty>() {
@Override
public void set(Difficulty newValue) {
world.get().setDifficulty(newValue);
@@ -392,22 +403,22 @@ public class MVWorld extends SerializationConfig implements MultiverseWorld {
}
};
@Property(validator = SpawningPropertyValidator.class, description = "Sorry, 'animals' must either be: true or false.")
private SpawnSettings spawning;
private volatile SpawnSettings spawning;
@Property
private EntryFee entryfee;
private volatile EntryFee entryfee;
@Property(description = "Sorry, 'hunger' must either be: true or false.")
private boolean hunger;
private volatile boolean hunger;
@Property(description = "Sorry, 'autoheal' must either be: true or false.")
private boolean autoHeal;
private volatile boolean autoHeal;
@Property(description = "Sorry, 'adjustspawn' must either be: true or false.")
private boolean adjustSpawn;
private volatile boolean adjustSpawn;
@Property(serializor = EnumPropertySerializor.class, description = "Allow portal forming must be NONE, ALL, NETHER or END.")
private AllowedPortalType portalForm;
private volatile AllowedPortalType portalForm;
@Property(serializor = GameModePropertySerializor.class, validator = GameModePropertyValidator.class,
description = "GameMode must be set as one of the following: survival creative")
private GameMode gameMode;
private volatile GameMode gameMode;
@Property(description = "Sorry, this must either be: true or false.", virtualType = Boolean.class, persistVirtual = true)
private VirtualProperty<Boolean> keepSpawnInMemory = new VirtualProperty<Boolean>() {
private volatile VirtualProperty<Boolean> keepSpawnInMemory = new VirtualProperty<Boolean>() {
@Override
public void set(Boolean newValue) {
world.get().setKeepSpawnInMemory(newValue);
@@ -419,10 +430,10 @@ public class MVWorld extends SerializationConfig implements MultiverseWorld {
}
};
@Property
private SpawnLocation spawnLocation;
private volatile SpawnLocation spawnLocation;
@Property(validator = SpawnLocationPropertyValidator.class, virtualType = Location.class,
description = "There is no help available for this variable. Go bug Rigby90 about it.")
private VirtualProperty<Location> spawn = new VirtualProperty<Location>() {
private volatile VirtualProperty<Location> spawn = new VirtualProperty<Location>() {
@Override
public void set(Location newValue) {
if (getCBWorld() != null)
@@ -440,15 +451,14 @@ public class MVWorld extends SerializationConfig implements MultiverseWorld {
}
};
@Property(description = "Set this to false ONLY if you don't want this world to load itself on server restart.")
private boolean autoLoad;
private volatile boolean autoLoad;
@Property(description = "If a player dies in this world, shoudld they go to their bed?")
private boolean bedRespawn;
private volatile boolean bedRespawn;
@Property
private List<String> worldBlacklist;
@SuppressWarnings("unused") // it IS used!
private volatile List<String> worldBlacklist;
@Property(serializor = TimePropertySerializor.class, virtualType = Long.class,
description = "Set the time to whatever you want! (Will NOT freeze time)")
private VirtualProperty<Long> time = new VirtualProperty<Long>() {
private volatile VirtualProperty<Long> time = new VirtualProperty<Long>() {
@Override
public void set(Long newValue) {
world.get().setTime(newValue);
@@ -460,17 +470,20 @@ public class MVWorld extends SerializationConfig implements MultiverseWorld {
}
};
@Property
private Environment environment;
private volatile Environment environment;
@Property
private long seed;
private volatile long seed;
@Property
private String generator;
private volatile String generator;
@Property
private volatile int playerLimit;
// End of properties
// --------------------------------------------------------------
private Permission permission;
private Permission exempt;
private Permission ignoreperm;
private Permission limitbypassperm;
public MVWorld(boolean fixSpawn) {
super();
@@ -576,15 +589,21 @@ public class MVWorld extends SerializationConfig implements MultiverseWorld {
this.exempt = new Permission("multiverse.exempt." + this.getName(),
"A player who has this does not pay to enter this world, or use any MV portals in it " + this.getName(), PermissionDefault.OP);
this.limitbypassperm = new Permission("mv.bypass.playerlimit." + this.getName(),
"A player who can enter this world regardless of wether its full", PermissionDefault.OP);
try {
this.plugin.getServer().getPluginManager().addPermission(this.permission);
this.plugin.getServer().getPluginManager().addPermission(this.exempt);
this.plugin.getServer().getPluginManager().addPermission(this.ignoreperm);
this.plugin.getServer().getPluginManager().addPermission(this.limitbypassperm);
// Add the permission and exempt to parents.
this.addToUpperLists(this.permission);
// Add ignore to it's parent:
this.ignoreperm.addParent("mv.bypass.gamemode.*", true);
// Add limit bypass to it's parent
this.limitbypassperm.addParent("mv.bypass.playerlimit.*", true);
} catch (IllegalArgumentException e) {
this.plugin.log(Level.FINER, "Permissions nodes were already added for " + this.name);
}
@@ -613,16 +632,16 @@ public class MVWorld extends SerializationConfig implements MultiverseWorld {
// Not sure how it will work in the nether...
//Location newSpawn = this.spawnLocation.getWorld().getHighestBlockAt(this.spawnLocation).getLocation();
if (newSpawn != null) {
this.plugin.log(Level.INFO, String.format("New Spawn for '%s' is located at: %s",
this.getName(), plugin.getLocationManipulation().locationToString(newSpawn)));
Logging.info("New Spawn for '%s' is located at: %s",
this.getName(), plugin.getLocationManipulation().locationToString(newSpawn));
return newSpawn;
} else {
// If it's a standard end world, let's check in a better place:
Location newerSpawn;
newerSpawn = bs.getTopBlock(new Location(w, 0, 0, 0));
if (newerSpawn != null) {
this.plugin.log(Level.INFO, String.format("New Spawn for '%s' is located at: %s",
this.getName(), plugin.getLocationManipulation().locationToString(newerSpawn)));
Logging.info("New Spawn for '%s' is located at: %s",
this.getName(), plugin.getLocationManipulation().locationToString(newerSpawn));
return newerSpawn;
} else {
this.plugin.log(Level.SEVERE, "Safe spawn NOT found!!!");
@@ -656,6 +675,7 @@ public class MVWorld extends SerializationConfig implements MultiverseWorld {
this.bedRespawn = true;
this.worldBlacklist = new ArrayList<String>();
this.generator = null;
this.playerLimit = -1;
}
/**
@@ -664,7 +684,7 @@ public class MVWorld extends SerializationConfig implements MultiverseWorld {
* @see SerializationConfig
*/
protected static Map<String, String> getAliases() {
return propertyAliases;
return PROPERTY_ALIASES;
}
private static double getDefaultScale(Environment environment) {
@@ -914,6 +934,22 @@ public class MVWorld extends SerializationConfig implements MultiverseWorld {
public void setGenerator(String generator) {
this.setPropertyValueUnchecked("generator", generator);
}
/**
* {@inheritDoc}
*/
@Override
public int getPlayerLimit() {
return this.playerLimit;
}
/**
* {@inheritDoc}
*/
@Override
public void setPlayerLimit(int limit) {
this.setPropertyValueUnchecked("playerLimit", limit);
}
/**
* {@inheritDoc}
@@ -1398,11 +1434,13 @@ public class MVWorld extends SerializationConfig implements MultiverseWorld {
@Override
public String toString() {
StringBuilder toStringBuilder = new StringBuilder();
toStringBuilder.append(this.getClass().getSimpleName());
toStringBuilder.append('@');
toStringBuilder.append(this.hashCode());
toStringBuilder.append(" (Name: '").append(this.getName()).append("')");
return toStringBuilder.toString();
final JSONObject jsonData = new JSONObject();
jsonData.put("Name", getName());
jsonData.put("Env", getEnvironment().toString());
jsonData.put("Type", getWorldType().toString());
jsonData.put("Gen", getGenerator());
final JSONObject topLevel = new JSONObject();
topLevel.put(getClass().getSimpleName() + "@" + hashCode(), jsonData);
return topLevel.toString();
}
}
@@ -7,6 +7,8 @@
package com.onarandombox.MultiverseCore;
import buscript.Buscript;
import com.dumptruckman.minecraft.util.Logging;
import com.fernferret.allpay.AllPay;
import com.fernferret.allpay.GenericBank;
import com.onarandombox.MultiverseCore.api.BlockSafety;
@@ -20,6 +22,7 @@ import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.api.SafeTTeleporter;
import com.onarandombox.MultiverseCore.commands.AnchorCommand;
import com.onarandombox.MultiverseCore.commands.CheckCommand;
import com.onarandombox.MultiverseCore.commands.CloneCommand;
import com.onarandombox.MultiverseCore.commands.ConfigCommand;
import com.onarandombox.MultiverseCore.commands.ConfirmCommand;
import com.onarandombox.MultiverseCore.commands.CoordCommand;
@@ -42,7 +45,9 @@ import com.onarandombox.MultiverseCore.commands.PurgeCommand;
import com.onarandombox.MultiverseCore.commands.RegenCommand;
import com.onarandombox.MultiverseCore.commands.ReloadCommand;
import com.onarandombox.MultiverseCore.commands.RemoveCommand;
import com.onarandombox.MultiverseCore.commands.ScriptCommand;
import com.onarandombox.MultiverseCore.commands.SetSpawnCommand;
import com.onarandombox.MultiverseCore.commands.SilentCommand;
import com.onarandombox.MultiverseCore.commands.SpawnCommand;
import com.onarandombox.MultiverseCore.commands.TeleportCommand;
import com.onarandombox.MultiverseCore.commands.UnloadCommand;
@@ -57,24 +62,35 @@ import com.onarandombox.MultiverseCore.destination.PlayerDestination;
import com.onarandombox.MultiverseCore.destination.WorldDestination;
import com.onarandombox.MultiverseCore.event.MVVersionEvent;
import com.onarandombox.MultiverseCore.exceptions.PropertyDoesNotExistException;
import com.onarandombox.MultiverseCore.listeners.MVAsyncPlayerChatListener;
import com.onarandombox.MultiverseCore.listeners.MVChatListener;
import com.onarandombox.MultiverseCore.listeners.MVEntityListener;
import com.onarandombox.MultiverseCore.listeners.MVPlayerChatListener;
import com.onarandombox.MultiverseCore.listeners.MVPlayerListener;
import com.onarandombox.MultiverseCore.listeners.MVPluginListener;
import com.onarandombox.MultiverseCore.localization.LazyLocaleMessageProvider;
import com.onarandombox.MultiverseCore.localization.LocalizationLoadingException;
import com.onarandombox.MultiverseCore.localization.MessageProvider;
import com.onarandombox.MultiverseCore.localization.MessageProviding;
import com.onarandombox.MultiverseCore.localization.NoSuchLocalizationException;
import com.onarandombox.MultiverseCore.listeners.MVPortalListener;
import com.onarandombox.MultiverseCore.listeners.MVWeatherListener;
import com.onarandombox.MultiverseCore.localization.MultiverseMessage;
import com.onarandombox.MultiverseCore.localization.SimpleMessageProvider;
import com.onarandombox.MultiverseCore.utils.AnchorManager;
import com.onarandombox.MultiverseCore.utils.DebugLog;
import com.onarandombox.MultiverseCore.utils.MVMessaging;
import com.onarandombox.MultiverseCore.utils.MVPermissions;
import com.onarandombox.MultiverseCore.utils.MVPlayerSession;
import com.onarandombox.MultiverseCore.utils.SimpleBlockSafety;
import com.onarandombox.MultiverseCore.utils.SimpleLocationManipulation;
import com.onarandombox.MultiverseCore.utils.SimpleSafeTTeleporter;
import com.onarandombox.MultiverseCore.utils.VaultHandler;
import com.onarandombox.MultiverseCore.utils.WorldManager;
import com.pneumaticraft.commandhandler.CommandHandler;
import me.main__.util.SerializationConfig.SerializationConfig;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World.Environment;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.Configuration;
@@ -84,6 +100,7 @@ import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.mcstats.Metrics;
import java.io.File;
import java.io.IOException;
@@ -91,25 +108,27 @@ 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.Locale;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The implementation of the Multiverse-{@link Core}.
*/
public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
private static final int PROTOCOL = 15;
public class MultiverseCore extends JavaPlugin implements MVPlugin, Core, MessageProviding {
private static final int PROTOCOL = 18;
// TODO: Investigate if this one is really needed to be static.
// Doubt it. -- FernFerret
private static Map<String, String> teleportQueue = new HashMap<String, String>();
private AnchorManager anchorManager = new AnchorManager(this);
private MessageProvider messageProvider = new SimpleMessageProvider(this);
// TODO please let's make this non-static
private MultiverseCoreConfiguration config;
private volatile MultiverseCoreConfiguration config;
/**
* This method is used to find out who is teleporting a player.
@@ -132,7 +151,7 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
* @param teleportee The name of the player that was teleported.
*/
public static void addPlayerToTeleportQueue(String teleporter, String teleportee) {
staticLog(Level.FINEST, "Adding mapping '" + teleporter + "' => '" + teleportee + "' to teleport queue");
Logging.finest("Adding mapping '%s' => '%s' to teleport queue", teleporter, teleportee);
teleportQueue.put(teleportee, teleporter);
}
@@ -168,10 +187,6 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
return MultiverseCore.PROTOCOL;
}
// Useless stuff to keep us going.
private static final Logger LOGGER = Logger.getLogger("Minecraft");
private static DebugLog debugLog;
// Setup our Map for our Commands using the CommandHandler.
private CommandHandler commandHandler;
@@ -183,19 +198,22 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
// Configurations
private FileConfiguration multiverseConfig = null;
private MVWorldManager worldManager = new WorldManager(this);
private final MVWorldManager worldManager = new WorldManager(this);
// Setup the block/player/entity listener.
private MVPlayerListener playerListener = new MVPlayerListener(this);
private MVEntityListener entityListener = new MVEntityListener(this);
private MVPluginListener pluginListener = new MVPluginListener(this);
private MVWeatherListener weatherListener = new MVWeatherListener(this);
private MVPortalListener portalListener = new MVPortalListener(this);
private final MVPlayerListener playerListener = new MVPlayerListener(this);
private final MVEntityListener entityListener = new MVEntityListener(this);
private final MVPluginListener pluginListener = new MVPluginListener(this);
private final MVWeatherListener weatherListener = new MVWeatherListener(this);
private final MVPortalListener portalListener = new MVPortalListener(this);
private MVChatListener chatListener;
// HashMap to contain information relating to the Players.
private HashMap<String, MVPlayerSession> playerSessions;
private VaultHandler vaultHandler;
private GenericBank bank = null;
private AllPay banker;
private Buscript buscript;
private int pluginCount;
private DestinationFactory destFactory;
//private SpoutInterface spoutInterface = null;
@@ -215,9 +233,8 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
// Create our DataFolder
getDataFolder().mkdirs();
// Setup our Debug Log
debugLog = new DebugLog("Multiverse-Core", getDataFolder() + File.separator + "debug.log");
debugLog.setStandardLogger(LOGGER);
SerializationConfig.initLogging(debugLog);
Logging.init(this);
SerializationConfig.initLogging(Logging.getLogger());
// Setup our BlockSafety
this.blockSafety = new SimpleBlockSafety(this);
// Setup our LocationManipulation
@@ -238,21 +255,27 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
/**
* {@inheritDoc}
* @deprecated Now using Vault.
*/
@Override
@Deprecated
public GenericBank getBank() {
return this.bank;
}
@Override
public VaultHandler getVaultHandler() {
return vaultHandler;
}
/**
* {@inheritDoc}
*/
@Override
public void onEnable() {
this.messaging = new MVMessaging();
this.messaging = new MVMessaging(this);
this.banker = new AllPay(this, LOG_TAG + " ");
// Output a little snippet to show it's enabled.
this.log(Level.INFO, "- Version " + this.getDescription().getVersion() + " (API v" + PROTOCOL + ") Enabled - By " + getAuthors());
this.vaultHandler = new VaultHandler(this);
// Load the defaultWorldGenerators
this.worldManager.getDefaultWorldGenerators();
@@ -280,7 +303,28 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
// this function will be called every time a plugin registers a new envtype with MV
// Setup & Load our Configuration files.
loadConfigs();
try {
Locale l = (this.config.getLocale() == null) ? Locale.getDefault() : this.config.getLocale();
if (this.messageProvider instanceof LazyLocaleMessageProvider)
((LazyLocaleMessageProvider)this.messageProvider).loadLocale(l);
this.messageProvider.setLocale(l);
} catch (NoSuchLocalizationException e) {
if (this.config.getLocale() != null)
this.log(Level.SEVERE, String.format(
"Multiverse couldn't find any translations for the selected locale '%s'. '%s' will be used instead.",
this.config.getLocale(), this.messageProvider.getLocale()));
} catch (LocalizationLoadingException e) {
this.log(Level.SEVERE, String.format("Failed to load the selected locale '%s'. '%s' will be used instead.",
this.config.getLocale(), this.messageProvider.getLocale()));
e.printStackTrace();
} catch (IllegalArgumentException e) {
this.log(Level.SEVERE, e.getMessage());
this.getServer().getPluginManager().disablePlugin(this);
return;
}
if (this.multiverseConfig != null) {
Logging.setDebugLevel(getMVConfig().getGlobalDebug());
Logging.setShowingConfig(!getMVConfig().getSilentStart());
this.worldManager.loadDefaultWorlds();
this.worldManager.loadWorlds(true);
} else {
@@ -289,13 +333,25 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
this.anchorManager.loadAnchors();
// Now set the firstspawnworld (after the worlds are loaded):
this.worldManager.setFirstSpawnWorld(config.getFirstSpawnWorld());
this.worldManager.setFirstSpawnWorld(getMVConfig().getFirstSpawnWorld());
try {
config.setFirstSpawnWorld(this.worldManager.getFirstSpawnWorld().getName());
getMVConfig().setFirstSpawnWorld(this.worldManager.getFirstSpawnWorld().getName());
} catch (NullPointerException e) {
// A test that had no worlds loaded was being run. This should never happen in production
}
this.saveMVConfig();
// Register async or sync player chat according to config
try {
Class.forName("org.bukkit.event.player.AsyncPlayerChatEvent");
} catch (ClassNotFoundException e) {
getMVConfig().setUseAsyncChat(false);
}
if (getMVConfig().getUseAsyncChat()) {
this.chatListener = new MVAsyncPlayerChatListener(this, this.playerListener);
} else {
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) {
@@ -303,6 +359,112 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
this.log(Level.INFO, "Spout integration enabled.");
}
*/
this.initializeBuscript();
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());
}
/**
* Initializes the buscript javascript library.
*/
private void initializeBuscript() {
buscript = new Buscript(this);
// Add global variable "multiverse" to javascript environment
buscript.getGlobalScope().put("multiverse", buscript.getGlobalScope(), 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 static String envToString(Environment env) {
return new StringBuilder().append(env.name().toUpperCase().charAt(0))
.append(env.name().toLowerCase().substring(1)).toString();
}
@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;
}
}
/**
* 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;
}
@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;
}
}
private void setupMetrics() {
try {
Metrics m = new Metrics(this);
Metrics.Graph envGraph = m.createGraph("worlds_by_env");
for (Environment env : Environment.values())
envGraph.addPlotter(new EnvironmentPlotter(this, env));
m.addCustomData(new Metrics.Plotter("Loaded worlds") {
@Override
public int getValue() {
return getMVWorldManager().getMVWorlds().size();
}
});
m.addCustomData(new Metrics.Plotter("Total number of worlds") {
@Override
public int getValue() {
return getMVWorldManager().getMVWorlds().size()
+ getMVWorldManager().getUnloadedWorlds().size();
}
});
Set<String> gens = new HashSet<String>();
for (MultiverseWorld w : this.getMVWorldManager().getMVWorlds())
gens.add(w.getGenerator());
gens.remove(null);
gens.remove("null");
Metrics.Graph genGraph = m.createGraph("custom_gens");
for (String gen : gens)
genGraph.addPlotter(new GeneratorPlotter(this, gen));
m.start();
log(Level.FINE, "Metrics have run!");
} catch (IOException e) {
log(Level.WARNING, "There was an issue while enabling metrics: " + e.getMessage());
}
}
private void initializeDestinationFactory() {
@@ -344,15 +506,14 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
MultiverseCoreConfiguration wantedConfig = null;
try {
wantedConfig = (MultiverseCoreConfiguration) multiverseConfig.get("multiverse-configuration");
} catch (Exception e) {
// We're just thinking "no risk no fun" and therefore have to catch and forget this exception
} catch (Exception ignore) {
} finally {
config = ((wantedConfig == null) ? new MultiverseCoreConfiguration() : wantedConfig);
}
this.migrateWorldConfig();
this.worldManager.loadWorldConfig(new File(getDataFolder(), "worlds.yml"));
this.messaging.setCooldown(config.getMessageCooldown());
this.messaging.setCooldown(getMVConfig().getMessageCooldown());
// Remove old values.
this.multiverseConfig.set("enforcegamemodes", null);
@@ -370,47 +531,47 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
*/
private void migrate22Values() {
if (this.multiverseConfig.isSet("worldnameprefix")) {
this.log(Level.INFO, "Migrating 'worldnameprefix'...");
this.config.setPrefixChat(this.multiverseConfig.getBoolean("worldnameprefix"));
Logging.config("Migrating 'worldnameprefix'...");
this.getMVConfig().setPrefixChat(this.multiverseConfig.getBoolean("worldnameprefix"));
this.multiverseConfig.set("worldnameprefix", null);
}
if (this.multiverseConfig.isSet("firstspawnworld")) {
this.log(Level.INFO, "Migrating 'firstspawnworld'...");
this.config.setFirstSpawnWorld(this.multiverseConfig.getString("firstspawnworld"));
Logging.config("Migrating 'firstspawnworld'...");
this.getMVConfig().setFirstSpawnWorld(this.multiverseConfig.getString("firstspawnworld"));
this.multiverseConfig.set("firstspawnworld", null);
}
if (this.multiverseConfig.isSet("enforceaccess")) {
this.log(Level.INFO, "Migrating 'enforceaccess'...");
this.config.setEnforceAccess(this.multiverseConfig.getBoolean("enforceaccess"));
Logging.config("Migrating 'enforceaccess'...");
this.getMVConfig().setEnforceAccess(this.multiverseConfig.getBoolean("enforceaccess"));
this.multiverseConfig.set("enforceaccess", null);
}
if (this.multiverseConfig.isSet("displaypermerrors")) {
this.log(Level.INFO, "Migrating 'displaypermerrors'...");
this.config.setDisplayPermErrors(this.multiverseConfig.getBoolean("displaypermerrors"));
Logging.config("Migrating 'displaypermerrors'...");
this.getMVConfig().setDisplayPermErrors(this.multiverseConfig.getBoolean("displaypermerrors"));
this.multiverseConfig.set("displaypermerrors", null);
}
if (this.multiverseConfig.isSet("teleportintercept")) {
this.log(Level.INFO, "Migrating 'teleportintercept'...");
this.config.setTeleportIntercept(this.multiverseConfig.getBoolean("teleportintercept"));
Logging.config("Migrating 'teleportintercept'...");
this.getMVConfig().setTeleportIntercept(this.multiverseConfig.getBoolean("teleportintercept"));
this.multiverseConfig.set("teleportintercept", null);
}
if (this.multiverseConfig.isSet("firstspawnoverride")) {
this.log(Level.INFO, "Migrating 'firstspawnoverride'...");
this.config.setFirstSpawnOverride(this.multiverseConfig.getBoolean("firstspawnoverride"));
Logging.config("Migrating 'firstspawnoverride'...");
this.getMVConfig().setFirstSpawnOverride(this.multiverseConfig.getBoolean("firstspawnoverride"));
this.multiverseConfig.set("firstspawnoverride", null);
}
if (this.multiverseConfig.isSet("messagecooldown")) {
this.log(Level.INFO, "Migrating 'messagecooldown'...");
this.config.setMessageCooldown(this.multiverseConfig.getInt("messagecooldown"));
Logging.config("Migrating 'messagecooldown'...");
this.getMVConfig().setMessageCooldown(this.multiverseConfig.getInt("messagecooldown"));
this.multiverseConfig.set("messagecooldown", null);
}
if (this.multiverseConfig.isSet("debug")) {
this.log(Level.INFO, "Migrating 'debug'...");
this.config.setGlobalDebug(this.multiverseConfig.getInt("debug"));
Logging.config("Migrating 'debug'...");
this.getMVConfig().setGlobalDebug(this.multiverseConfig.getInt("debug"));
this.multiverseConfig.set("debug", null);
}
if (this.multiverseConfig.isSet("version")) {
this.log(Level.INFO, "Migrating 'version'...");
Logging.config("Migrating 'version'...");
this.multiverseConfig.set("version", null);
}
}
@@ -418,11 +579,11 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
/**
* Migrate the worlds.yml to SerializationConfig.
*/
private void migrateWorldConfig() {
private void migrateWorldConfig() { // SUPPRESS CHECKSTYLE: MethodLength
FileConfiguration wconf = YamlConfiguration
.loadConfiguration(new File(getDataFolder(), "worlds.yml"));
if (!wconf.isConfigurationSection("worlds")) {// empty config
if (!wconf.isConfigurationSection("worlds")) { // empty config
this.log(Level.FINE, "No worlds to migrate!");
return;
}
@@ -643,6 +804,7 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
this.commandHandler.registerCommand(new ListCommand(this));
this.commandHandler.registerCommand(new InfoCommand(this));
this.commandHandler.registerCommand(new CreateCommand(this));
this.commandHandler.registerCommand(new CloneCommand(this));
this.commandHandler.registerCommand(new ImportCommand(this));
this.commandHandler.registerCommand(new ReloadCommand(this));
this.commandHandler.registerCommand(new SetSpawnCommand(this));
@@ -669,8 +831,10 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
// Misc Commands
this.commandHandler.registerCommand(new EnvironmentCommand(this));
this.commandHandler.registerCommand(new DebugCommand(this));
this.commandHandler.registerCommand(new SilentCommand(this));
this.commandHandler.registerCommand(new GeneratorCommand(this));
this.commandHandler.registerCommand(new CheckCommand(this));
this.commandHandler.registerCommand(new ScriptCommand(this));
}
/**
@@ -679,10 +843,9 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
@Override
public void onDisable() {
this.saveMVConfigs();
debugLog.close();
this.banker = null;
this.bank = null;
log(Level.INFO, "- Disabled");
Logging.shutdown();
}
/**
@@ -693,7 +856,7 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
if (this.playerSessions.containsKey(player.getName())) {
return this.playerSessions.get(player.getName());
} else {
this.playerSessions.put(player.getName(), new MVPlayerSession(player, config));
this.playerSessions.put(player.getName(), new MVPlayerSession(player, getMVConfig()));
return this.playerSessions.get(player.getName());
}
}
@@ -723,12 +886,19 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
@Override
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
if (!this.isEnabled()) {
sender.sendMessage("This plugin is Disabled!");
this.messaging.sendMessage(sender, MultiverseMessage.CH_PLUGIN_DISABLED);
return true;
}
ArrayList<String> allArgs = new ArrayList<String>(Arrays.asList(args));
allArgs.add(0, command.getName());
return this.commandHandler.locateAndRunCommand(sender, allArgs, config.getDisplayPermErrors());
try {
return this.commandHandler.locateAndRunCommand(sender, allArgs, getMVConfig().getDisplayPermErrors());
} catch (Exception e) {
e.printStackTrace();
this.messaging.sendMessage(sender, MultiverseMessage.CH_INTERNAL_ERROR);
this.messaging.sendMessage(sender, sender.isOp() ? MultiverseMessage.CH_ADMIN_DEBUG : MultiverseMessage.CH_USER_DEBUG);
return true;
}
}
/**
@@ -736,7 +906,7 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
*/
@Override
public void log(Level level, String msg) {
staticLog(level, msg);
Logging.log(level, msg);
}
/**
@@ -744,30 +914,28 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
*
* @param level The Log-{@link Level}.
* @param msg The message to log.
*
* @deprecated Replaced by {@link Logging}. Please refrain from using this from a third party plugin as the
* messages will appear to originate from Multiverse-Core.
*/
@Deprecated
public static void staticLog(Level level, String msg) {
if (level == Level.FINE && MultiverseCoreConfiguration.getInstance().getGlobalDebug() >= 1) {
staticDebugLog(Level.INFO, msg);
} else if (level == Level.FINER && MultiverseCoreConfiguration.getInstance().getGlobalDebug() >= 2) {
staticDebugLog(Level.INFO, msg);
} else if (level == Level.FINEST && MultiverseCoreConfiguration.getInstance().getGlobalDebug() >= 3) {
staticDebugLog(Level.INFO, msg);
} else if (level != Level.FINE && level != Level.FINER && level != Level.FINEST) {
String message = LOG_TAG + " " + msg;
LOGGER.log(level, message);
debugLog.log(level, message);
}
Logging.log(level, msg);
}
/**
* Print messages to the Debug Log, if the servers in Debug Mode then we also wan't to print the messages to the
* Print messages to the Debug Log, if the servers in Debug Mode then we also want to print the messages to the
* standard Server Console.
*
* @param level The Log-{@link Level}
* @param msg The message
* @param msg The message
*
* @deprecated Replaced by {@link Logging}. Please refrain from using this from a third party plugin as the
* messages will appear to originate from Multiverse-Core.
*/
@Deprecated
public static void staticDebugLog(Level level, String msg) {
debugLog.log(level, msg);
Logging.log(level, msg);
}
/**
@@ -820,8 +988,8 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
* @param worldName The name of the invalid world
*/
public void showNotMVWorldMessage(CommandSender sender, String worldName) {
sender.sendMessage("Multiverse doesn't know about " + ChatColor.DARK_AQUA + worldName + ChatColor.WHITE + " yet.");
sender.sendMessage("Type " + ChatColor.DARK_AQUA + "/mv import ?" + ChatColor.WHITE + " for help!");
// TODO remove this method because we can now send this message in one line
this.messaging.sendMessage(sender, MultiverseMessage.GENERIC_NOT_MV_WORLD, worldName);
}
/**
@@ -861,16 +1029,20 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
/**
* {@inheritDoc}
* @deprecated Now using Vault.
*/
@Override
@Deprecated
public AllPay getBanker() {
return this.banker;
}
/**
* {@inheritDoc}
* @deprecated Now using Vault.
*/
@Override
@Deprecated
public void setBank(GenericBank bank) {
this.bank = bank;
}
@@ -952,6 +1124,15 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
return this.playerListener;
}
/**
* Gets the {@link MVChatListener}.
*
* @return The {@link MVChatListener}.
*/
public MVChatListener getChatListener() {
return this.chatListener;
}
/**
* Gets the {@link MVEntityListener}.
*
@@ -977,7 +1158,7 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
*/
public boolean saveMVConfig() {
try {
this.multiverseConfig.set("multiverse-configuration", config);
this.multiverseConfig.set("multiverse-configuration", getMVConfig());
this.multiverseConfig.save(new File(getDataFolder(), "config.yml"));
return true;
} catch (IOException e) {
@@ -1014,38 +1195,27 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
return this.worldManager.deleteWorld(name);
}
/**
* NOT deprecated for the time as queued commands use this.
* However, this is not in the API and other plugins should therefore not use it.
*
* @param oldName World to copy
* @param newName World to create
* @param generator The Custom generator plugin to use.
* @return True if success, false if fail.
*/
public Boolean cloneWorld(String oldName, String newName, String generator) {
return this.worldManager.cloneWorld(oldName, newName, generator);
}
/**
* {@inheritDoc}
* @deprecated This is deprecated!
*/
@Override
@Deprecated
public Boolean regenWorld(String name, Boolean useNewSeed, Boolean randomSeed, String seed) {
MultiverseWorld world = this.worldManager.getMVWorld(name);
if (world == null) {
return false;
}
List<Player> ps = world.getCBWorld().getPlayers();
if (useNewSeed) {
// Set the worldseed.
if (randomSeed) {
Random random = new Random();
Long newseed = random.nextLong();
seed = newseed.toString();
}
((WorldManager) this.worldManager).getConfigWorlds().set("worlds." + name + ".seed", seed);
}
if (this.worldManager.deleteWorld(name, false)) {
this.worldManager.loadWorlds(false);
SafeTTeleporter teleporter = this.getSafeTTeleporter();
Location newSpawn = this.getServer().getWorld(name).getSpawnLocation();
// Send all players that were in the old world, BACK to it!
for (Player p : ps) {
teleporter.safelyTeleport(null, p, newSpawn, true);
}
return true;
}
return false;
return this.worldManager.regenWorld(name, useNewSeed, randomSeed, seed);
}
/**
@@ -1056,6 +1226,25 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
return this.anchorManager;
}
/**
* {@inheritDoc}
*/
@Override
public MessageProvider getMessageProvider() {
return messageProvider;
}
/**
* {@inheritDoc}
*/
@Override
public void setMessageProvider(MessageProvider provider) {
if (provider == null)
throw new IllegalArgumentException("The new provider can't be null!");
messageProvider = provider;
}
/**
* {@inheritDoc}
*/
@@ -1122,4 +1311,9 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
public static MultiverseCoreConfiguration getStaticConfig() {
return MultiverseCoreConfiguration.getInstance();
}
@Override
public Buscript getScriptAPI() {
return buscript;
}
}
@@ -1,10 +1,13 @@
package com.onarandombox.MultiverseCore;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.api.MultiverseCoreConfig;
import com.onarandombox.MultiverseCore.configuration.LocaleSerializor;
import me.main__.util.SerializationConfig.NoSuchPropertyException;
import me.main__.util.SerializationConfig.Property;
import me.main__.util.SerializationConfig.SerializationConfig;
import java.util.Locale;
import java.util.Map;
/**
@@ -39,25 +42,31 @@ public class MultiverseCoreConfiguration extends SerializationConfig implements
}
@Property
private boolean enforceaccess;
private volatile boolean enforceaccess;
@Property
private boolean prefixchat;
private volatile boolean prefixchat;
@Property
private boolean teleportintercept;
private volatile boolean useasyncchat;
@Property
private boolean firstspawnoverride;
private volatile boolean teleportintercept;
@Property
private boolean displaypermerrors;
private volatile boolean firstspawnoverride;
@Property
private int globaldebug;
private volatile boolean displaypermerrors;
@Property
private int messagecooldown;
private volatile int globaldebug;
@Property
private double version;
private volatile boolean silentstart;
@Property
private String firstspawnworld;
private volatile int messagecooldown;
@Property
private int teleportcooldown;
private volatile double version;
@Property
private volatile String firstspawnworld;
@Property
private volatile int teleportcooldown;
@Property(serializor = LocaleSerializor.class)
private volatile Locale locale;
public MultiverseCoreConfiguration() {
super();
@@ -73,9 +82,10 @@ public class MultiverseCoreConfiguration extends SerializationConfig implements
* {@inheritDoc}
*/
@Override
public void setDefaults() {
protected void setDefaults() {
// BEGIN CHECKSTYLE-SUPPRESSION: MagicNumberCheck
enforceaccess = false;
useasyncchat = true;
prefixchat = true;
teleportintercept = true;
firstspawnoverride = true;
@@ -84,6 +94,7 @@ public class MultiverseCoreConfiguration extends SerializationConfig implements
messagecooldown = 5000;
teleportcooldown = 1000;
this.version = 2.9;
silentstart = false;
// END CHECKSTYLE-SUPPRESSION: MagicNumberCheck
}
@@ -195,6 +206,7 @@ public class MultiverseCoreConfiguration extends SerializationConfig implements
@Override
public void setGlobalDebug(int globalDebug) {
this.globaldebug = globalDebug;
Logging.setDebugLevel(globalDebug);
}
/**
@@ -260,4 +272,35 @@ public class MultiverseCoreConfiguration extends SerializationConfig implements
public void setTeleportCooldown(int teleportCooldown) {
this.teleportcooldown = teleportCooldown;
}
@Override
public void setUseAsyncChat(boolean useAsyncChat) {
this.useasyncchat = useAsyncChat;
}
@Override
public boolean getUseAsyncChat() {
return this.useasyncchat;
}
@Override
public Locale getLocale() {
return locale;
}
@Override
public void setLocale(Locale locale) {
this.locale = locale;
}
@Override
public void setSilentStart(boolean silentStart) {
Logging.setShowingConfig(!silentStart);
this.silentstart = silentStart;
}
@Override
public boolean getSilentStart() {
return silentstart;
}
}
@@ -35,6 +35,13 @@ public interface BlockSafety {
*/
boolean playerCanSpawnHereSafely(Location l);
/**
* Gets a safe bed spawn location OR null if the bed is invalid.
* @param l The location of the bead head (block with the pillow on it).
* @return Safe location around the bed or null if no location was found.
*/
Location getSafeBedSpawn(Location l);
/**
* Gets the location of the top block at the specified {@link Location}.
* @param l Any {@link Location}.
@@ -7,10 +7,18 @@
package com.onarandombox.MultiverseCore.api;
import buscript.Buscript;
import com.fernferret.allpay.AllPay;
import com.fernferret.allpay.GenericBank;
import com.onarandombox.MultiverseCore.destination.DestinationFactory;
import com.onarandombox.MultiverseCore.utils.*;
import com.onarandombox.MultiverseCore.utils.AnchorManager;
import com.onarandombox.MultiverseCore.utils.MVPermissions;
import com.onarandombox.MultiverseCore.utils.MVPlayerSession;
import com.onarandombox.MultiverseCore.utils.SimpleBlockSafety;
import com.onarandombox.MultiverseCore.utils.SimpleLocationManipulation;
import com.onarandombox.MultiverseCore.utils.SimpleSafeTTeleporter;
import com.onarandombox.MultiverseCore.utils.VaultHandler;
import com.onarandombox.MultiverseCore.utils.WorldManager;
import com.pneumaticraft.commandhandler.CommandHandler;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
@@ -35,9 +43,19 @@ public interface Core {
* Gets the Banking system that Multiverse-Core has hooked into.
*
* @return A {@link GenericBank} that can be used for payments.
* @deprecated Now using vault, see {@link VaultHandler#getEconomy}
*/
@Deprecated
GenericBank getBank();
/**
* Returns the Vault handler used by Multiverse. The returned object will have all methods necessary for
* interfacing with Vault.
*
* @return the Vault handler for Multiverse.
*/
VaultHandler getVaultHandler();
/**
* Reloads the Multiverse Configuration files:
* worlds.yml and config.yml.
@@ -128,21 +146,28 @@ public interface Core {
* @param seed The seed of the world.
*
* @return True if success, false if fail.
*
* @deprecated Use {@link MVWorldManager#regenWorld(String, boolean, boolean, String)} instead.
*/
@Deprecated
Boolean regenWorld(String name, Boolean useNewSeed, Boolean randomSeed, String seed);
/**
* Sets the {@link GenericBank}-Bank AllPay is using.
*
* @param bank The new {@link GenericBank}
* @deprecated Now using vault, see {@link VaultHandler#getEconomy}
*/
@Deprecated
void setBank(GenericBank bank);
/**
* Gets this plugin's {@link AllPay}-Banker.
*
* @return An {@link AllPay}-Banker
* @deprecated Now using vault, see {@link VaultHandler#getEconomy}
*/
@Deprecated
AllPay getBanker();
/**
@@ -222,4 +247,11 @@ public interface Core {
* @return The configuration.
*/
MultiverseCoreConfig getMVConfig();
/**
* Gets the buscript object for Multiverse. This is what handles Javascript processing.
*
* @return The Multiverse buscript object.
*/
Buscript getScriptAPI();
}
@@ -60,6 +60,16 @@ public interface MVWorldManager {
boolean addWorld(String name, Environment env, String seedString, WorldType type, Boolean generateStructures,
String generator, boolean useSpawnAdjust);
/**
* Make a copy of a world.
*
* @param oldName Name of world to be copied
* @param newName Name of world to be created
* @param generator The Custom generator plugin to use.
* @return True if the world is copied successfully, false if not.
*/
boolean cloneWorld(String oldName, String newName, String generator);
/**
* Remove the world from the Multiverse list, from the
* config and deletes the folder.
@@ -80,6 +90,17 @@ public interface MVWorldManager {
*/
boolean deleteWorld(String name, boolean removeConfig);
/**
*
* @param name The name of the world to remove
* @param removeFromConfig If true(default), we'll remove the entries from the
* config. If false, they'll stay and the world may come back.
* @param deleteWorldFolder If true the world folder will be completely deleted. If false
* only the contents of the world folder will be deleted
* @return True if success, false if failure.
*/
boolean deleteWorld(String name, boolean removeFromConfig, boolean deleteWorldFolder);
/**
* Unload a world from Multiverse.
*
@@ -245,4 +266,16 @@ public interface MVWorldManager {
* @return The {@link MultiverseWorld} new players should spawn in.
*/
MultiverseWorld getFirstSpawnWorld();
/**
* Regenerates a world.
*
* @param name Name of the world to regenerate
* @param useNewSeed If a new seed should be used
* @param randomSeed IF the new seed should be random
* @param seed The seed of the world.
*
* @return True if success, false if fail.
*/
boolean regenWorld(String name, boolean useNewSeed, boolean randomSeed, String seed);
}
@@ -1,5 +1,7 @@
package com.onarandombox.MultiverseCore.api;
import java.util.Locale;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
/**
@@ -133,4 +135,42 @@ public interface MultiverseCoreConfig extends ConfigurationSerializable {
* @return enforceAccess.
*/
boolean getEnforceAccess();
/**
* Sets useasyncchat.
* @param useAsyncChat The new value.
*/
void setUseAsyncChat(boolean useAsyncChat);
/**
* Gets useasyncchat.
* @return useasyncchat.
*/
boolean getUseAsyncChat();
/**
* Sets the locale.
* @param locale The new value.
*/
void setLocale(Locale locale);
/**
* Gets the locale.
* @return locale
*/
Locale getLocale();
/**
* Sets whether to suppress startup messages.
*
* @param silentStart true to suppress messages.
*/
void setSilentStart(boolean silentStart);
/**
* Whether we are suppressing startup messages.
*
* @return true if we are suppressing startup messages.
*/
boolean getSilentStart();
}
@@ -4,6 +4,8 @@ import java.util.Collection;
import org.bukkit.command.CommandSender;
import com.onarandombox.MultiverseCore.localization.MultiverseMessage;
/**
* Multiverse-messaging.
*/
@@ -14,6 +16,27 @@ public interface MultiverseMessaging {
*/
void setCooldown(int milliseconds);
/**
* Sends a message to the specified sender if the cooldown has passed.
*
* @param sender The person/console to send the message to.
* @param message The message to send.
* @param formatArgs Format arguments for the message.
* @return true if the message was sent, false if not.
*/
boolean sendMessage(CommandSender sender, MultiverseMessage message, Object...formatArgs);
/**
* Sends a message to the specified sender if the cooldown has passed.
*
* @param sender The person/console to send the message to.
* @param message The message to send.
* @param ignoreCooldown If true this message will always be sent. Useful for things like menus
* @param formatArgs Format arguments for the message.
* @return true if the message was sent, false if not.
*/
boolean sendMessage(CommandSender sender, MultiverseMessage message, boolean ignoreCooldown, Object... formatArgs);
/**
* Sends a message to the specified sender if the cooldown has passed.
*
@@ -12,6 +12,7 @@ import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.localization.MultiverseMessage;
import com.onarandombox.MultiverseCore.utils.DebugLog;
import com.pneumaticraft.commandhandler.CommandHandler;
@@ -49,7 +50,6 @@ public abstract class MultiversePlugin extends JavaPlugin implements MVPlugin {
}
this.setCore(theCore);
// Turn on Logging
this.getServer().getLogger().info(String.format("%s - Version %s enabled - By %s",
this.getDescription().getName(), this.getDescription().getVersion(), getAuthors()));
getDataFolder().mkdirs();
@@ -59,7 +59,7 @@ public abstract class MultiversePlugin extends JavaPlugin implements MVPlugin {
} catch (IOException e) {
e.printStackTrace();
}
debugLog = new DebugLog("Multiverse-Adventure", getDataFolder() + File.separator + "debug.log");
debugLog = new DebugLog(this.getDescription().getName(), getDataFolder() + File.separator + "debug.log");
debugLog.setTag(String.format("[%s-Debug]", this.getDescription().getName()));
this.onPluginEnable();
@@ -106,7 +106,7 @@ public abstract class MultiversePlugin extends JavaPlugin implements MVPlugin {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!this.isEnabled()) {
sender.sendMessage("This plugin is Disabled!");
this.core.getMessaging().sendMessage(sender, MultiverseMessage.CH_PLUGIN_DISABLED);
return true;
}
@@ -620,6 +620,22 @@ public interface MultiverseWorld {
* @param autoLoad True if players dying in this world respawn at their bed.
*/
void setBedRespawn(boolean autoLoad);
/**
* Sets the player limit for this world after which players without an override
* permission node will not be allowed in. A value of -1 or less signifies no limit
*
* @param limit The new limit
*/
void setPlayerLimit(int limit);
/**
* Gets the player limit for this world after which players without an override
* permission node will not be allowed in. A value of -1 or less signifies no limit
*
* @return The player limit
*/
int getPlayerLimit();
/**
* Same as {@link #getTime()}, but returns a string.
@@ -3,14 +3,14 @@ package com.onarandombox.MultiverseCore.api;
import java.util.List;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
/**
* Used to remove animals from worlds that don't belong there.
*/
public interface WorldPurger {
/**
* Synchronizes the given world with it's settings.
* Synchronizes the given worlds with their settings.
*
* @param worlds A list of {@link MultiverseWorld}
*/
@@ -46,4 +46,23 @@ public interface WorldPurger {
void purgeWorld(MultiverseWorld mvworld, List<String> thingsToKill, boolean negateAnimals,
boolean negateMonsters, CommandSender sender);
/**
* Determines whether the specified creature should be killed.
*
* @param e The creature.
* @param thingsToKill A {@link List} of animals/monsters to be killed.
* @param negateAnimals Whether the monsters in the list should be negated.
* @param negateMonsters Whether the animals in the list should be negated.
* @return {@code true} if the creature should be killed, otherwise {@code false}.
*/
boolean shouldWeKillThisCreature(Entity e, List<String> thingsToKill, boolean negateAnimals, boolean negateMonsters);
/**
* Determines whether the specified creature should be killed and automatically reads the params from a world object.
*
* @param w The world.
* @param e The creature.
* @return {@code true} if the creature should be killed, otherwise {@code false}.
*/
boolean shouldWeKillThisCreature(MultiverseWorld w, Entity e);
}
@@ -8,9 +8,12 @@
package com.onarandombox.MultiverseCore.commands;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.localization.MultiverseMessage;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionDefault;
import java.util.ArrayList;
@@ -34,7 +37,11 @@ public class AnchorCommand extends PaginatedCoreCommand<String> {
this.addCommandExample("/mv anchor " + ChatColor.GREEN + "otherthing");
this.addCommandExample("/mv anchor " + ChatColor.GREEN + "awesomething " + ChatColor.RED + "-d");
this.addCommandExample("/mv anchors ");
this.setPermission("multiverse.core.anchor", "Allows management of Anchor Destinations.", PermissionDefault.OP);
this.setPermission("multiverse.core.anchor.list", "Allows a player to list all anchors.", PermissionDefault.OP);
this.addAdditonalPermission(new Permission("multiverse.core.anchor.create",
"Allows a player to create anchors.", PermissionDefault.OP));
this.addAdditonalPermission(new Permission("multiverse.core.anchor.delete",
"Allows a player to delete anchors.", PermissionDefault.OP));
this.setItemsPerPage(8); // SUPPRESS CHECKSTYLE: MagicNumberCheck
}
@@ -49,7 +56,12 @@ public class AnchorCommand extends PaginatedCoreCommand<String> {
}
private void showList(CommandSender sender, List<String> args) {
sender.sendMessage(ChatColor.LIGHT_PURPLE + "====[ Multiverse Anchor List ]====");
if (!this.plugin.getMVPerms().hasPermission(sender, "multiverse.core.anchor.list", true)) {
this.plugin.getMessaging().sendMessage(sender, MultiverseMessage.CMD_ANCHOR_NOLISTPERM);
return;
}
this.plugin.getMessaging().sendMessage(sender, MultiverseMessage.CMD_ANCHOR_LISTHEADER);
Player p = null;
if (sender instanceof Player) {
p = (Player) sender;
@@ -62,13 +74,12 @@ public class AnchorCommand extends PaginatedCoreCommand<String> {
if (filterObject.getFilter().length() > 0) {
availableAnchors = this.getFilteredItems(availableAnchors, filterObject.getFilter());
if (availableAnchors.size() == 0) {
sender.sendMessage(ChatColor.RED + "Sorry... " + ChatColor.WHITE
+ "No anchors matched your filter: " + ChatColor.AQUA + filterObject.getFilter());
this.plugin.getMessaging().sendMessage(sender, MultiverseMessage.CMD_ANCHOR_NOMATCH, filterObject.getFilter());
return;
}
} else {
if (availableAnchors.size() == 0) {
sender.sendMessage(ChatColor.RED + "Sorry... " + ChatColor.WHITE + "No anchors were defined.");
this.plugin.getMessaging().sendMessage(sender, MultiverseMessage.CMD_ANCHOR_NODEF);
return;
}
}
@@ -89,7 +100,7 @@ public class AnchorCommand extends PaginatedCoreCommand<String> {
filterObject.setPage(1);
}
sender.sendMessage(ChatColor.AQUA + " Page " + filterObject.getPage() + " of " + totalPages);
this.plugin.getMessaging().sendMessage(sender, MultiverseMessage.CMD_ANCHOR_PAGEHEADER, filterObject.getPage(), totalPages);
this.showPage(filterObject.getPage(), sender, availableAnchors);
}
@@ -105,26 +116,24 @@ public class AnchorCommand extends PaginatedCoreCommand<String> {
return;
}
if (args.size() == 2 && args.get(1).equalsIgnoreCase("-d")) {
if (this.plugin.getAnchorManager().deleteAnchor(args.get(0))) {
sender.sendMessage("Anchor '" + args.get(0) + "' was successfully " + ChatColor.RED + "deleted!");
} else {
sender.sendMessage("Anchor '" + args.get(0) + "' was " + ChatColor.RED + " NOT " + ChatColor.WHITE + "deleted!");
}
if (!this.plugin.getMVPerms().hasPermission(sender, "multiverse.core.anchor.delete", true))
this.plugin.getMessaging().sendMessage(sender, MultiverseMessage.CMD_ANCHOR_NODELPERM);
else
this.plugin.getMessaging().sendMessage(sender, this.plugin.getAnchorManager().deleteAnchor(args.get(0))
? MultiverseMessage.CMD_ANCHOR_DELSUCCESS : MultiverseMessage.CMD_ANCHOR_DELFAIL, args.get(0));
return;
}
if (!(sender instanceof Player)) {
sender.sendMessage("You must be a player to create Anchors.");
this.plugin.getMessaging().sendMessage(sender, MultiverseMessage.CMD_ANCHOR_CONSOLECREATE);
return;
}
Player player = (Player) sender;
if (this.plugin.getAnchorManager().saveAnchorLocation(args.get(0), player.getLocation())) {
sender.sendMessage("Anchor '" + args.get(0) + "' was successfully " + ChatColor.GREEN + "created!");
} else {
sender.sendMessage("Anchor '" + args.get(0) + "' was " + ChatColor.RED + " NOT " + ChatColor.WHITE + "created!");
}
if (!this.plugin.getMVPerms().hasPermission(sender, "multiverse.core.anchor.create", true))
this.plugin.getMessaging().sendMessage(sender, MultiverseMessage.CMD_ANCHOR_NOCREATEPERM);
else
this.plugin.getMessaging().sendMessage(sender, this.plugin.getAnchorManager().saveAnchorLocation(args.get(0), ((Player) sender).getLocation())
? MultiverseMessage.CMD_ANCHOR_CREATESUCCESS : MultiverseMessage.CMD_ANCHOR_CREATEFAIL, args.get(0));
}
@Override
@@ -10,6 +10,7 @@ package com.onarandombox.MultiverseCore.commands;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVDestination;
import com.onarandombox.MultiverseCore.destination.InvalidDestination;
import com.onarandombox.MultiverseCore.localization.MultiverseMessage;
import com.onarandombox.MultiverseCore.utils.MVPermissions;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
@@ -39,15 +40,12 @@ public class CheckCommand extends MultiverseCommand {
public void runCommand(CommandSender sender, List<String> args) {
Player p = this.plugin.getServer().getPlayer(args.get(0));
if (p == null) {
sender.sendMessage("Could not find player " + ChatColor.GREEN + args.get(0));
sender.sendMessage("Are they online?");
this.messaging.sendMessage(sender, MultiverseMessage.CMD_CHECK_NOSUCHPLAYER, args.get(0));
return;
}
MVDestination dest = this.plugin.getDestFactory().getDestination(args.get(1));
if (dest instanceof InvalidDestination) {
sender.sendMessage(String.format("You asked if '%s' could go to %s%s%s,",
args.get(0), ChatColor.GREEN, args.get(0), ChatColor.WHITE));
sender.sendMessage("but I couldn't find a Destination of that name? Did you type it correctly?");
this.messaging.sendMessage(sender, MultiverseMessage.CMD_CHECK_NOSUCHDEST);
return;
}
@@ -0,0 +1,60 @@
/******************************************************************************
* 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 com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.localization.MultiverseMessage;
import com.pneumaticraft.commandhandler.CommandHandler;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.PermissionDefault;
import java.util.ArrayList;
import java.util.List;
/**
* Creates a clone of a world.
*/
public class CloneCommand extends MultiverseCommand {
private MVWorldManager worldManager;
public CloneCommand(MultiverseCore plugin) {
super(plugin);
this.setName("Clone World");
this.setCommandUsage("/mv clone" + ChatColor.GREEN + " {TARGET} {NAME}" + ChatColor.GOLD + " -g [GENERATOR[:ID]]");
this.setArgRange(2, 4); // SUPPRESS CHECKSTYLE: MagicNumberCheck
this.addKey("mvclone");
this.addKey("mvcl");
this.addKey("mv cl");
this.addKey("mv clone");
this.addCommandExample("/mv clone " + ChatColor.GOLD + "world" + ChatColor.GREEN + " world_backup");
this.addCommandExample("/mv clone " + ChatColor.GOLD + "skyblock_pristine" + ChatColor.GREEN + " skyblock");
this.addCommandExample("To clone a world that uses a generator:");
this.addCommandExample("/mv clone " + ChatColor.GOLD + "CleanRoom"
+ ChatColor.GREEN + " CleanRoomCopy" + ChatColor.DARK_AQUA + " -g CleanRoomGenerator");
this.setPermission("multiverse.core.clone", "Clones a world.", PermissionDefault.OP);
this.worldManager = this.plugin.getMVWorldManager();
}
@Override
public void runCommand(CommandSender sender, List<String> args) {
Class<?>[] paramTypes = {String.class, String.class, String.class};
List<Object> objectArgs = new ArrayList<Object>();
objectArgs.add(args.get(0));
objectArgs.add(args.get(1));
objectArgs.add(CommandHandler.getFlag("-g", args));
if (!this.worldManager.isMVWorld(args.get(0))) {
// If no world was found, we can't clone.
this.messaging.sendMessage(sender, MultiverseMessage.CMD_CLONE_NOSUCHWORLD, args.get(0));
return;
}
this.plugin.getCommandHandler().queueCommand(sender, "mvclone", "cloneWorld", objectArgs,
paramTypes, ChatColor.GREEN + "World Cloned!", ChatColor.RED + "World could NOT be cloned!");
}
}
@@ -8,6 +8,8 @@
package com.onarandombox.MultiverseCore.commands;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.localization.MultiverseMessage;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.PermissionDefault;
@@ -52,7 +54,7 @@ public class ConfigCommand extends MultiverseCommand {
return;
}
if (!this.plugin.getMVConfig().setConfigProperty(args.get(0).toLowerCase(), args.get(1))) {
sender.sendMessage(String.format("%sSetting '%s' to '%s' failed!", ChatColor.RED, args.get(0).toLowerCase(), args.get(1)));
this.messaging.sendMessage(sender, MultiverseMessage.CMD_CONFIG_SETFAIL, args.get(0), args.get(1));
return;
}
@@ -63,10 +65,10 @@ public class ConfigCommand extends MultiverseCommand {
}
if (this.plugin.saveMVConfigs()) {
sender.sendMessage(ChatColor.GREEN + "SUCCESS!" + ChatColor.WHITE + " Values were updated successfully!");
this.messaging.sendMessage(sender, MultiverseMessage.CMD_CLONE_SUCCESS);
this.plugin.loadConfigs();
} else {
sender.sendMessage(ChatColor.RED + "FAIL!" + ChatColor.WHITE + " Check your console for details!");
this.messaging.sendMessage(sender, MultiverseMessage.CMD_CONFIG_FAIL);
}
}
}
@@ -9,6 +9,7 @@ package com.onarandombox.MultiverseCore.commands;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.localization.MultiverseMessage;
import com.pneumaticraft.commandhandler.CommandHandler;
import org.bukkit.ChatColor;
import org.bukkit.World.Environment;
@@ -18,6 +19,8 @@ import org.bukkit.command.CommandSender;
import org.bukkit.permissions.PermissionDefault;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
@@ -65,15 +68,19 @@ public class CreateCommand extends MultiverseCommand {
}
}
if (worldFile.exists() || this.worldManager.isMVWorld(worldName)) {
sender.sendMessage(ChatColor.RED + "A Folder/World already exists with this name!");
sender.sendMessage(ChatColor.RED + "If you are confident it is a world you can import with /mvimport");
if (this.worldManager.isMVWorld(worldName)) {
this.messaging.sendMessage(sender, MultiverseMessage.CMD_CREATE_WORLDEXISTS, worldName);
return;
}
if (worldFile.exists()) {
this.messaging.sendMessage(sender, MultiverseMessage.CMD_CREATE_FILEEXISTS);
return;
}
Environment environment = EnvironmentCommand.getEnvFromString(env);
if (environment == null) {
sender.sendMessage(ChatColor.RED + "That is not a valid environment.");
this.messaging.sendMessage(sender, MultiverseMessage.CMD_CREATE_INVALIDENV);
EnvironmentCommand.showEnvironments(sender);
return;
}
@@ -84,17 +91,29 @@ public class CreateCommand extends MultiverseCommand {
}
WorldType type = EnvironmentCommand.getWorldTypeFromString(typeString);
if (type == null) {
sender.sendMessage(ChatColor.RED + "That is not a valid World Type.");
this.messaging.sendMessage(sender, MultiverseMessage.CMD_CREATE_INVALIDTYPE);
EnvironmentCommand.showWorldTypes(sender);
return;
}
Command.broadcastCommandMessage(sender, "Starting creation of world '" + worldName + "'...");
// Determine if the generator is valid. #918
if (generator != null) {
List<String> genarray = new ArrayList<String>(Arrays.asList(generator.split(":")));
if (genarray.size() < 2) {
// If there was only one arg specified, pad with another empty one.
genarray.add("");
}
if (this.worldManager.getChunkGenerator(genarray.get(0), genarray.get(1), "test") == null) {
// We have an invalid generator.
this.messaging.sendMessage(sender, MultiverseMessage.CMD_CREATE_INVALIDGEN, generator);
return;
}
}
Command.broadcastCommandMessage(sender, this.plugin.getMessageProvider().getMessage(MultiverseMessage.CMD_CREATE_START, worldName));
if (this.worldManager.addWorld(worldName, environment, seed, type, allowStructures, generator, useSpawnAdjust)) {
Command.broadcastCommandMessage(sender, "Complete!");
Command.broadcastCommandMessage(sender, this.plugin.getMessageProvider().getMessage(MultiverseMessage.CMD_CREATE_COMPLETE));
} else {
Command.broadcastCommandMessage(sender, "FAILED.");
Command.broadcastCommandMessage(sender, this.plugin.getMessageProvider().getMessage(MultiverseMessage.CMD_CREATE_FAILED));
}
}
}
@@ -23,7 +23,7 @@ public class DebugCommand extends MultiverseCommand {
public DebugCommand(MultiverseCore plugin) {
super(plugin);
this.setName("Turn Debug on/off?");
this.setCommandUsage("/mv debug" + ChatColor.GOLD + " [1|2|3|off]");
this.setCommandUsage("/mv debug" + ChatColor.GOLD + " [1|2|3|off|silent]");
this.setArgRange(0, 1);
this.addKey("mv debug");
this.addKey("mv d");
@@ -48,17 +48,18 @@ public class DebugCommand extends MultiverseCommand {
sender.sendMessage(ChatColor.RED + "Error" + ChatColor.WHITE
+ " setting debug level. Please use a number 0-3 " + ChatColor.AQUA + "(3 being many many messages!)");
}
}
plugin.saveMVConfigs();
}
this.displayDebugMode(sender);
}
private void displayDebugMode(CommandSender sender) {
if (plugin.getMVConfig().getGlobalDebug() == 0) {
final int debugLevel = plugin.getMVConfig().getGlobalDebug();
if (debugLevel == 0) {
sender.sendMessage("Multiverse Debug mode is " + ChatColor.RED + "OFF");
} else {
sender.sendMessage("Multiverse Debug mode is " + ChatColor.GREEN + plugin.getMVConfig().getGlobalDebug());
sender.sendMessage("Multiverse Debug mode is " + ChatColor.GREEN + debugLevel);
this.plugin.log(Level.FINE, "Multiverse Debug ENABLED");
}
}
@@ -53,8 +53,8 @@ public class EnvironmentCommand extends MultiverseCommand {
*/
public static void showWorldTypes(CommandSender sender) {
sender.sendMessage(ChatColor.YELLOW + "Valid World Types are:");
sender.sendMessage(String.format("%sNORMAL%s, %sFLAT %sor %sVERSION_1_1",
ChatColor.GREEN, ChatColor.WHITE, ChatColor.AQUA, ChatColor.WHITE, ChatColor.GOLD));
sender.sendMessage(String.format("%sNORMAL%s, %sFLAT, %sLARGEBIOMES %sor %sVERSION_1_1",
ChatColor.GREEN, ChatColor.WHITE, ChatColor.AQUA, ChatColor.RED, ChatColor.WHITE, ChatColor.GOLD));
}
@Override
@@ -75,6 +75,9 @@ public class EnvironmentCommand extends MultiverseCommand {
type = "NORMAL";
if (type.equalsIgnoreCase("flat"))
type = "FLAT";
if (type.equalsIgnoreCase("largebiomes")) {
type = "LARGE_BIOMES";
}
try {
// Now that we've converted a potentially unfriendly value
// to a friendly one, get it from the ENUM!
@@ -7,7 +7,10 @@
package com.onarandombox.MultiverseCore.commands;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.localization.MultiverseMessage;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.PermissionDefault;
@@ -15,7 +18,6 @@ import org.bukkit.plugin.Plugin;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
/**
* Returns a list of loaded generator plugins.
@@ -24,7 +26,7 @@ public class GeneratorCommand extends MultiverseCommand {
public GeneratorCommand(MultiverseCore plugin) {
super(plugin);
this.setName("World Information");
this.setName("Generator Information");
this.setCommandUsage("/mv generators");
this.setArgRange(0, 0);
this.addKey("mv generators");
@@ -37,7 +39,7 @@ public class GeneratorCommand extends MultiverseCommand {
@Override
public void runCommand(CommandSender sender, List<String> args) {
this.plugin.log(Level.INFO, "PLEASE IGNORE the 'Plugin X does not contain any generators' message below!");
Logging.info("PLEASE IGNORE the 'Plugin X does not contain any generators' message below!");
Plugin[] plugins = this.plugin.getServer().getPluginManager().getPlugins();
List<String> generators = new ArrayList<String>();
for (Plugin p : plugins) {
@@ -45,16 +47,16 @@ public class GeneratorCommand extends MultiverseCommand {
generators.add(p.getDescription().getName());
}
}
sender.sendMessage(ChatColor.AQUA + "--- Loaded Generator Plugins ---");
this.messaging.sendMessage(sender, MultiverseMessage.CMD_GENERATOR_LISTHEADER);
String loadedGens = "";
boolean altColor = false;
for (String s : generators) {
loadedGens += (altColor ? ChatColor.YELLOW : ChatColor.WHITE) + s + " ";
altColor = !altColor;
}
if (loadedGens.length() == 0) {
loadedGens = ChatColor.RED + "No Generator Plugins found.";
}
sender.sendMessage(loadedGens);
if (loadedGens.length() == 0)
this.messaging.sendMessage(sender, MultiverseMessage.CMD_GENERATOR_NOGENSFOUND);
else
this.messaging.sendMessage(sender, loadedGens, false);
}
}
@@ -124,8 +124,13 @@ public class InfoCommand extends MultiverseCommand {
message.add(new FancyMessage("Spawn Location: ", plugin.getLocationManipulation().strCoords(spawn), colors));
message.add(new FancyMessage("World Scale: ", world.getScaling() + "", colors));
if (world.getPrice() > 0) {
message.add(new FancyMessage("Price to enter this world: ",
this.plugin.getBank().getFormattedAmount(p, world.getPrice(), world.getCurrency()), colors));
final String formattedAmount;
if (world.getCurrency() <= 0 && plugin.getVaultHandler().getEconomy() != null) {
formattedAmount = plugin.getVaultHandler().getEconomy().format(world.getPrice());
} else {
formattedAmount = this.plugin.getBank().getFormattedAmount(p, world.getPrice(), world.getCurrency());
}
message.add(new FancyMessage("Price to enter this world: ", formattedAmount, colors));
} else {
message.add(new FancyMessage("Price to enter this world: ", ChatColor.GREEN + "FREE!", colors));
}
@@ -9,6 +9,8 @@ package com.onarandombox.MultiverseCore.commands;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.localization.MessageProvider;
import com.onarandombox.MultiverseCore.localization.MultiverseMessage;
import org.bukkit.ChatColor;
import org.bukkit.World.Environment;
import org.bukkit.command.CommandSender;
@@ -22,16 +24,18 @@ import java.util.List;
* Displays a listing of all worlds that a player can enter.
*/
public class ListCommand extends PaginatedCoreCommand<String> {
private MessageProvider provider;
public ListCommand(MultiverseCore plugin) {
super(plugin);
this.setName("World Listing");
provider = plugin.getMessageProvider();
this.setName(provider.getMessage(MultiverseMessage.CMD_LIST_NAME));
this.setCommandUsage("/mv list");
this.setArgRange(0, 2);
this.addKey("mvlist");
this.addKey("mvl");
this.addKey("mv list");
this.setPermission("multiverse.core.list.worlds", "Displays a listing of all worlds that you can enter.", PermissionDefault.OP);
this.setPermission("multiverse.core.list.worlds", provider.getMessage(MultiverseMessage.CMD_LIST_DESC), PermissionDefault.OP);
this.setItemsPerPage(8); // SUPPRESS CHECKSTYLE: MagicNumberCheck
}
@@ -66,7 +70,7 @@ public class ListCommand extends PaginatedCoreCommand<String> {
}
for (String name : this.plugin.getMVWorldManager().getUnloadedWorlds()) {
if (p == null || this.plugin.getMVPerms().hasPermission(p, "multiverse.access." + name, true)) {
worldList.add(ChatColor.GRAY + name + " - UNLOADED");
worldList.add(ChatColor.GRAY + name + " - " + "UNLOADED");
}
}
return worldList;
@@ -91,7 +95,7 @@ public class ListCommand extends PaginatedCoreCommand<String> {
@Override
public void runCommand(CommandSender sender, List<String> args) {
sender.sendMessage(ChatColor.LIGHT_PURPLE + "====[ Multiverse World List ]====");
sender.sendMessage(ChatColor.LIGHT_PURPLE + "====[ " + this.provider.getMessage(MultiverseMessage.CMD_LIST_TITLE) + " ]====");
Player p = null;
if (sender instanceof Player) {
p = (Player) sender;
@@ -104,8 +108,7 @@ public class ListCommand extends PaginatedCoreCommand<String> {
if (filterObject.getFilter().length() > 0) {
availableWorlds = this.getFilteredItems(availableWorlds, filterObject.getFilter());
if (availableWorlds.size() == 0) {
sender.sendMessage(ChatColor.RED + "Sorry... " + ChatColor.WHITE
+ "No worlds matched your filter: " + ChatColor.AQUA + filterObject.getFilter());
sender.sendMessage(ChatColor.RED + "Sorry... " + ChatColor.WHITE + provider.getMessage(MultiverseMessage.CMD_LIST_NO_MATCH) + " " + ChatColor.AQUA + filterObject.getFilter());
return;
}
}
@@ -85,6 +85,9 @@ public class ModifyAddCommand extends MultiverseCommand {
if (world.addToVariable(property, value)) {
sender.sendMessage(ChatColor.GREEN + "Success! " + ChatColor.AQUA
+ value + ChatColor.WHITE + " was " + ChatColor.GREEN + "added to " + ChatColor.GREEN + property);
if (!plugin.saveWorldConfig()) {
sender.sendMessage(ChatColor.RED + "There was an issue saving worlds.yml! Your changes will only be temporary!");
}
} else {
sender.sendMessage(value + " could not be added to " + property);
}
@@ -80,6 +80,9 @@ public class ModifyClearCommand extends MultiverseCommand {
sender.sendMessage(property + " was cleared. It contains 0 values now.");
sender.sendMessage(ChatColor.GREEN + "Success! " + ChatColor.AQUA + property + ChatColor.WHITE + " was "
+ ChatColor.GREEN + "CLEARED" + ChatColor.WHITE + ". It contains " + ChatColor.LIGHT_PURPLE + "0" + ChatColor.WHITE + " values now.");
if (!plugin.saveWorldConfig()) {
sender.sendMessage(ChatColor.RED + "There was an issue saving worlds.yml! Your changes will only be temporary!");
}
} else {
sender.sendMessage(ChatColor.RED + "Error: " + ChatColor.GOLD + property
+ ChatColor.WHITE + " was " + ChatColor.GOLD + "NOT" + ChatColor.WHITE + " cleared.");
@@ -85,6 +85,9 @@ public class ModifyRemoveCommand extends MultiverseCommand {
if (world.removeFromVariable(property, value)) {
sender.sendMessage(ChatColor.GREEN + "Success! " + ChatColor.AQUA + value + ChatColor.WHITE
+ " was " + ChatColor.RED + "removed from " + ChatColor.GREEN + property);
if (!plugin.saveWorldConfig()) {
sender.sendMessage(ChatColor.RED + "There was an issue saving worlds.yml! Your changes will only be temporary!");
}
} else {
sender.sendMessage(ChatColor.RED + "There was an error removing " + ChatColor.GRAY
+ value + ChatColor.WHITE + " from " + ChatColor.GOLD + property);
@@ -111,6 +111,9 @@ public class ModifySetCommand extends MultiverseCommand {
if (world.setPropertyValue(property, value)) {
sender.sendMessage(ChatColor.GREEN + "Success!" + ChatColor.WHITE + " Property " + ChatColor.AQUA + property
+ ChatColor.WHITE + " was set to " + ChatColor.GREEN + value);
if (!plugin.saveWorldConfig()) {
sender.sendMessage(ChatColor.RED + "There was an issue saving worlds.yml! Your changes will only be temporary!");
}
} else {
sender.sendMessage(ChatColor.RED + world.getPropertyHelp(property));
}
@@ -0,0 +1,54 @@
/******************************************************************************
* 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 java.io.File;
import java.util.List;
/**
* States who is in what world.
*/
public class ScriptCommand extends MultiverseCommand {
public ScriptCommand(MultiverseCore plugin) {
super(plugin);
this.setName("Runs a script.");
this.setCommandUsage("/mv script" + ChatColor.GOLD + " {script} [target]");
this.setArgRange(1, 2);
this.addKey("mv script");
this.addKey("mvscript");
this.addCommandExample(String.format("/mv script %sscript.txt", ChatColor.GOLD));
this.addCommandExample(String.format("/mv script %stest.txt %ssomeplayer", ChatColor.GOLD, ChatColor.GREEN));
this.setPermission("multiverse.core.script", "Runs a script.", PermissionDefault.OP);
}
@Override
public void runCommand(CommandSender sender, List<String> args) {
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!");
return;
}
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
String target = null;
if (args.size() == 2) {
target = args.get(1);
}
plugin.getScriptAPI().executeScript(file, target, player);
sender.sendMessage(String.format("Script '%s%s%s' finished!", ChatColor.GOLD, file.getName(), ChatColor.WHITE));
}
}
@@ -0,0 +1,52 @@
/******************************************************************************
* 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.permissions.PermissionDefault;
import java.util.List;
/**
* Enables debug-information.
*/
public class SilentCommand extends MultiverseCommand {
public SilentCommand(MultiverseCore plugin) {
super(plugin);
this.setName("Turn silent mode on/off?");
this.setCommandUsage("/mv silent" + ChatColor.GOLD + " [true|false|on|off]");
this.setArgRange(0, 1);
this.addKey("mv silent");
this.addKey("mvsilent");
this.addCommandExample("/mv silent " + ChatColor.GOLD + "true");
this.setPermission("multiverse.core.silent", "Reduces the amount of startup messages.", PermissionDefault.OP);
}
@Override
public void runCommand(CommandSender sender, List<String> args) {
if (args.size() == 1) {
if (args.get(0).equalsIgnoreCase("on")) {
args.set(0, "true");
}
plugin.getMVConfig().setSilentStart(Boolean.valueOf(args.get(0)));
plugin.saveMVConfigs();
}
this.displaySilentMode(sender);
}
private void displaySilentMode(CommandSender sender) {
if (plugin.getMVConfig().getSilentStart()) {
sender.sendMessage("Multiverse Silent Start mode is " + ChatColor.GREEN + "ON");
} else {
sender.sendMessage("Multiverse Silent Start mode is " + ChatColor.RED + "OFF");
}
}
}
@@ -7,6 +7,7 @@
package com.onarandombox.MultiverseCore.commands;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.event.MVVersionEvent;
import com.onarandombox.MultiverseCore.utils.webpaste.BitlyURLShortener;
@@ -15,14 +16,12 @@ 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 org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.PermissionDefault;
import java.util.List;
import java.util.logging.Level;
/**
* Dumps version info to the console.
@@ -52,9 +51,15 @@ public class VersionCommand extends MultiverseCommand {
StringBuilder buffer = new StringBuilder();
buffer.append("[Multiverse-Core] Multiverse-Core Version: ").append(this.plugin.getDescription().getVersion()).append('\n');
buffer.append("[Multiverse-Core] Bukkit Version: ").append(this.plugin.getServer().getVersion()).append('\n');
buffer.append("[Multiverse-Core] Loaded Worlds: ").append(this.plugin.getMVWorldManager().getMVWorlds().size()).append('\n');
buffer.append("[Multiverse-Core] Loaded Worlds: ").append(this.plugin.getMVWorldManager().getMVWorlds()).append('\n');
buffer.append("[Multiverse-Core] Multiverse Plugins Loaded: ").append(this.plugin.getPluginCount()).append('\n');
buffer.append("[Multiverse-Core] Economy being used: ").append(this.plugin.getBank().getEconUsed()).append('\n');
final boolean usingVault = plugin.getVaultHandler().getEconomy() != null;
buffer.append("[Multiverse-Core] Using Vault: ").append(usingVault).append('\n');
if (usingVault) {
buffer.append("[Multiverse-Core] Economy being used: ").append(plugin.getVaultHandler().getEconomy().getName()).append('\n');
} else {
buffer.append("[Multiverse-Core] Economy being used: ").append(this.plugin.getBank().getEconUsed()).append('\n');
}
buffer.append("[Multiverse-Core] Permissions Plugin: ").append(this.plugin.getMVPerms().getType()).append('\n');
buffer.append("[Multiverse-Core] Dumping Config Values: (version ")
.append(this.plugin.getMVConfig().getVersion()).append(")").append('\n');
@@ -76,7 +81,7 @@ public class VersionCommand extends MultiverseCommand {
final String data = versionEvent.getVersionInfo();
String[] lines = data.split("\n");
for (String line : lines) {
this.plugin.log(Level.INFO, line);
Logging.info(line);
}
this.plugin.getServer().getScheduler().scheduleAsyncDelayedTask(this.plugin, new Runnable() {
@@ -93,7 +98,7 @@ public class VersionCommand extends MultiverseCommand {
}
sender.sendMessage("Version info dumped here: " + ChatColor.GREEN + pasteUrl);
plugin.log(Level.INFO, "Version info dumped here: " + pasteUrl);
Logging.info("Version info dumped here: %s", pasteUrl);
}
}
});
@@ -15,6 +15,8 @@ import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.PermissionDefault;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
/**
@@ -50,6 +52,14 @@ public class WhoCommand extends MultiverseCommand {
showAll = false;
}
final Player[] onlinePlayers = plugin.getServer().getOnlinePlayers();
final Collection<Player> visiblePlayers = new HashSet<Player>(onlinePlayers.length);
for (final Player player : onlinePlayers) {
if (p == null || p.canSee(player)) {
visiblePlayers.add(player);
}
}
if (args.size() == 1) {
if (args.get(0).equalsIgnoreCase("--all") || args.get(0).equalsIgnoreCase("-a")) {
showAll = true;
@@ -68,18 +78,19 @@ public class WhoCommand extends MultiverseCommand {
sender.sendMessage(String.format("%s--- Players in %s%s ---", ChatColor.AQUA,
world.getColoredWorldString(), ChatColor.AQUA));
sender.sendMessage(buildPlayerString(world, p));
sender.sendMessage(this.buildPlayerString(world, p, visiblePlayers));
return;
}
}
// multiworld mode
sender.sendMessage(ChatColor.AQUA + "--- Worlds and their players ---");
sender.sendMessage(ChatColor.AQUA + "--- Worlds and their players --- "
+ visiblePlayers.size() + "/" + plugin.getServer().getMaxPlayers());
boolean shownOne = false;
for (MultiverseWorld world : this.worldManager.getMVWorlds()) {
if (this.plugin.getMVPerms().canEnterWorld(p, world)) { // only show world if the player can access it
if (showAll || !world.getCBWorld().getPlayers().isEmpty()) { // either show all or show if the world is not empty
sender.sendMessage(String.format("%s%s - %s", world.getColoredWorldString(), ChatColor.WHITE, buildPlayerString(world, p)));
sender.sendMessage(String.format("%s%s - %s", world.getColoredWorldString(), ChatColor.WHITE, buildPlayerString(world, p, visiblePlayers)));
shownOne = true;
}
}
@@ -90,18 +101,18 @@ public class WhoCommand extends MultiverseCommand {
return;
}
private static String buildPlayerString(MultiverseWorld world, Player viewer) {
private static String buildPlayerString(MultiverseWorld world, Player viewer, final Collection<Player> visiblePlayers) {
// Retrieve the players in this world
List<Player> players = world.getCBWorld().getPlayers();
if (players.size() == 0) {
return "No players found.";
} else {
StringBuilder playerBuilder = new StringBuilder();
for (Player player : players) {
if ((viewer == null) || viewer.canSee(player))
playerBuilder.append(player.getDisplayName()).append(", ");
}
String bString = playerBuilder.toString();
return bString.substring(0, bString.length() - 2);
StringBuilder playerBuilder = new StringBuilder();
for (Player player : players) {
// If the viewer is the console or the viewier is allowed to see the player, show them.
// Make sure we're also ONLY showing online players.
// Since we already checked visible players, we'll just make sure who we're about to show is in that.
if (visiblePlayers.contains(player))
playerBuilder.append(player.getDisplayName()).append(", ");
}
String bString = playerBuilder.toString();
return (bString.length() == 0) ? "No players found." : bString.substring(0, bString.length() - 2);
}
}
@@ -0,0 +1,24 @@
package com.onarandombox.MultiverseCore.configuration;
import java.util.Locale;
import me.main__.util.SerializationConfig.IllegalPropertyValueException;
import me.main__.util.SerializationConfig.Serializor;
public class LocaleSerializor implements Serializor<Locale, String> {
/**
* {@inheritDoc}
*/
@Override
public Locale deserialize(String arg0, Class<Locale> arg1) throws IllegalPropertyValueException {
return new Locale(arg0);
}
/**
* {@inheritDoc}
*/
@Override
public String serialize(Locale arg0) {
return arg0.getLanguage();
}
}
@@ -17,6 +17,8 @@ public class SubSpawnSettings extends SerializationConfig {
@Property
private boolean spawn;
@Property
private int spawnrate;
@Property
private List<String> exceptions;
public SubSpawnSettings() {
@@ -34,6 +36,7 @@ public class SubSpawnSettings extends SerializationConfig {
public void setDefaults() {
spawn = true;
exceptions = new ArrayList<String>();
spawnrate = -1;
}
/**
@@ -51,9 +54,23 @@ public class SubSpawnSettings extends SerializationConfig {
}
/**
* @return the exceptions
* @return The exceptions
*/
public List<String> getExceptions() {
return exceptions;
}
/**
* @param rate The new spawn rate
*/
public void setSpawnRate(int rate) {
this.spawnrate = rate;
}
/**
* @return The spawn rate
*/
public int getSpawnRate() {
return this.spawnrate;
}
}
@@ -7,7 +7,9 @@
package com.onarandombox.MultiverseCore.destination;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVDestination;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
@@ -21,6 +23,7 @@ public class BedDestination implements MVDestination {
private boolean isValid;
private Location knownBedLoc;
private MultiverseCore plugin;
/**
* {@inheritDoc}
@@ -46,7 +49,10 @@ public class BedDestination implements MVDestination {
@Override
public Location getLocation(Entity entity) {
if (entity instanceof Player) {
this.knownBedLoc = ((Player) entity).getBedSpawnLocation();
this.knownBedLoc = this.plugin.getBlockSafety().getSafeBedSpawn(((Player) entity).getBedSpawnLocation());
if (this.knownBedLoc == null) {
((Player) entity).sendMessage("Your bed was " + ChatColor.RED + "invalid or blocked" + ChatColor.RESET + ". Sorry.");
}
return this.knownBedLoc;
}
return null;
@@ -65,7 +71,7 @@ public class BedDestination implements MVDestination {
*/
@Override
public void setDestination(JavaPlugin plugin, String destination) {
// Not needed.
this.plugin = (MultiverseCore) plugin;
}
/**
@@ -0,0 +1,35 @@
package com.onarandombox.MultiverseCore.listeners;
import org.bukkit.entity.Player;
import org.bukkit.event.player.AsyncPlayerChatEvent;
/**
* A wrapper for the {@link AsyncPlayerChatEvent}.
*/
public class AsyncChatEvent implements ChatEvent {
private final AsyncPlayerChatEvent event;
public AsyncChatEvent(AsyncPlayerChatEvent event) {
this.event = event;
}
@Override
public boolean isCancelled() {
return event.isCancelled();
}
@Override
public String getFormat() {
return event.getFormat();
}
@Override
public void setFormat(String s) {
event.setFormat(s);
}
@Override
public Player getPlayer() {
return event.getPlayer();
}
}
@@ -0,0 +1,29 @@
package com.onarandombox.MultiverseCore.listeners;
import org.bukkit.entity.Player;
/**
* A wrapper for the two chat-events in Bukkit.
*/
public interface ChatEvent {
/**
* @return Whether this event is cancelled.
*/
boolean isCancelled();
/**
* @return The format.
*/
String getFormat();
/**
* Sets the format.
* @param s The new format.
*/
void setFormat(String s);
/**
* @return The player.
*/
Player getPlayer();
}
@@ -0,0 +1,34 @@
/******************************************************************************
* 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.listeners;
import java.util.logging.Level;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import com.onarandombox.MultiverseCore.MultiverseCore;
/**
* Multiverse's {@link org.bukkit.event.Listener} for players.
*/
public class MVAsyncPlayerChatListener extends MVChatListener {
public MVAsyncPlayerChatListener(MultiverseCore plugin, MVPlayerListener playerListener) {
super(plugin, playerListener);
plugin.log(Level.FINE, "Created AsyncPlayerChatEvent listener.");
}
/**
* This method is called when a player wants to chat.
* @param event The Event that was fired.
*/
@EventHandler
public void playerChat(AsyncPlayerChatEvent event) {
this.playerChat(new AsyncChatEvent(event));
}
}
@@ -0,0 +1,52 @@
package com.onarandombox.MultiverseCore.listeners;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import org.bukkit.event.Listener;
/**
* Multiverse's {@link org.bukkit.event.Listener} for players.
*/
public abstract class MVChatListener implements Listener {
private final MultiverseCore plugin;
private final MVWorldManager worldManager;
private final MVPlayerListener playerListener;
public MVChatListener(MultiverseCore plugin, MVPlayerListener playerListener) {
this.plugin = plugin;
this.worldManager = plugin.getMVWorldManager();
this.playerListener = playerListener;
}
/**
* This handles a {@link ChatEvent}.
* @param event The {@link ChatEvent}.
*/
public void playerChat(ChatEvent event) {
if (event.isCancelled()) {
return;
}
// Check whether the Server is set to prefix the chat with the World name.
// If not we do nothing, if so we need to check if the World has an Alias.
if (plugin.getMVConfig().getPrefixChat()) {
String world = playerListener.getPlayerWorld().get(event.getPlayer().getName());
if (world == null) {
world = event.getPlayer().getWorld().getName();
playerListener.getPlayerWorld().put(event.getPlayer().getName(), world);
}
String prefix = "";
// If we're not a MV world, don't do anything
if (!this.worldManager.isMVWorld(world)) {
return;
}
MultiverseWorld mvworld = this.worldManager.getMVWorld(world);
if (mvworld.isHidden()) {
return;
}
prefix = mvworld.getColoredWorldString();
String format = event.getFormat();
event.setFormat("[" + prefix + "]" + format);
}
}
}
@@ -11,13 +11,8 @@ import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import org.bukkit.World;
import org.bukkit.entity.Animals;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Ghast;
import org.bukkit.entity.Monster;
import org.bukkit.entity.Player;
import org.bukkit.entity.Slime;
import org.bukkit.entity.Squid;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
@@ -26,14 +21,12 @@ import org.bukkit.event.entity.EntityRegainHealthEvent;
import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import java.util.List;
import java.util.logging.Level;
/**
* Multiverse's Entity {@link Listener}.
*/
public class MVEntityListener implements Listener {
private MultiverseCore plugin;
private MVWorldManager worldManager;
@@ -87,7 +80,8 @@ public class MVEntityListener implements Listener {
public void creatureSpawn(CreatureSpawnEvent event) {
// Check to see if the Creature is spawned by a plugin, we don't want to prevent this behaviour.
// TODO: Allow the egg thing to be a config param. Doubt this will be per world; seems silly.
if (event.getSpawnReason() == SpawnReason.CUSTOM || event.getSpawnReason() == SpawnReason.SPAWNER_EGG) {
if (event.getSpawnReason() == SpawnReason.CUSTOM || event.getSpawnReason() == SpawnReason.SPAWNER_EGG
|| event.getSpawnReason() == SpawnReason.BREEDING) {
return;
}
@@ -100,8 +94,6 @@ public class MVEntityListener implements Listener {
return;
EntityType type = event.getEntityType();
MultiverseWorld mvworld = this.worldManager.getMVWorld(world.getName());
/**
* Handle people with non-standard animals: ie a patched craftbukkit.
*/
@@ -110,43 +102,8 @@ public class MVEntityListener implements Listener {
return;
}
/**
* Animal Handling
*/
if (!event.isCancelled() && (event.getEntity() instanceof Animals || event.getEntity() instanceof Squid)) {
event.setCancelled(shouldWeKillThisCreature(mvworld.getAnimalList(), mvworld.canAnimalsSpawn(), type.getName().toUpperCase()));
}
/**
* Monster Handling
*/
if (!event.isCancelled() && (event.getEntity() instanceof Monster || event.getEntity() instanceof Ghast || event.getEntity() instanceof Slime)) {
event.setCancelled(shouldWeKillThisCreature(mvworld.getMonsterList(), mvworld.canMonstersSpawn(), type.getName().toUpperCase()));
}
}
private static boolean shouldWeKillThisCreature(List<String> creatureList, boolean allowCreatureSpawning, String creature) {
if (creatureList.isEmpty() && allowCreatureSpawning) {
// 1. There are no exceptions and animals are allowed. Save it.
return false;
} else if (creatureList.isEmpty()) {
// 2. There are no exceptions and animals are NOT allowed. Kill it.
return true;
} else if (creatureList.contains(creature.toUpperCase()) && allowCreatureSpawning) {
// 3. There ARE exceptions and animals ARE allowed. Kill it.
return true;
} else if (!creatureList.contains(creature.toUpperCase()) && allowCreatureSpawning) {
// 4. There ARE exceptions and animals ARE NOT allowed. SAVE it.
return false;
} else if (creatureList.contains(creature.toUpperCase()) && !allowCreatureSpawning) {
// 5. No animals are allowed to be spawned, BUT this one can stay...
return false;
} else if (!creatureList.contains(creature.toUpperCase()) && !allowCreatureSpawning) {
// 6. Animals are NOT allowed to spawn, and this creature is not in the save list... KILL IT
return true;
} else {
// This code should NEVER execute. I just left the verbose conditions in right now.
throw new UnsupportedOperationException();
}
MultiverseWorld mvworld = this.worldManager.getMVWorld(world.getName());
event.setCancelled(this.plugin.getMVWorldManager().getTheWorldPurger().shouldWeKillThisCreature(mvworld, event.getEntity()));
}
}
@@ -0,0 +1,35 @@
/******************************************************************************
* 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.listeners;
import java.util.logging.Level;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerChatEvent;
import com.onarandombox.MultiverseCore.MultiverseCore;
/**
* Multiverse's {@link org.bukkit.event.Listener} for players.
*/
@SuppressWarnings("deprecation") // this exists only for downwards compatibility
public class MVPlayerChatListener extends MVChatListener {
public MVPlayerChatListener(MultiverseCore plugin, MVPlayerListener playerListener) {
super(plugin, playerListener);
plugin.log(Level.FINE, "Registered PlayerChatEvent listener.");
}
/**
* This method is called when a player wants to chat.
* @param event The Event that was fired.
*/
@EventHandler
public void playerChat(PlayerChatEvent event) {
this.playerChat(new NormalChatEvent(event));
}
}
@@ -7,10 +7,12 @@
package com.onarandombox.MultiverseCore.listeners;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.event.MVRespawnEvent;
import com.onarandombox.MultiverseCore.localization.MultiverseMessage;
import com.onarandombox.MultiverseCore.utils.PermissionTools;
import org.bukkit.Location;
import org.bukkit.Material;
@@ -21,55 +23,37 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerPortalEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
/**
* Multiverse's {@link Listener} for players.
*/
public class MVPlayerListener implements Listener {
private MultiverseCore plugin;
private MVWorldManager worldManager;
private PermissionTools pt;
private final MultiverseCore plugin;
private final MVWorldManager worldManager;
private final PermissionTools pt;
private final Map<String, String> playerWorld = new ConcurrentHashMap<String, String>();
public MVPlayerListener(MultiverseCore plugin) {
this.plugin = plugin;
worldManager = plugin.getMVWorldManager();
pt = new PermissionTools(plugin);
}
/**
* This method is called when a player wants to chat.
* @param event The Event that was fired.
* @return the playerWorld-map
*/
@EventHandler
public void playerChat(PlayerChatEvent event) {
if (event.isCancelled()) {
return;
}
// Check whether the Server is set to prefix the chat with the World name.
// If not we do nothing, if so we need to check if the World has an Alias.
if (plugin.getMVConfig().getPrefixChat()) {
String world = event.getPlayer().getWorld().getName();
String prefix = "";
// If we're not a MV world, don't do anything
if (!this.worldManager.isMVWorld(world)) {
return;
}
MultiverseWorld mvworld = this.worldManager.getMVWorld(world);
if (mvworld.isHidden()) {
return;
}
prefix = mvworld.getColoredWorldString();
String format = event.getFormat();
event.setFormat("[" + prefix + "]" + format);
}
public Map<String, String> getPlayerWorld() {
return playerWorld;
}
/**
@@ -137,12 +121,13 @@ public class MVPlayerListener implements Listener {
this.plugin.log(Level.FINER, "Player joined AGAIN!");
if (this.plugin.getMVConfig().getEnforceAccess() // check this only if we're enforcing access!
&& !this.plugin.getMVPerms().hasPermission(p, "multiverse.access." + p.getWorld().getName(), false)) {
p.sendMessage("[MV] - Sorry you can't be in this world anymore!");
this.plugin.getMessaging().sendMessage(p, MultiverseMessage.LISTENER_PLAYER_LOSTACCESSPERM);
this.sendPlayerToDefaultWorld(p);
}
}
// Handle the Players GameMode setting for the new world.
this.handleGameMode(event.getPlayer(), event.getPlayer().getWorld());
playerWorld.put(p.getName(), p.getWorld().getName());
}
/**
@@ -153,6 +138,7 @@ public class MVPlayerListener implements Listener {
public void playerChangedWorld(PlayerChangedWorldEvent event) {
// Permissions now determine whether or not to handle a gamemode.
this.handleGameMode(event.getPlayer(), event.getPlayer().getWorld());
playerWorld.put(event.getPlayer().getName(), event.getPlayer().getWorld().getName());
}
/**
@@ -208,6 +194,8 @@ public class MVPlayerListener implements Listener {
+ "' don't have the FUNDS required to enter it.");
return;
}
// Check if player is allowed to enter the world if we're enforcing permissions
if (plugin.getMVConfig().getEnforceAccess()) {
event.setCancelled(!pt.playerCanGoFromTo(fromWorld, toWorld, teleporter, teleportee));
if (event.isCancelled() && teleporter != null) {
@@ -215,13 +203,31 @@ public class MVPlayerListener implements Listener {
+ "' was DENIED ACCESS to '" + toWorld.getAlias()
+ "' because '" + teleporter.getName()
+ "' don't have: multiverse.access." + event.getTo().getWorld().getName());
} else {
this.stateSuccess(teleportee.getName(), toWorld.getAlias());
return;
}
} else {
this.plugin.log(Level.FINE, "Player '" + teleportee.getName()
+ "' was allowed to go to '" + toWorld.getAlias() + "' because enforceaccess is off.");
}
// Does a limit actually exist?
if (toWorld.getPlayerLimit() > -1) {
// Are there equal or more people on the world than the limit?
if (toWorld.getCBWorld().getPlayers().size() >= toWorld.getPlayerLimit()) {
// Ouch the world is full, lets see if the player can bypass that limitation
if (!pt.playerCanBypassPlayerLimit(toWorld, teleporter, teleportee)) {
this.plugin.log(Level.FINE, "Player '" + teleportee.getName()
+ "' was DENIED ACCESS to '" + toWorld.getAlias()
+ "' because the world is full and '" + teleporter.getName()
+ "' doesn't have: mv.bypass.playerlimit." + event.getTo().getWorld().getName());
event.setCancelled(true);
return;
}
}
}
// By this point anything cancelling the event has returned on the method, meaning the teleport is a success \o/
this.stateSuccess(teleportee.getName(), toWorld.getAlias());
}
private void stateSuccess(String playerName, String worldName) {
@@ -300,6 +306,7 @@ public class MVPlayerListener implements Listener {
// Remove the player 1 tick after the login. I'm sure there's GOT to be a better way to do this...
this.plugin.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin,
new Runnable() {
@Override
public void run() {
player.teleport(plugin.getMVWorldManager().getFirstSpawnWorld().getSpawnLocation());
}
@@ -329,19 +336,17 @@ public class MVPlayerListener implements Listener {
if (!this.pt.playerCanIgnoreGameModeRestriction(world, player)) {
this.plugin.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin,
new Runnable() {
@Override
public void run() {
// Check that the player is in the new world and they haven't been teleported elsewhere or the event cancelled.
if (player.getWorld() == world.getCBWorld()) {
MultiverseCore.staticLog(Level.FINE, "Handling gamemode for player: "
+ player.getName() + ", Changing to " + world.getGameMode().toString());
MultiverseCore.staticLog(Level.FINEST, "From World: " + player.getWorld());
MultiverseCore.staticLog(Level.FINEST, "To World: " + world);
Logging.fine("Handling gamemode for player: %s, Changing to %s", player.getName(), world.getGameMode().toString());
Logging.finest("From World: %s", player.getWorld());
Logging.finest("To World: %s", world);
player.setGameMode(world.getGameMode());
} else {
MultiverseCore.staticLog(Level.FINE, "The gamemode was NOT changed for player '"
+ player.getName() + "' because he is now in world '"
+ player.getWorld().getName() + "' instead of world '"
+ world.getName() +"'");
Logging.fine("The gamemode was NOT changed for player '%s' because he is now in world '%s' instead of world '%s'",
player.getName(), player.getWorld().getName(), world.getName());
}
}
}, 1L);
@@ -34,6 +34,10 @@ public class MVPluginListener implements Listener {
*/
@EventHandler(priority = EventPriority.MONITOR)
public void pluginEnable(PluginEnableEvent event) {
if (plugin.getVaultHandler().getEconomy() != null) {
// Don't hook 2 economy plugins.
return;
}
// Let AllPay handle all econ plugin loadings, only go for econ plugins we support
if (Arrays.asList(AllPay.getValidEconPlugins()).contains(event.getPlugin().getDescription().getName())) {
this.plugin.setBank(this.plugin.getBanker().loadEconPlugin());
@@ -0,0 +1,37 @@
package com.onarandombox.MultiverseCore.listeners;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerChatEvent;
/**
* A wrapper for the {@link PlayerChatEvent}.
* @deprecated This is deprecated like the {@link PlayerChatEvent}.
*/
@Deprecated
public class NormalChatEvent implements ChatEvent {
private final PlayerChatEvent event;
public NormalChatEvent(PlayerChatEvent event) {
this.event = event;
}
@Override
public boolean isCancelled() {
return event.isCancelled();
}
@Override
public String getFormat() {
return event.getFormat();
}
@Override
public void setFormat(String s) {
event.setFormat(s);
}
@Override
public Player getPlayer() {
return event.getPlayer();
}
}
@@ -0,0 +1,38 @@
package com.onarandombox.MultiverseCore.localization;
import java.util.Locale;
import java.util.Set;
/**
* Multiverse 2 LazyMessageProvider
* <p>
* This interface describes a Multiverse-MessageProvider that only loads locales when they're needed.
*/
public interface LazyLocaleMessageProvider extends MessageProvider {
/**
* Loads a localization for a specified {@link Locale}.
* <p>
* If that localization is already loaded, this method will reload it.
*
* @param locale The desired {@link Locale}.
* @throws LocalizationLoadingException When an error occurs while trying to load the specified localization.
*/
void loadLocale(Locale locale) throws LocalizationLoadingException;
/**
* Retrieves all loaded localizations.
*
* @return A {@link Set} of {@link Locale}s whose localizations are currently loaded.
*/
Set<Locale> getLoadedLocales();
/**
* Detects if a localization is loaded for the specified {@link Locale}.
*
* @param locale The {@link Locale}.
* @return Whether a localization is loaded for the specified {@link Locale}.
*/
boolean isLocaleLoaded(Locale locale);
}
@@ -0,0 +1,42 @@
package com.onarandombox.MultiverseCore.localization;
import java.io.IOException;
import java.util.Locale;
/**
* Thrown when an error occurs while a localization is loaded.
*/
public class LocalizationLoadingException extends IOException {
private final Locale locale;
public LocalizationLoadingException(Locale locale) {
this.locale = locale;
}
public LocalizationLoadingException(String message, Locale locale) {
super(message);
this.locale = locale;
}
public LocalizationLoadingException(Throwable cause, Locale locale) {
super(cause);
this.locale = locale;
}
public LocalizationLoadingException(String message, Throwable cause, Locale locale) {
super(message, cause);
this.locale = locale;
}
/**
* @return The locale we were trying to load.
*/
public Locale getLocale() {
return locale;
}
@Override
public String getMessage() {
return super.getMessage() + " (While trying to load localization for locale " + getLocale() + ")";
}
}
@@ -0,0 +1,46 @@
package com.onarandombox.MultiverseCore.localization;
import java.util.Locale;
/**
* Multiverse 2 MessageProvider
* <p>
* This interface describes a Multiverse-MessageProvider.
*/
public interface MessageProvider {
/**
* The default locale.
*/
Locale DEFAULT_LOCALE = Locale.ENGLISH;
/**
* Returns a message (as {@link String}) for the specified key (as {@link MultiverseMessage}).
*
* @param key The key
* @param args Args for String.format()
* @return The message
*/
String getMessage(MultiverseMessage key, Object... args);
/**
* Returns a message (as {@link String}) in a specified {@link Locale} for the specified key (as {@link MultiverseMessage}).
*
* @param key The Key
* @param locale The {@link Locale}
* @param args Args for String.format()
* @return The message
*/
String getMessage(MultiverseMessage key, Locale locale, Object... args);
/**
* @return the Locale this MessageProvider is currently using.
*/
Locale getLocale();
/**
* Sets the locale for this MessageProvider.
*
* @param locale The new {@link Locale}.
*/
void setLocale(Locale locale);
}
@@ -0,0 +1,20 @@
package com.onarandombox.MultiverseCore.localization;
/**
* Multiverse 2 MessageProviding
* <p>
* This interface is implemented by classes that use a {@link MessageProvider}.
*/
public interface MessageProviding {
/**
* @return The {@link MessageProvider} used by the Core.
*/
MessageProvider getMessageProvider();
/**
* Sets the {@link MessageProvider} used by the core.
*
* @param provider The new {@link MessageProvider}. Must not be null!
*/
void setMessageProvider(MessageProvider provider);
}
@@ -0,0 +1,90 @@
package com.onarandombox.MultiverseCore.localization;
/**
* An enum containing all messages/strings used by Multiverse.
*/
public enum MultiverseMessage {
// BEGIN CHECKSTYLE-SUPPRESSION: JavadocVariable
TEST_STRING("a test-string from the enum"),
//// Command handling error messages
CH_PLUGIN_DISABLED("This plugin is disabled!"),
CH_INTERNAL_ERROR("&cAn internal error occurred when attempting to perform this command."),
CH_ADMIN_DEBUG("&cDetails were printed to the server console and logs, please add that to your bug report."),
CH_USER_DEBUG("&cTry again and contact the server owner or an admin if this problem persists."),
//// Not MV world message
GENERIC_NOT_MV_WORLD("Multiverse doesn't know about &3%s&f yet.\nType &3/mv import ?&f for help!"),
//// Commands
// Anchor Command
CMD_ANCHOR_NOLISTPERM("&cYou don't have the permission to list anchors!"),
CMD_ANCHOR_LISTHEADER("&d====[ Multiverse Anchor List ]===="),
CMD_ANCHOR_NOMATCH("&cSorry... &fNo anchors matched your filter: &b%s"),
CMD_ANCHOR_NODEF("&cSorry... &fNo anchors were defined."),
CMD_ANCHOR_PAGEHEADER("&b Page %d of %d"),
CMD_ANCHOR_NODELPERM("&cYou don't have the permission to delete anchors!"),
CMD_ANCHOR_NOCREATEPERM("&cYou don't have the permission to create anchors!"),
CMD_ANCHOR_DELSUCCESS("Anchor '%s' was successfully &cdeleted!"),
CMD_ANCHOR_DELFAIL("Anchor '%s' was &cNOT&f deleted!"),
CMD_ANCHOR_CREATESUCCESS("Anchor '%s' was &asuccessfully&f created!"),
CMD_ANCHOR_CREATEFAIL("Anchor '%s' was &cNOT&f created!"),
CMD_ANCHOR_CONSOLECREATE("You must be a player to create Anchors!"),
// Check Command
CMD_CHECK_NOSUCHPLAYER("Could not find player &d%s&f\nAre they online?"),
CMD_CHECK_NOSUCHDEST("You asked if '%s' could go to '&d%s&f', but I couldn't find a Destination of that name? Did you type it correctly?"),
// Clone Command
CMD_CLONE_NOSUCHWORLD("Sorry, Multiverse doesn't know about world '%s', so we can't clone it!\nCheck the &a/mv list&f command to verify it is listed."),
CMD_CLONE_SUCCESS("&aWorld Cloned!"),
CMD_CLONE_FAIL("&cWorld could NOT be cloned!"),
// Config Command
CMD_CONFIG_SETFAIL("&cSetting '%s' to '%s' failed!"),
CMD_CONFIG_SUCCESS("&aSUCCESS!&f Values were updated successfully!"),
CMD_CONFIG_FAIL("&cFAIL!&f Check your console for details!"),
// Create Command
CMD_CREATE_WORLDEXISTS("&cMultiverse cannot create &n&6another&r&c world named '%s'."),
CMD_CREATE_FILEEXISTS("&cA Folder/World already exists with this name!\n&cIf you are confident it is a world you can import it with &a/mv import"),
CMD_CREATE_INVALIDENV("&cThat is not a valid environment."),
CMD_CREATE_INVALIDTYPE("&cThat is not a valid World Type."),
CMD_CREATE_INVALIDGEN("Invalid generator '%s'! &cAborting world creation."),
CMD_CREATE_START("Starting creation of world '%s'..."),
CMD_CREATE_COMPLETE("Complete!"),
CMD_CREATE_FAILED("FAILED."),
// Generator Command
CMD_GENERATOR_LISTHEADER("&b--- Loaded Generator Plugins ---"),
CMD_GENERATOR_NOGENSFOUND("&cNo Generator Plugins found."),
// List Command
CMD_LIST_NAME("World Listing"),
CMD_LIST_DESC("Displays a listing of all worlds that you can enter."),
CMD_LIST_TITLE("Multiverse World List"),
CMD_LIST_NO_MATCH("No worlds matched your filter:"),
//// Listeners
// PlayerListener
LISTENER_PLAYER_LOSTACCESSPERM("[MV] - Sorry you can't be in this world anymore!"),
//// Permissions
PERMS_NOACCESS_SELF("You don't have access to go here..."),
PERMS_NOACCESS_OTHER("You can't send %s here..."),
PERMS_NOACCESS_BLACKLIST_SELF("You don't have access to go to %s from %s"),
PERMS_NOACCESS_BLACKLIST_OTHER("You don't have access to send %s from %s to %s"),
//// World purger
PURGER_ENTITIESKILLED("%d entities purged from the world '%s'"),
// END CHECKSTYLE-SUPPRESSION: JavadocVariable
; // SUPPRESS CHECKSTYLE: Whitespace
private final String def;
MultiverseMessage(String def) {
this.def = def;
}
/**
* @return This {@link MultiverseMessage}'s default-message
*/
public String getDefault() {
return def;
}
}
@@ -0,0 +1,25 @@
package com.onarandombox.MultiverseCore.localization;
import java.util.Locale;
/**
* Thrown when the requested localization is not found.
*/
public class NoSuchLocalizationException extends LocalizationLoadingException {
public NoSuchLocalizationException(Locale locale) {
super(locale);
}
public NoSuchLocalizationException(String message, Locale locale) {
super(message, locale);
}
public NoSuchLocalizationException(String message, Throwable cause, Locale locale) {
super(message, cause, locale);
}
public NoSuchLocalizationException(Throwable cause, Locale locale) {
super(cause, locale);
}
}
@@ -0,0 +1,212 @@
package com.onarandombox.MultiverseCore.localization;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.bukkit.ChatColor;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import com.onarandombox.MultiverseCore.MultiverseCore;
/**
* The normal {@link MessageProvider}-implementation.
*/
public class SimpleMessageProvider implements LazyLocaleMessageProvider {
private static final String LOCALIZATION_FOLDER_NAME = "localization";
// Regex 1: replace all single & with the section char
private static final String FORMAT_PATTERN_1;
private static final String FORMAT_REPL_1;
static {
StringBuilder formatBuilder = new StringBuilder("([^&])&([");
for (ChatColor c : ChatColor.values())
formatBuilder.append(c.getChar());
FORMAT_PATTERN_1 = formatBuilder.append("])").toString();
FORMAT_REPL_1 = new StringBuilder().append("$1").append(ChatColor.COLOR_CHAR).append("$2").toString();
}
// Regex 2: replace all double & with single &
private static final String FORMAT_PATTERN_2 = "&&";
private static final String FORMAT_REPL_2 = "&";
private final Map<Locale, Map<MultiverseMessage, String>> messages;
private final MultiverseCore core;
private Locale locale = DEFAULT_LOCALE;
public SimpleMessageProvider(MultiverseCore core) {
this.core = core;
messages = new ConcurrentHashMap<Locale, Map<MultiverseMessage, String>>();
try {
loadLocale(locale);
} catch (NoSuchLocalizationException e) {
// let's take the defaults from the enum!
}
}
/**
* Loads a given {@link Locale} if and only if it wasn't already loaded.
* @param locale The locale
* @throws LocalizationLoadingException If the locale wasn't loaded successfully.
*/
public void maybeLoadLocale(Locale locale) throws LocalizationLoadingException {
if (!isLocaleLoaded(locale)) {
try {
loadLocale(locale);
} catch (NoSuchLocalizationException e) {
throw e;
}
}
if (!isLocaleLoaded(locale))
throw new LocalizationLoadingException("Couldn't load the localization: "
+ locale.toString(), locale);
}
/**
* Formats the specified string.
* <p>
* You can use {@code &} to get colors. To get an {@code &} in the output, you have to write {@code &&}.
*
* @param string The {@link String}.
* @param args Args for {@link String#format(String, Object...)}.
* @return The formatted string.
*/
public static String format(String string, Object... args) {
// Replaces & with the Section character
string = string.replaceAll(FORMAT_PATTERN_1, FORMAT_REPL_1).replaceAll(FORMAT_PATTERN_2, FORMAT_REPL_2);
return String.format(string, args);
}
/**
* {@inheritDoc}
*/
@Override
public void loadLocale(Locale l) throws NoSuchLocalizationException {
messages.remove(l);
InputStream resstream = null;
InputStream filestream = null;
try {
try {
filestream = new FileInputStream(new File(core.getDataFolder(), l.getLanguage() + ".yml"));
} catch (FileNotFoundException e) {
}
try {
resstream = core.getResource(new StringBuilder(LOCALIZATION_FOLDER_NAME)
.append("/").append(l.getLanguage()).append(".yml").toString());
} catch (Exception e) {
}
if ((resstream == null) && (filestream == null))
throw new NoSuchLocalizationException(l);
Map<MultiverseMessage, String> stringsMap = new HashMap<MultiverseMessage, String>();
FileConfiguration resconfig = (resstream == null) ? null : YamlConfiguration.loadConfiguration(resstream);
FileConfiguration fileconfig = (filestream == null) ? null : YamlConfiguration.loadConfiguration(filestream);
for (MultiverseMessage m : MultiverseMessage.values()) {
String value = m.getDefault();
if (resconfig != null)
value = resconfig.getString(m.toString(), value);
if (fileconfig != null)
value = fileconfig.getString(m.toString(), value);
stringsMap.put(m, value);
}
messages.put(l, Collections.unmodifiableMap(stringsMap));
} finally {
if (filestream != null)
try {
filestream.close();
} catch (IOException e) {
// silently discard
}
if (resstream != null)
try {
resstream.close();
} catch (IOException e) {
// silently discard
}
}
}
/**
* {@inheritDoc}
*/
@Override
public Set<Locale> getLoadedLocales() {
return messages.keySet();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isLocaleLoaded(Locale l) {
return messages.containsKey(l);
}
/**
* {@inheritDoc}
*/
@Override
public String getMessage(MultiverseMessage key, Object... args) {
if (!isLocaleLoaded(locale))
return format(key.getDefault(), args);
else
return format(messages.get(locale).get(key), args);
}
/**
* {@inheritDoc}
*/
@Override
public String getMessage(MultiverseMessage key, Locale locale, Object... args) {
try {
maybeLoadLocale(locale);
} catch (LocalizationLoadingException e) {
e.printStackTrace();
return getMessage(key);
}
return format(messages.get(locale).get(key), args);
}
/**
* {@inheritDoc}
*/
@Override
public Locale getLocale() {
return locale;
}
/**
* {@inheritDoc}
*/
@Override
public void setLocale(Locale locale) {
if (locale == null)
throw new IllegalArgumentException("Can't set locale to null!");
try {
maybeLoadLocale(locale);
} catch (LocalizationLoadingException e) {
if (!locale.equals(DEFAULT_LOCALE))
throw new IllegalArgumentException("Error while trying to load localization for the given Locale!", e);
}
this.locale = locale;
}
}
@@ -0,0 +1,4 @@
/**
* Contains localization.
*/
package com.onarandombox.MultiverseCore.localization;
@@ -7,6 +7,7 @@
package com.onarandombox.MultiverseCore.utils;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.MultiverseCore;
import org.bukkit.Location;
import org.bukkit.configuration.ConfigurationSection;
@@ -16,7 +17,6 @@ import org.bukkit.entity.Player;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
@@ -50,10 +50,10 @@ public class AnchorManager {
//world:x,y,z:pitch:yaw
Location anchorLocation = plugin.getLocationManipulation().stringToLocation(anchorsSection.getString(key, ""));
if (anchorLocation != null) {
MultiverseCore.staticLog(Level.INFO, "Loading anchor: '" + key + "'...");
Logging.config("Loading anchor: '%s'...", key);
this.anchors.put(key, anchorLocation);
} else {
MultiverseCore.staticLog(Level.WARNING, "The location for anchor '" + key + "' is INVALID.");
Logging.warning("The location for anchor '%s' is INVALID.", key);
}
}
@@ -7,15 +7,13 @@
package com.onarandombox.MultiverseCore.utils;
import com.onarandombox.MultiverseCore.MultiverseCore;
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;
import java.util.logging.Level;
/**
* Used to determine block/location-related facts.
*
@@ -75,28 +73,28 @@ public class BlockSafety {
if (this.isSolidBlock(world.getBlockAt(actual).getType())
|| this.isSolidBlock(upOne.getBlock().getType())) {
MultiverseCore.staticLog(Level.FINER, "Error Here (Actual)? ("
+ actual.getBlock().getType() + ")[" + this.isSolidBlock(actual.getBlock().getType()) + "]");
MultiverseCore.staticLog(Level.FINER, "Error Here (upOne)? ("
+ upOne.getBlock().getType() + ")[" + this.isSolidBlock(upOne.getBlock().getType()) + "]");
Logging.finer("Error Here (Actual)? (%s)[%s]", actual.getBlock().getType(),
this.isSolidBlock(actual.getBlock().getType()));
Logging.finer("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) {
MultiverseCore.staticLog(Level.FINER, "Error Here (downOne)? ("
+ downOne.getBlock().getType() + ")[" + this.isSolidBlock(downOne.getBlock().getType()) + "]");
Logging.finer("Error Here (downOne)? (%s)[%s]", downOne.getBlock().getType(),
this.isSolidBlock(downOne.getBlock().getType()));
return false;
}
if (downOne.getBlock().getType() == Material.FIRE) {
MultiverseCore.staticLog(Level.FINER, "There's fire below! ("
+ actual.getBlock().getType() + ")[" + this.isSolidBlock(actual.getBlock().getType()) + "]");
Logging.finer("There's fire below! (%s)[%s]", actual.getBlock().getType(),
this.isSolidBlock(actual.getBlock().getType()));
return false;
}
if (isBlockAboveAir(actual)) {
MultiverseCore.staticLog(Level.FINER, "Is block above air [" + isBlockAboveAir(actual) + "]");
MultiverseCore.staticLog(Level.FINER, "Has 2 blocks of water below [" + this.hasTwoBlocksofWaterBelow(actual) + "]");
Logging.finer("Is block above air [%s]", isBlockAboveAir(actual));
Logging.finer("Has 2 blocks of water below [%s]", this.hasTwoBlocksofWaterBelow(actual));
return this.hasTwoBlocksofWaterBelow(actual);
}
return true;
@@ -24,7 +24,9 @@ import java.util.logging.Logger;
/**
* The Multiverse debug-logger.
* @deprecated Deprecated in favor of new Logging lib. See {@link com.dumptruckman.minecraft.util.Logging}.
*/
@Deprecated
public class DebugLog extends Logger {
private FileHandler fh;
private Logger standardLog = null;
@@ -79,11 +81,11 @@ public class DebugLog extends Logger {
* @param msg the message.
*/
@Override
public void log(Level level, String msg) {
public void log(final Level level, final String msg) {
if (MultiverseCoreConfiguration.isSet() && MultiverseCoreConfiguration.getInstance().getGlobalDebug() > 0) {
// only redirect to standardLog if it's lower than INFO so we don't log that twice!
if ((level.intValue() < Level.INFO.intValue()) && (standardLog != null)) {
standardLog.log(level, prefix + msg);
standardLog.log(Level.INFO, prefix + msg);
}
super.log(level, prefix + msg);
@@ -8,6 +8,13 @@
package com.onarandombox.MultiverseCore.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Logger;
/**
* File-utilities.
@@ -37,4 +44,79 @@ public class FileUtils {
return false;
}
}
/**
* Used to delete the contents of a folder, without deleting the folder itself.
*
* @param file The folder whose contents to delete.
* @return true if the contents were successfully deleted
*/
public static boolean deleteFolderContents(File file) {
if (file.exists()) {
boolean ret = true;
// If the file exists, and it has more than one file in it.
if (file.isDirectory()) {
for (File f : file.listFiles()) {
ret = ret && deleteFolder(f);
}
}
return ret;
} else {
return false;
}
}
private static final int COPY_BLOCK_SIZE = 1024;
/**
* Helper method to copy the world-folder.
* @param source Source-File
* @param target Target-File
* @param log A logger that logs the operation
*
* @return if it had success
*/
public static boolean copyFolder(File source, File target, Logger log) {
InputStream in = null;
OutputStream out = null;
try {
if (source.isDirectory()) {
if (!target.exists())
target.mkdir();
String[] children = source.list();
// for (int i=0; i<children.length; i++) {
for (String child : children) {
copyFolder(new File(source, child), new File(target, child), log);
}
} else {
in = new FileInputStream(source);
out = new FileOutputStream(target);
byte[] buf = new byte[COPY_BLOCK_SIZE];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
return true;
} catch (FileNotFoundException e) {
log.warning("Exception while copying file: " + e.getMessage());
} catch (IOException e) {
log.warning("Exception while copying file: " + e.getMessage());
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ignore) { }
}
if (out != null) {
try {
out.close();
} catch (IOException ignore) { }
}
}
return false;
}
}
@@ -11,6 +11,8 @@ import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.onarandombox.MultiverseCore.api.MultiverseMessaging;
import com.onarandombox.MultiverseCore.localization.MessageProviding;
import com.onarandombox.MultiverseCore.localization.MultiverseMessage;
import java.util.Collection;
import java.util.HashMap;
@@ -20,10 +22,12 @@ import java.util.Map;
* The default-implementation of {@link MultiverseMessaging}.
*/
public class MVMessaging implements MultiverseMessaging {
private final MessageProviding msgProviding;
private Map<String, Long> sentList;
private int cooldown;
public MVMessaging() {
public MVMessaging(MessageProviding msgProviding) {
this.msgProviding = msgProviding;
this.sentList = new HashMap<String, Long>();
this.cooldown = 5000; // SUPPRESS CHECKSTYLE: MagicNumberCheck
}
@@ -50,7 +54,6 @@ public class MVMessaging implements MultiverseMessaging {
@Override
public boolean sendMessages(CommandSender sender, String[] messages, boolean ignoreCooldown) {
if (!(sender instanceof Player) || ignoreCooldown) {
sendMessages(sender, messages);
return true;
}
@@ -90,4 +93,20 @@ public class MVMessaging implements MultiverseMessaging {
public int getCooldown() {
return cooldown;
}
/**
* {@inheritDoc}
*/
@Override
public boolean sendMessage(CommandSender sender, MultiverseMessage message, Object... args) {
return this.sendMessage(sender, message, true, args); // TODO what is a good default value?
}
/**
* {@inheritDoc}
*/
@Override
public boolean sendMessage(CommandSender sender, MultiverseMessage message, boolean ignoreCooldown, Object...args) {
return this.sendMessage(sender, this.msgProviding.getMessageProvider().getMessage(message, args), ignoreCooldown);
}
}
@@ -76,6 +76,10 @@ public class MVPermissions implements PermissionsInterface {
* @return Whether the {@link CommandSender} can travel to the specified {@link Location}.
*/
public boolean canTravelFromLocation(CommandSender sender, Location location) {
// Now The Bed destination can return null now.
if (location == null) {
return false;
}
if (!(sender instanceof Player)) {
return true;
}
@@ -10,6 +10,8 @@ package com.onarandombox.MultiverseCore.utils;
import com.fernferret.allpay.GenericBank;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.localization.MultiverseMessage;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
@@ -143,17 +145,40 @@ public class PermissionTools {
if (this.plugin.getMVPerms().hasPermission(teleporter, toWorld.getExemptPermission().getName(), true)) {
return true;
}
GenericBank bank = plugin.getBank();
String errString = "You need " + bank.getFormattedAmount(teleporterPlayer, toWorld.getPrice(), toWorld.getCurrency())
+ " to send " + teleportee + " to " + toWorld.getColoredWorldString();
if (teleportee.equals(teleporter)) {
errString = "You need " + bank.getFormattedAmount(teleporterPlayer, toWorld.getPrice(), toWorld.getCurrency())
+ " to enter " + toWorld.getColoredWorldString();
final boolean usingVault;
final String formattedAmount;
if (toWorld.getCurrency() <= 0 && plugin.getVaultHandler().getEconomy() != null) {
usingVault = true;
formattedAmount = plugin.getVaultHandler().getEconomy().format(toWorld.getPrice());
} else {
usingVault = false;
formattedAmount = this.plugin.getBank().getFormattedAmount(teleporterPlayer, toWorld.getPrice(), toWorld.getCurrency());
}
if (!bank.hasEnough(teleporterPlayer, toWorld.getPrice(), toWorld.getCurrency(), errString)) {
return false;
} else if (pay) {
bank.give(teleporterPlayer, toWorld.getPrice(), toWorld.getCurrency());
String errString = "You need " + formattedAmount + " to send " + teleportee + " to " + toWorld.getColoredWorldString();
if (teleportee.equals(teleporter)) {
errString = "You need " + formattedAmount + " to enter " + toWorld.getColoredWorldString();
}
if (usingVault) {
if (!plugin.getVaultHandler().getEconomy().has(teleporterPlayer.getName(), toWorld.getPrice())) {
return false;
} else if (pay) {
if (toWorld.getPrice() < 0D) {
plugin.getVaultHandler().getEconomy().depositPlayer(teleporterPlayer.getName(), toWorld.getPrice() * -1D);
} else {
plugin.getVaultHandler().getEconomy().withdrawPlayer(teleporterPlayer.getName(), toWorld.getPrice());
}
}
} else {
GenericBank bank = plugin.getBank();
if (!bank.hasEnough(teleporterPlayer, toWorld.getPrice(), toWorld.getCurrency(), errString)) {
return false;
} else if (pay) {
if (toWorld.getPrice() < 0D) {
bank.give(teleporterPlayer, toWorld.getPrice() * -1D, toWorld.getCurrency());
} else {
bank.take(teleporterPlayer, toWorld.getPrice(), toWorld.getCurrency());
}
}
}
}
return true;
@@ -208,11 +233,10 @@ public class PermissionTools {
// Actual checks
if (toWorld != null) {
if (!this.plugin.getMVPerms().canEnterWorld(teleporterPlayer, toWorld)) {
if (teleportee.equals(teleporter)) {
teleporter.sendMessage("You don't have access to go here...");
} else {
teleporter.sendMessage("You can't send " + teleportee.getName() + " here...");
}
if (teleportee.equals(teleporter))
this.plugin.getMessaging().sendMessage(teleporter, MultiverseMessage.PERMS_NOACCESS_SELF);
else
this.plugin.getMessaging().sendMessage(teleporter, MultiverseMessage.PERMS_NOACCESS_OTHER, teleportee.getName());
return false;
}
@@ -223,17 +247,34 @@ public class PermissionTools {
}
if (fromWorld != null) {
if (fromWorld.getWorldBlacklist().contains(toWorld.getName())) {
if (teleportee.equals(teleporter)) {
teleporter.sendMessage("You don't have access to go to " + toWorld.getColoredWorldString() + " from " + fromWorld.getColoredWorldString());
} else {
teleporter.sendMessage("You don't have access to send " + teleportee.getName() + " from "
+ fromWorld.getColoredWorldString() + " to " + toWorld.getColoredWorldString());
}
if (teleportee.equals(teleporter))
this.plugin.getMessaging().sendMessage(teleporter, MultiverseMessage.PERMS_NOACCESS_BLACKLIST_SELF, toWorld.getColoredWorldString(), fromWorld.getColoredWorldString());
else
this.plugin.getMessaging().sendMessage(teleporter, MultiverseMessage.PERMS_NOACCESS_BLACKLIST_OTHER, teleportee.getName(), fromWorld.getColoredWorldString(), toWorld.getColoredWorldString());
return false;
}
}
return true;
}
public boolean playerCanBypassPlayerLimit(MultiverseWorld toWorld, CommandSender teleporter, Player teleportee) {
if (teleporter == null) {
teleporter = teleportee;
}
if (!(teleporter instanceof Player)) {
return true;
}
MVPermissions perms = plugin.getMVPerms();
if (perms.hasPermission(teleportee, "mv.bypass.playerlimit." + toWorld.getName(), false)) {
return true;
} else {
teleporter.sendMessage("The world " + toWorld.getColoredWorldString() + " is full");
return false;
}
}
/**
* Checks to see if a player should bypass game mode restrictions.
@@ -7,23 +7,38 @@
package com.onarandombox.MultiverseCore.utils;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.api.BlockSafety;
import com.onarandombox.MultiverseCore.api.Core;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Minecart;
import org.bukkit.entity.Vehicle;
import org.bukkit.material.Bed;
import java.util.logging.Level;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.Set;
/**
* The default-implementation of {@link BlockSafety}.
*/
public class SimpleBlockSafety implements BlockSafety {
private final Core plugin;
private static final Set<BlockFace> AROUND_BLOCK = EnumSet.noneOf(BlockFace.class);
static {
AROUND_BLOCK.add(BlockFace.NORTH);
AROUND_BLOCK.add(BlockFace.NORTH_EAST);
AROUND_BLOCK.add(BlockFace.EAST);
AROUND_BLOCK.add(BlockFace.SOUTH_EAST);
AROUND_BLOCK.add(BlockFace.SOUTH);
AROUND_BLOCK.add(BlockFace.SOUTH_WEST);
AROUND_BLOCK.add(BlockFace.WEST);
AROUND_BLOCK.add(BlockFace.NORTH_WEST);
}
public SimpleBlockSafety(Core plugin) {
this.plugin = plugin;
@@ -67,33 +82,88 @@ public class SimpleBlockSafety implements BlockSafety {
if (isSolidBlock(world.getBlockAt(actual).getType())
|| isSolidBlock(upOne.getBlock().getType())) {
MultiverseCore.staticLog(Level.FINER, "Error Here (Actual)? ("
+ actual.getBlock().getType() + ")[" + isSolidBlock(actual.getBlock().getType()) + "]");
MultiverseCore.staticLog(Level.FINER, "Error Here (upOne)? ("
+ upOne.getBlock().getType() + ")[" + isSolidBlock(upOne.getBlock().getType()) + "]");
Logging.finer("Error Here (Actual)? (%s)[%s]", actual.getBlock().getType(),
isSolidBlock(actual.getBlock().getType()));
Logging.finer("Error Here (upOne)? (%s)[%s]", upOne.getBlock().getType(),
isSolidBlock(upOne.getBlock().getType()));
return false;
}
if (downOne.getBlock().getType() == Material.LAVA || downOne.getBlock().getType() == Material.STATIONARY_LAVA) {
MultiverseCore.staticLog(Level.FINER, "Error Here (downOne)? ("
+ downOne.getBlock().getType() + ")[" + isSolidBlock(downOne.getBlock().getType()) + "]");
Logging.finer("Error Here (downOne)? (%s)[%s]", downOne.getBlock().getType(), isSolidBlock(downOne.getBlock().getType()));
return false;
}
if (downOne.getBlock().getType() == Material.FIRE) {
MultiverseCore.staticLog(Level.FINER, "There's fire below! ("
+ actual.getBlock().getType() + ")[" + isSolidBlock(actual.getBlock().getType()) + "]");
Logging.finer("There's fire below! (%s)[%s]", actual.getBlock().getType(), isSolidBlock(actual.getBlock().getType()));
return false;
}
if (isBlockAboveAir(actual)) {
MultiverseCore.staticLog(Level.FINER, "Is block above air [" + isBlockAboveAir(actual) + "]");
MultiverseCore.staticLog(Level.FINER, "Has 2 blocks of water below [" + this.hasTwoBlocksofWaterBelow(actual) + "]");
Logging.finer("Is block above air [%s]", isBlockAboveAir(actual));
Logging.finer("Has 2 blocks of water below [%s]", this.hasTwoBlocksofWaterBelow(actual));
return this.hasTwoBlocksofWaterBelow(actual);
}
return true;
}
/**
* {@inheritDoc}
*/
@Override
public Location getSafeBedSpawn(Location l) {
// The passed location, may be null (if the bed is invalid)
if (l == null) {
return null;
}
final Location trySpawn = this.getSafeSpawnAroundABlock(l);
if (trySpawn != null) {
return trySpawn;
}
Location otherBlock = this.findOtherBedPiece(l);
if (otherBlock == null) {
return null;
}
// Now we have 2 locations, check around each, if the type is bed, skip it.
return this.getSafeSpawnAroundABlock(otherBlock);
}
/**
* Find a safe spawn around a location. (N,S,E,W,NE,NW,SE,SW)
* @param l Location to check around
* @return A safe location, or none if it wasn't found.
*/
private Location getSafeSpawnAroundABlock(Location l) {
Iterator<BlockFace> checkblock = AROUND_BLOCK.iterator();
while (checkblock.hasNext()) {
final BlockFace face = checkblock.next();
if (this.playerCanSpawnHereSafely(l.getBlock().getRelative(face).getLocation())) {
// Don't forget to center the player.
return l.getBlock().getRelative(face).getLocation().add(.5, 0, .5);
}
}
return null;
}
/**
* Find the other bed block.
* @param checkLoc The location to check for the other piece at
* @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) {
return null;
}
// Construct a bed object at this location
final Bed b = new Bed(Material.BED_BLOCK, checkLoc.getBlock().getData());
if (b.isHeadOfBed()) {
return checkLoc.getBlock().getRelative(b.getFacing().getOppositeFace()).getLocation();
}
// We shouldn't ever be looking at the foot, but here's the code for it.
return checkLoc.getBlock().getRelative(b.getFacing()).getLocation();
}
/**
* {@inheritDoc}
*/
@@ -10,6 +10,7 @@ package com.onarandombox.MultiverseCore.utils;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.api.WorldPurger;
import com.onarandombox.MultiverseCore.localization.MultiverseMessage;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
@@ -17,6 +18,7 @@ import org.bukkit.entity.Animals;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Ghast;
import org.bukkit.entity.Golem;
import org.bukkit.entity.Monster;
import org.bukkit.entity.Slime;
import org.bukkit.entity.Squid;
@@ -62,6 +64,16 @@ public class SimpleWorldPurger implements WorldPurger {
purgeWorld(world, allMobs, !world.canAnimalsSpawn(), !world.canMonstersSpawn());
}
/**
* {@inheritDoc}
*/
@Override
public boolean shouldWeKillThisCreature(MultiverseWorld world, Entity e) {
ArrayList<String> allMobs = new ArrayList<String>(world.getAnimalList());
allMobs.addAll(world.getMonsterList());
return this.shouldWeKillThisCreature(e, allMobs, !world.canAnimalsSpawn(), !world.canMonstersSpawn());
}
/**
* {@inheritDoc}
*/
@@ -80,54 +92,66 @@ public class SimpleWorldPurger implements WorldPurger {
boolean specifiedAnimals = thingsToKill.contains("ANIMALS") || specifiedAll;
boolean specifiedMonsters = thingsToKill.contains("MONSTERS") || specifiedAll;
for (Entity e : world.getEntities()) {
boolean negate = false;
boolean specified = false;
if (e instanceof Squid || e instanceof Animals) {
// it's an animal
if (specifiedAnimals && !negateAnimals) {
this.plugin.log(Level.FINEST, "Removing an entity because I was told to remove all animals: " + e);
e.remove();
entitiesKilled++;
continue;
}
if (specifiedAnimals)
specified = true;
negate = negateAnimals;
} else if (e instanceof Monster || e instanceof Ghast || e instanceof Slime) {
// it's a monster
if (specifiedMonsters && !negateMonsters) {
this.plugin.log(Level.FINEST, "Removing an entity because I was told to remove all monsters: " + e);
e.remove();
entitiesKilled++;
continue;
}
if (specifiedMonsters)
specified = true;
negate = negateMonsters;
}
for (String s : thingsToKill) {
EntityType type = EntityType.fromName(s);
if (type != null && type.equals(e.getType())) {
specified = true;
if (!negate) {
this.plugin.log(Level.FINEST, "Removing an entity because it WAS specified and we are NOT negating: " + e);
e.remove();
entitiesKilled++;
continue;
}
break;
}
}
if (!specified && negate) {
this.plugin.log(Level.FINEST, "Removing an entity because it was NOT specified and we ARE negating: " + e);
if (killDecision(e, thingsToKill, negateAnimals, negateMonsters, specifiedAnimals, specifiedMonsters)) {
e.remove();
entitiesKilled++;
continue;
}
}
if (sender != null) {
sender.sendMessage(entitiesKilled + " entities purged from the world '" + world.getName() + "'");
if (sender != null)
this.plugin.getMessaging().sendMessage(sender, MultiverseMessage.PURGER_ENTITIESKILLED, entitiesKilled, world.getName());
}
private boolean killDecision(Entity e, List<String> thingsToKill, boolean negateAnimals,
boolean negateMonsters, boolean specifiedAnimals, boolean specifiedMonsters) {
boolean negate = false;
boolean specified = false;
if (e instanceof Golem || e instanceof Squid || e instanceof Animals) {
// it's an animal
if (specifiedAnimals && !negateAnimals) {
this.plugin.log(Level.FINEST, "Removing an entity because I was told to remove all animals: " + e);
return true;
}
if (specifiedAnimals)
specified = true;
negate = negateAnimals;
} else if (e instanceof Monster || e instanceof Ghast || e instanceof Slime) {
// it's a monster
if (specifiedMonsters && !negateMonsters) {
this.plugin.log(Level.FINEST, "Removing an entity because I was told to remove all monsters: " + e);
return true;
}
if (specifiedMonsters)
specified = true;
negate = negateMonsters;
}
for (String s : thingsToKill) {
EntityType type = EntityType.fromName(s);
if (type != null && type.equals(e.getType())) {
specified = true;
if (!negate) {
this.plugin.log(Level.FINEST, "Removing an entity because it WAS specified and we are NOT negating: " + e);
return true;
}
break;
}
}
if (!specified && negate) {
this.plugin.log(Level.FINEST, "Removing an entity because it was NOT specified and we ARE negating: " + e);
return true;
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
public boolean shouldWeKillThisCreature(Entity e, List<String> thingsToKill, boolean negateAnimals, boolean negateMonsters) {
boolean specifiedAll = thingsToKill.contains("ALL");
boolean specifiedAnimals = thingsToKill.contains("ANIMALS") || specifiedAll;
boolean specifiedMonsters = thingsToKill.contains("MONSTERS") || specifiedAll;
return this.killDecision(e, thingsToKill, negateAnimals, negateMonsters, specifiedAnimals, specifiedMonsters);
}
/**
@@ -7,6 +7,8 @@
package com.onarandombox.MultiverseCore.utils;
import com.dumptruckman.minecraft.util.Logging;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
@@ -87,7 +89,7 @@ public class UpdateChecker {
int compare = v1.compareTo(v2);
if (compare > 0) {
log.info("[" + this.name + "]" + " - Update Available (" + version + ")");
Logging.info("[%s] - Update Available (%s)", this.name, version);
}
rd.close();
@@ -0,0 +1,69 @@
package com.onarandombox.MultiverseCore.utils;
import com.dumptruckman.minecraft.util.Logging;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
/**
* A class we use to interface with Vault when it is present.
*/
public class VaultHandler implements Listener {
private Economy economy;
public VaultHandler(final Plugin plugin) {
Bukkit.getPluginManager().registerEvents(new VaultListener(), plugin);
setupVaultEconomy();
}
private boolean setupVaultEconomy() {
if (Bukkit.getPluginManager().getPlugin("Vault") != null) {
final RegisteredServiceProvider<Economy> economyProvider
= Bukkit.getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
if (economyProvider != null) {
Logging.fine("Vault economy enabled.");
economy = economyProvider.getProvider();
} else {
Logging.finer("Vault economy not detected.");
economy = null;
}
} else {
Logging.finer("Vault was not found.");
economy = null;
}
return (economy != null);
}
private class VaultListener implements Listener {
@EventHandler
private void vaultEnabled(PluginEnableEvent event) {
if (event.getPlugin() != null && event.getPlugin().getName().equals("Vault")) {
setupVaultEconomy();
}
}
@EventHandler
private void vaultDisabled(PluginDisableEvent event) {
if (event.getPlugin() != null && event.getPlugin().getName().equals("Vault")) {
Logging.fine("Vault economy disabled");
setupVaultEconomy();
}
}
}
/**
* Returns the Vault economy system if Vault is present and has an economy system enabled.
*
* @return The vault economy system or null if not configured.
*/
public Economy getEconomy() {
return economy;
}
}
@@ -7,6 +7,7 @@
package com.onarandombox.MultiverseCore.utils;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.MVWorld;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
@@ -14,6 +15,8 @@ import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.api.SafeTTeleporter;
import com.onarandombox.MultiverseCore.api.WorldPurger;
import com.onarandombox.MultiverseCore.event.MVWorldDeleteEvent;
import com.onarandombox.MultiverseCore.exceptions.PropertyDoesNotExistException;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.WorldCreator;
@@ -35,18 +38,21 @@ import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Stack;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Public facing API to add/remove Multiverse worlds.
*/
public class WorldManager implements MVWorldManager {
private MultiverseCore plugin;
private WorldPurger worldPurger;
private final MultiverseCore plugin;
private final WorldPurger worldPurger;
private final Map<String, MultiverseWorld> worlds;
private Map<String, MVWorld> worldsFromTheConfig;
private Map<String, MultiverseWorld> worlds;
private FileConfiguration configWorlds = null;
private Map<String, String> defaultGens;
private String firstSpawn;
@@ -54,7 +60,7 @@ public class WorldManager implements MVWorldManager {
public WorldManager(MultiverseCore core) {
this.plugin = core;
this.worldsFromTheConfig = new HashMap<String, MVWorld>();
this.worlds = new HashMap<String, MultiverseWorld>();
this.worlds = new ConcurrentHashMap<String, MultiverseWorld>();
this.worldPurger = new SimpleWorldPurger(plugin);
}
@@ -83,6 +89,85 @@ public class WorldManager implements MVWorldManager {
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean cloneWorld(String oldName, String newName, String generator) {
// Make sure we don't already know about the new world.
if (this.isMVWorld(newName)) {
return false;
}
// Make sure the old world is actually a world!
if (this.getUnloadedWorlds().contains(oldName) || !this.isMVWorld(oldName)) {
return false;
}
final File oldWorldFile = new File(this.plugin.getServer().getWorldContainer(), oldName);
final File newWorldFile = new File(this.plugin.getServer().getWorldContainer(), newName);
// Make sure the new world doesn't exist outside of multiverse.
if (newWorldFile.exists()) {
return false;
}
unloadWorld(oldName);
removePlayersFromWorld(oldName);
Logging.config("Copying data for world '%s'", oldName);
try {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
FileUtils.copyFolder(oldWorldFile, newWorldFile, Logger.getLogger("Minecraft"));
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
// do nothing
}
File uidFile = new File(newWorldFile, "uid.dat");
uidFile.delete();
} catch (NullPointerException e) {
e.printStackTrace();
return false;
}
Logging.fine("Kind of copied stuff");
WorldCreator worldCreator = new WorldCreator(newName);
Logging.fine("Started to copy settings");
worldCreator.copy(this.getMVWorld(oldName).getCBWorld());
Logging.fine("Copied lots of settings");
boolean useSpawnAdjust = this.getMVWorld(oldName).getAdjustSpawn();
Logging.fine("Copied more settings");
Environment environment = worldCreator.environment();
Logging.fine("Copied most settings");
if (newWorldFile.exists()) {
Logging.fine("Succeeded at copying stuff");
if (this.addWorld(newName, environment, null, null, null, generator, useSpawnAdjust)) {
// getMVWorld() doesn't actually return an MVWorld
Logging.fine("Succeeded at importing stuff");
MVWorld newWorld = (MVWorld) this.getMVWorld(newName);
MVWorld oldWorld = (MVWorld) this.getMVWorld(oldName);
newWorld.copyValues(oldWorld);
try {
// don't keep the alias the same -- that would be useless
newWorld.setPropertyValue("alias", newName);
} catch (PropertyDoesNotExistException e) {
// this should never happen
throw new RuntimeException(e);
}
return true;
}
}
return false;
}
/**
* {@inheritDoc}
*/
@@ -135,9 +220,9 @@ public class WorldManager implements MVWorldManager {
if (generator != null) {
builder.append(" & generator: ").append(generator);
}
this.plugin.log(Level.INFO, builder.toString());
Logging.info(builder.toString());
if (!doLoad(c)) {
if (!doLoad(c, true)) {
this.plugin.log(Level.SEVERE, "Failed to Create/Load the world '" + name + "'");
return false;
}
@@ -176,12 +261,12 @@ public class WorldManager implements MVWorldManager {
}
if (this.worldsFromTheConfig.containsKey(name)) {
this.worldsFromTheConfig.remove(name);
this.plugin.log(Level.INFO, "World '" + name + "' was removed from config.yml");
Logging.info("World '%s' was removed from config.yml", name);
this.saveWorldsConfig();
return true;
} else {
this.plugin.log(Level.INFO, "World '" + name + "' was already removed from config.yml");
Logging.info("World '%s' was already removed from config.yml", name);
}
return false;
}
@@ -225,20 +310,22 @@ public class WorldManager implements MVWorldManager {
if (this.worlds.containsKey(name)) {
if (this.unloadWorldFromBukkit(name, true)) {
this.worlds.remove(name);
this.plugin.log(Level.INFO, "World '" + name + "' was unloaded from memory.");
Logging.info("World '%s' was unloaded from memory.", name);
this.worldsFromTheConfig.get(name).tearDown();
return true;
} else {
this.plugin.log(Level.WARNING, "World '" + name + "' could not be unloaded. Is it a default world?");
Logging.warning("World '%s' could not be unloaded. Is it a default world?", name);
}
} else if (this.plugin.getServer().getWorld(name) != null) {
this.plugin.log(Level.WARNING, "Hmm Multiverse does not know about this world but it's loaded in memory.");
this.plugin.log(Level.WARNING, "To let Multiverse know about it, use:");
this.plugin.log(Level.WARNING, String.format("/mv import %s %s", name, this.plugin.getServer().getWorld(name).getEnvironment().toString()));
Logging.warning("Hmm Multiverse does not know about this world but it's loaded in memory.");
Logging.warning("To let Multiverse know about it, use:");
Logging.warning("/mv import %s %s", name, this.plugin.getServer().getWorld(name).getEnvironment().toString());
} else if (this.worldsFromTheConfig.containsKey(name)) {
return true; // it's already unloaded
} else {
this.plugin.log(Level.INFO, "Multiverse does not know about " + name + " and it's not loaded by Bukkit.");
Logging.info("Multiverse does not know about '%s' and it's not loaded by Bukkit.", name);
}
return false;
}
@@ -268,6 +355,10 @@ public class WorldManager implements MVWorldManager {
}
private boolean doLoad(String name) {
return doLoad(name, false);
}
private boolean doLoad(String name, boolean ignoreExists) {
if (!worldsFromTheConfig.containsKey(name))
throw new IllegalArgumentException("That world doesn't exist!");
@@ -278,15 +369,22 @@ public class WorldManager implements MVWorldManager {
if ((world.getGenerator() != null) && (!world.getGenerator().equals("null")))
creator.generator(world.getGenerator());
return doLoad(creator);
return doLoad(creator, ignoreExists);
}
private boolean doLoad(WorldCreator creator) {
private boolean doLoad(WorldCreator creator, boolean ignoreExists) {
String worldName = creator.name();
if (!worldsFromTheConfig.containsKey(worldName))
throw new IllegalArgumentException("That world doesn't exist!");
if (worlds.containsKey(worldName))
throw new IllegalArgumentException("That world is already loaded!");
if (!ignoreExists && !new File(this.plugin.getServer().getWorldContainer(), worldName).exists()) {
this.plugin.log(Level.WARNING, "WorldManager: Can't load this world because the folder was deleted/moved: " + worldName);
this.plugin.log(Level.WARNING, "Use '/mv remove' to remove it from the config!");
return false;
}
MVWorld mvworld = worldsFromTheConfig.get(worldName);
World cbworld;
try {
@@ -306,7 +404,7 @@ public class WorldManager implements MVWorldManager {
* {@inheritDoc}
*/
@Override
public boolean deleteWorld(String name, boolean removeFromConfig) {
public boolean deleteWorld(String name, boolean removeFromConfig, boolean deleteWorldFolder) {
World world = this.plugin.getServer().getWorld(name);
if (world == null) {
// We can only delete loaded worlds
@@ -334,25 +432,33 @@ public class WorldManager implements MVWorldManager {
try {
File worldFile = world.getWorldFolder();
plugin.log(Level.FINER, "deleteWorld(): worldFile: " + worldFile.getAbsolutePath());
boolean deletedWorld = FileUtils.deleteFolder(worldFile);
if (deletedWorld) {
this.plugin.log(Level.INFO, "World " + name + " was DELETED.");
if (deleteWorldFolder ? FileUtils.deleteFolder(worldFile) : FileUtils.deleteFolderContents(worldFile)) {
Logging.info("World '%s' was DELETED.", name);
return true;
} else {
this.plugin.log(Level.SEVERE, "World " + name + " was NOT deleted.");
this.plugin.log(Level.SEVERE, "Are you sure the folder " + name + " exists?");
this.plugin.log(Level.SEVERE, "Please check your file permissions on " + name);
Logging.severe("World '%s' was NOT deleted.", name);
Logging.severe("Are you sure the folder %s exists?", name);
Logging.severe("Please check your file permissions on '%s'", name);
return false;
}
return deletedWorld;
} catch (Throwable e) {
this.plugin.log(Level.SEVERE, "Hrm, something didn't go as planned. Here's an exception for ya.");
this.plugin.log(Level.SEVERE, "You can go politely explain your situation in #multiverse on esper.net");
this.plugin.log(Level.SEVERE, "But from here, it looks like your folder is oddly named.");
this.plugin.log(Level.SEVERE, "This world has been removed from Multiverse-Core so your best bet is to go delete the folder by hand. Sorry.");
this.plugin.log(Level.SEVERE, e.getMessage());
Logging.severe("Hrm, something didn't go as planned. Here's an exception for ya.");
Logging.severe("You can go politely explain your situation in #multiverse on esper.net");
Logging.severe("But from here, it looks like your folder is oddly named.");
Logging.severe("This world has been removed from Multiverse-Core so your best bet is to go delete the folder by hand. Sorry.");
Logging.severe(e.getMessage());
return false;
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean deleteWorld(String name, boolean removeFromConfig) {
return this.deleteWorld(name, removeFromConfig, true);
}
/**
* {@inheritDoc}
*/
@@ -403,8 +509,12 @@ public class WorldManager implements MVWorldManager {
*/
@Override
public MultiverseWorld getMVWorld(String name) {
if (this.worlds.containsKey(name)) {
return this.worlds.get(name);
if (name == null) {
return null;
}
MultiverseWorld world = this.worlds.get(name);
if (world != null) {
return world;
}
return this.getMVWorldByAlias(name);
}
@@ -439,7 +549,7 @@ public class WorldManager implements MVWorldManager {
* {@inheritDoc}
*/
@Override
public boolean isMVWorld(String name) {
public boolean isMVWorld(final String name) {
return (this.worlds.containsKey(name) || isMVWorldAlias(name));
}
@@ -457,7 +567,7 @@ public class WorldManager implements MVWorldManager {
* @param alias The alias of the world to check.
* @return True if the world exists, false if not.
*/
private boolean isMVWorldAlias(String alias) {
private boolean isMVWorldAlias(final String alias) {
for (MultiverseWorld w : this.worlds.values()) {
if (w.getAlias().equalsIgnoreCase(alias)) {
return true;
@@ -527,8 +637,9 @@ public class WorldManager implements MVWorldManager {
}
for (Map.Entry<String, MVWorld> entry : worldsFromTheConfig.entrySet()) {
if (worlds.containsKey(entry.getKey()))
if (worlds.containsKey(entry.getKey())) {
continue;
}
if (!entry.getValue().getAutoLoad())
continue;
@@ -537,7 +648,7 @@ public class WorldManager implements MVWorldManager {
}
// Simple Output to the Console to show how many Worlds were loaded.
this.plugin.log(Level.INFO, count + " - World(s) loaded.");
Logging.config("%s - World(s) loaded.", count);
this.saveWorldsConfig();
}
@@ -592,19 +703,24 @@ public class WorldManager implements MVWorldManager {
Object obj = this.configWorlds.get(path);
if ((obj != null) && (obj instanceof MVWorld)) {
String worldName = key.replaceAll(String.valueOf(SEPARATOR), ".");
MVWorld mvWorld = null;
if (this.worldsFromTheConfig.containsKey(worldName)) {
// Object-Recycling :D
MVWorld oldMVWorld = (MVWorld) this.worlds.get(worldName);
oldMVWorld.copyValues((MVWorld) obj);
newWorldsFromTheConfig.put(worldName, oldMVWorld);
} else {
// TODO Why is is checking worldsFromTheConfig and then getting from worlds? So confused... (DTM)
mvWorld = (MVWorld) this.worlds.get(worldName);
if (mvWorld != null) {
mvWorld.copyValues((MVWorld) obj);
}
}
if (mvWorld == null) {
// we have to use a new one
World cbworld = this.plugin.getServer().getWorld(worldName);
MVWorld mvworld = (MVWorld) obj;
if (cbworld != null)
mvworld.init(cbworld, this.plugin);
newWorldsFromTheConfig.put(worldName, mvworld);
mvWorld = (MVWorld) obj;
if (cbworld != null) {
mvWorld.init(cbworld, this.plugin);
}
}
newWorldsFromTheConfig.put(worldName, mvWorld);
} else if (this.configWorlds.isConfigurationSection(path)) {
ConfigurationSection section = this.configWorlds.getConfigurationSection(path);
Set<String> subkeys = section.getKeys(false);
@@ -655,6 +771,46 @@ public class WorldManager implements MVWorldManager {
return allNames;
}
/**
* {@inheritDoc}
*/
@Override
public boolean regenWorld(String name, boolean useNewSeed, boolean randomSeed, String seed) {
MultiverseWorld world = this.getMVWorld(name);
if (world == null)
return false;
List<Player> ps = world.getCBWorld().getPlayers();
if (useNewSeed) {
long theSeed;
if (randomSeed) {
theSeed = new Random().nextLong();
} else {
try {
theSeed = Long.parseLong(seed);
} catch (NumberFormatException e) {
theSeed = seed.hashCode();
}
}
world.setSeed(theSeed);
}
if (this.deleteWorld(name, false, false)) {
this.doLoad(name, true);
SafeTTeleporter teleporter = this.plugin.getSafeTTeleporter();
Location newSpawn = world.getSpawnLocation();
// Send all players that were in the old world, BACK to it!
for (Player p : ps) {
teleporter.safelyTeleport(null, p, newSpawn, true);
}
return true;
}
return false;
}
/**
* Gets the {@link FileConfiguration} that this {@link WorldManager} is using.
* @return The {@link FileConfiguration} that this {@link WorldManager} is using.
+20
View File
@@ -0,0 +1,20 @@
TEST_STRING: 'a test-string from the resource'
# Generic Strings
GENERIC_SORRY: 'Sorry...'
GENERIC_PAGE: 'Page'
GENERIC_OF: 'of'
GENERIC_UNLOADED: 'UNLOADED'
GENERIC_PLUGIN_DISABLED: 'This plugin is Disabled!'
# Errors
ERROR_LOAD: 'Your configs were not loaded. Very little will function in Multiverse.'
## Commands
# List Command
LIST_NAME: 'World Listing'
LIST_DESC: 'Displays a listing of all worlds that you can enter.'
LIST_TITLE: 'Multiverse World List'
LIST_NO_MATCH: 'No worlds matched your filter:'
+13
View File
@@ -202,3 +202,16 @@ commands:
description: Regenerates a world Multiverse already knows about.
usage: |
/<command> {WORLD}
mvscript:
description: Runs a script from the Multiverse scripts directory.
usage: |
/<command> {script} [target]
mvclone:
description: World clone command
usage: |
/<command> <world> <environment>
/<command> creative grieftastic -- Creates a world called 'grieftastic' exactly identical to the world 'creative'.
mvsilent:
description: Reduces startup messages
usage: |
/<command> [true|false]
@@ -0,0 +1,158 @@
package com.onarandombox.MultiverseCore.test;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Sheep;
import org.bukkit.entity.Zombie;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.plugin.PluginDescriptionFile;
import org.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 com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.listeners.MVEntityListener;
import com.onarandombox.MultiverseCore.test.utils.TestInstanceCreator;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ MultiverseCore.class, PluginDescriptionFile.class })
public class TestEntitySpawnRules {
TestInstanceCreator creator;
MultiverseCore core;
MVEntityListener listener;
MultiverseWorld mvWorld;
World cbworld;
Sheep sheep;
Zombie zombie;
CreatureSpawnEvent sheepEvent;
CreatureSpawnEvent zombieEvent;
@Before
public void setUp() throws Exception {
creator = new TestInstanceCreator();
assertTrue(creator.setUp());
core = creator.getCore();
listener = core.getEntityListener();
mvWorld = mock(MultiverseWorld.class);
cbworld = mock(World.class);
when(mvWorld.getCBWorld()).thenReturn(cbworld);
MVWorldManager worldman = mock(MVWorldManager.class);
when(worldman.isMVWorld(anyString())).thenReturn(true);
when(worldman.getMVWorld(anyString())).thenReturn(mvWorld);
Field worldmanfield = MVEntityListener.class.getDeclaredField("worldManager");
worldmanfield.setAccessible(true);
worldmanfield.set(listener, worldman);
core.getMVConfig().setGlobalDebug(3);
}
@After
public void tearDown() throws Exception {
creator.tearDown();
}
private static CreatureSpawnEvent mockSpawnEvent(LivingEntity e, SpawnReason reason) {
CreatureSpawnEvent event = mock(CreatureSpawnEvent.class);
when(event.getEntity()).thenReturn(e);
EntityType type = e.getType();
when(event.getEntityType()).thenReturn(type);
when(event.getSpawnReason()).thenReturn(reason);
return event;
}
private void spawnAll(SpawnReason reason) {
sheepEvent = mockSpawnEvent(sheep, reason);
zombieEvent = mockSpawnEvent(zombie, reason);
listener.creatureSpawn(sheepEvent);
listener.creatureSpawn(zombieEvent);
}
private void spawnAllNatural() {
spawnAll(SpawnReason.NATURAL);
}
private void adjustSettings(boolean animalSpawn, boolean monsterSpawn,
List<String> animalExceptions, List<String> monsterExceptions) {
when(this.mvWorld.canAnimalsSpawn()).thenReturn(animalSpawn);
when(this.mvWorld.canMonstersSpawn()).thenReturn(monsterSpawn);
when(this.mvWorld.getAnimalList()).thenReturn(animalExceptions);
when(this.mvWorld.getMonsterList()).thenReturn(monsterExceptions);
}
@Test
public void test() {
// test 1: no spawning at all allowed
adjustSettings(false, false, Collections.EMPTY_LIST, Collections.EMPTY_LIST);
createAnimals();
spawnAllNatural();
verify(sheepEvent).setCancelled(true);
verify(zombieEvent).setCancelled(true);
// test 2: only monsters
adjustSettings(false, true, Collections.EMPTY_LIST, Collections.EMPTY_LIST);
createAnimals();
spawnAllNatural();
verify(sheepEvent).setCancelled(true);
verify(zombieEvent).setCancelled(false);
// test 3: all spawning allowed
adjustSettings(true, true, Collections.EMPTY_LIST, Collections.EMPTY_LIST);
createAnimals();
spawnAllNatural();
verify(sheepEvent).setCancelled(false);
verify(zombieEvent).setCancelled(false);
// test 4: no spawning with zombie exception
adjustSettings(false, false, Collections.EMPTY_LIST, Arrays.asList("ZOMBIE"));
createAnimals();
spawnAllNatural();
verify(sheepEvent).setCancelled(true);
verify(zombieEvent).setCancelled(false);
// test 5: all spawning with sheep exception
adjustSettings(true, true, Arrays.asList("SHEEP"), Collections.EMPTY_LIST);
createAnimals();
spawnAllNatural();
verify(sheepEvent).setCancelled(true);
verify(zombieEvent).setCancelled(false);
// test 6: eggs
adjustSettings(false, false, Collections.EMPTY_LIST, Collections.EMPTY_LIST);
createAnimals();
spawnAll(SpawnReason.SPAWNER_EGG);
verify(sheepEvent, never()).setCancelled(anyBoolean());
verify(zombieEvent, never()).setCancelled(anyBoolean());
}
private void createAnimals() {
sheep = mock(Sheep.class);
when(sheep.getType()).thenReturn(EntityType.SHEEP);
when(sheep.getWorld()).thenReturn(this.cbworld);
zombie = mock(Zombie.class);
when(zombie.getType()).thenReturn(EntityType.ZOMBIE);
when(zombie.getWorld()).thenReturn(this.cbworld);
when(cbworld.getEntities()).thenReturn(Arrays.asList((Entity) sheep, (Entity) zombie));
}
}
@@ -0,0 +1,204 @@
/******************************************************************************
* 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.test;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.util.Locale;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.localization.LazyLocaleMessageProvider;
import com.onarandombox.MultiverseCore.localization.MultiverseMessage;
import com.onarandombox.MultiverseCore.localization.SimpleMessageProvider;
import com.onarandombox.MultiverseCore.test.utils.TestInstanceCreator;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ MultiverseCore.class, PluginDescriptionFile.class })
public class TestLocalization {
TestInstanceCreator creator;
Server mockServer;
CommandSender mockCommandSender;
@Before
public void setUp() throws Exception {
creator = new TestInstanceCreator();
assertTrue(creator.setUp());
mockServer = creator.getServer();
mockCommandSender = creator.getCommandSender();
}
@After
public void tearDown() throws Exception {
creator.tearDown();
}
@Test
public void testEnumDefaults() throws Exception {
// Pull a core instance from the server.
Plugin plugin = mockServer.getPluginManager().getPlugin("Multiverse-Core");
// Make sure Core is not null
assertNotNull(plugin);
// Make sure Core is enabled
assertTrue(plugin.isEnabled());
// Make sure Core is a MultiverseCore
assertTrue(plugin instanceof MultiverseCore);
MultiverseCore core = (MultiverseCore) plugin;
// This should be the same core as creator.getCore()
assertEquals(core, creator.getCore());
// Make sure there is neither the file nor the resource
assertNull(core.getResource("localization/en.yml"));
assertFalse(new File(TestInstanceCreator.pluginDirectory, "en.yml").exists());
// And now test it
String actual = core.getMessageProvider().getMessage(MultiverseMessage.TEST_STRING);
String expected = "a test-string from the enum";
assertEquals(expected, actual);
}
@Test
public void testResourceDefaults() throws Exception {
// Pull a core instance from the server.
Plugin plugin = mockServer.getPluginManager().getPlugin("Multiverse-Core");
// Make sure Core is not null
assertNotNull(plugin);
// Make sure Core is enabled
assertTrue(plugin.isEnabled());
// Make sure Core is a MultiverseCore
assertTrue(plugin instanceof MultiverseCore);
MultiverseCore core = (MultiverseCore) plugin;
// This should be the same core as creator.getCore()
assertEquals(core, creator.getCore());
// Make sure there is no file, only the resource
assertFalse(new File(TestInstanceCreator.pluginDirectory, "en.yml").exists());
assertTrue(new File("src/main/resources/localization/en.yml").exists());
doAnswer(new Answer<InputStream>() {
@Override
public InputStream answer(InvocationOnMock invocation) throws Throwable {
try {
return new FileInputStream("src/main/resources/" + (String) invocation.getArguments()[0]);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}).when(core).getResource(anyString());
assertNotNull(core.getResource("localization/en.yml"));
// this only works for a LazyLocaleMessageProvider
assertTrue(core.getMessageProvider() instanceof LazyLocaleMessageProvider);
LazyLocaleMessageProvider messageProvider = (LazyLocaleMessageProvider) core.getMessageProvider();
// We have to reload it
messageProvider.loadLocale(Locale.ENGLISH);
// And now test it
String actual = core.getMessageProvider().getMessage(MultiverseMessage.TEST_STRING);
String expected = "a test-string from the resource";
assertEquals(expected, actual);
}
@Test
public void testUserFile() throws Exception {
// Pull a core instance from the server.
Plugin plugin = mockServer.getPluginManager().getPlugin("Multiverse-Core");
// Make sure Core is not null
assertNotNull(plugin);
// Make sure Core is enabled
assertTrue(plugin.isEnabled());
// Make sure Core is a MultiverseCore
assertTrue(plugin instanceof MultiverseCore);
MultiverseCore core = (MultiverseCore) plugin;
// This should be the same core as creator.getCore()
assertEquals(core, creator.getCore());
// Create the file
File file = new File(TestInstanceCreator.pluginDirectory, "en.yml");
BufferedWriter bwriter = new BufferedWriter(new FileWriter(file));
String expected = "a test-string from the user-file";
bwriter.write("TEST_STRING: " + expected);
bwriter.close();
// Make sure there is the file and the resource
assertTrue(file.exists());
assertTrue(new File("src/main/resources/localization/en.yml").exists());
doAnswer(new Answer<InputStream>() {
@Override
public InputStream answer(InvocationOnMock invocation) throws Throwable {
try {
return new FileInputStream("src/main/resources/" + (String) invocation.getArguments()[0]);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}).when(core).getResource(anyString());
assertNotNull(core.getResource("localization/en.yml"));
// this only works for a LazyLocaleMessageProvider
assertTrue(core.getMessageProvider() instanceof LazyLocaleMessageProvider);
LazyLocaleMessageProvider messageProvider = (LazyLocaleMessageProvider) core.getMessageProvider();
// We have to reload it
messageProvider.loadLocale(Locale.ENGLISH);
// And now test it
String actual = core.getMessageProvider().getMessage(MultiverseMessage.TEST_STRING);
assertEquals(expected, actual);
// Clean up afterwards:
assertTrue(file.delete());
}
@Test
public void testFormat() {
String testString = "%sthisisasimpletest&moretesting&&thatsit.";
String result = SimpleMessageProvider.format(testString, "arg");
assertEquals("argthisisasimpletest\u00A7moretesting&thatsit.", result);
}
}
@@ -1,91 +0,0 @@
package com.onarandombox.MultiverseCore.test;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.test.utils.TestInstanceCreator;
import com.onarandombox.MultiverseCore.utils.WorldManager;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.Configuration;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.plugin.PluginDescriptionFile;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.internal.verification.VerificationModeFactory;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.lang.reflect.Field;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ MultiverseCore.class, PluginDescriptionFile.class })
public class TestWorldCreation {
private TestInstanceCreator creator;
private MultiverseCore core;
private CommandSender mockCommandSender;
@Before
public void setUp() throws Exception {
this.creator = new TestInstanceCreator();
assertTrue(this.creator.setUp());
this.core = this.creator.getCore();
this.mockCommandSender = this.creator.getCommandSender();
}
@After
public void tearDown() throws Exception {
creator.tearDown();
}
@Test
@Ignore
public void test() {
// Initialize a fake command
Command mockCommand = mock(Command.class);
when(mockCommand.getName()).thenReturn("mv");
// Try to create a world that exists
String[] normalArgs = new String[] { "create", "world", "normal" };
core.onCommand(mockCommandSender, mockCommand, "", normalArgs);
verify(mockCommandSender).sendMessage(ChatColor.RED + "A Folder/World already exists with this name!");
verify(mockCommandSender).sendMessage(ChatColor.RED + "If you are confident it is a world you can import with /mvimport");
// Try to create a world that is new
String[] newArgs = new String[] { "create", "world2", "normal" };
core.onCommand(mockCommandSender, mockCommand, "", newArgs);
verify(mockCommandSender).sendMessage("Starting creation of world 'world2'...");
String[] dottedWorld = new String[] { "create", "fish.world", "normal" };
core.onCommand(mockCommandSender, mockCommand, "", dottedWorld);
verify(mockCommandSender).sendMessage("Starting creation of world 'fish.world'...");
verify(mockCommandSender, VerificationModeFactory.times(2)).sendMessage("Complete!");
// Grab the Config
Field worldConfigField = null;
ConfigurationSection worldsSection = null;
try {
worldConfigField = WorldManager.class.getDeclaredField("configWorlds");
worldConfigField.setAccessible(true);
Configuration rootConfig = (Configuration) worldConfigField.get(this.core.getMVWorldManager());
worldsSection = rootConfig.getConfigurationSection("worlds");
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
// Verify that the world was added to the configs
// TODO: Expand this.
assertNotNull(worldsSection);
assertEquals(2, worldsSection.getKeys(false).size());
assertTrue(worldsSection.getKeys(false).contains("world2"));
assertTrue(worldsSection.getKeys(false).contains("fish.world"));
}
}
@@ -7,12 +7,14 @@
package com.onarandombox.MultiverseCore.test;
import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*;
import java.io.File;
import com.onarandombox.MultiverseCore.MVWorld;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.configuration.SpawnLocation;
import com.onarandombox.MultiverseCore.listeners.MVAsyncPlayerChatListener;
import com.onarandombox.MultiverseCore.test.utils.TestInstanceCreator;
import com.onarandombox.MultiverseCore.utils.WorldManager;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Difficulty;
@@ -27,7 +29,7 @@ import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityRegainHealthEvent;
import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.weather.ThunderChangeEvent;
@@ -44,17 +46,16 @@ import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.onarandombox.MultiverseCore.MVWorld;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.configuration.SpawnLocation;
import com.onarandombox.MultiverseCore.test.utils.TestInstanceCreator;
import com.onarandombox.MultiverseCore.utils.WorldManager;
import java.io.File;
import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ PluginManager.class, MultiverseCore.class, Permission.class, Bukkit.class,
WeatherChangeEvent.class, ThunderChangeEvent.class, PlayerChatEvent.class,
WeatherChangeEvent.class, ThunderChangeEvent.class, AsyncPlayerChatEvent.class,
PlayerJoinEvent.class, PlayerRespawnEvent.class, EntityRegainHealthEvent.class,
FoodLevelChangeEvent.class, WorldManager.class, PluginDescriptionFile.class })
public class TestWorldProperties {
@@ -68,7 +69,7 @@ public class TestWorldProperties {
private ThunderChangeEvent thunderChangeOffEvent;
private ThunderChangeEvent thunderChangeOnEvent;
private Player mockPlayer;
private PlayerChatEvent playerChatEvent;
private AsyncPlayerChatEvent playerChatEvent;
private Player mockNewPlayer;
private PlayerJoinEvent playerNewJoinEvent;
private PlayerJoinEvent playerJoinEvent;
@@ -167,10 +168,11 @@ public class TestWorldProperties {
// call player chat event
core.getMVConfig().setPrefixChat(true);
core.getPlayerListener().playerChat(playerChatEvent);
com.onarandombox.MultiverseCore.listeners.MVChatListener mvcl = core.getChatListener();
((MVAsyncPlayerChatListener) core.getChatListener()).playerChat(playerChatEvent);
verify(playerChatEvent).setFormat("[" + mvWorld.getColoredWorldString() + "]" + "format");
core.getMVConfig().setPrefixChat(false);
core.getPlayerListener().playerChat(playerChatEvent);
((MVAsyncPlayerChatListener) core.getChatListener()).playerChat(playerChatEvent);
verify(playerChatEvent, times(1)).setFormat(anyString()); // only ONE TIME (not the 2nd time!)
// call player join events
@@ -261,15 +263,15 @@ public class TestWorldProperties {
// call player chat event
core.getMVConfig().setPrefixChat(true);
core.getPlayerListener().playerChat(playerChatEvent);
((MVAsyncPlayerChatListener) core.getChatListener()).playerChat(playerChatEvent);
// never because it's hidden!
verify(playerChatEvent, never()).setFormat(
"[" + mvWorld.getColoredWorldString() + "]" + "format");
mvWorld.setHidden(false);
core.getPlayerListener().playerChat(playerChatEvent);
((MVAsyncPlayerChatListener) core.getChatListener()).playerChat(playerChatEvent);
verify(playerChatEvent).setFormat("[" + mvWorld.getColoredWorldString() + "]" + "format");
core.getMVConfig().setPrefixChat(false);
core.getPlayerListener().playerChat(playerChatEvent);
((MVAsyncPlayerChatListener) core.getChatListener()).playerChat(playerChatEvent);
verify(playerChatEvent, times(1)).setFormat(anyString()); // only ONE TIME (not the 2nd time!)
mvWorld.setHidden(true); // reset hidden-state
@@ -344,7 +346,8 @@ public class TestWorldProperties {
when(mockPlayer.getWorld()).thenReturn(mvWorld.getCBWorld());
when(mockPlayer.hasPlayedBefore()).thenReturn(true);
when(mockPlayer.hasPermission("multiverse.access.world")).thenReturn(true);
playerChatEvent = PowerMockito.mock(PlayerChatEvent.class);
when(mockPlayer.getName()).thenReturn("MultiverseMan");
playerChatEvent = PowerMockito.mock(AsyncPlayerChatEvent.class);
when(playerChatEvent.getPlayer()).thenReturn(mockPlayer);
when(playerChatEvent.getFormat()).thenReturn("format");
// player join
@@ -168,6 +168,35 @@ public class TestWorldStuff {
verify(mockServer).createWorld(Matchers.argThat(matcher));
}
@Test
public void testWorldCreateInvalidGenerator() {
// Pull a core instance from the server.
Plugin plugin = mockServer.getPluginManager().getPlugin("Multiverse-Core");
// Make sure Core is not null
assertNotNull(plugin);
// Make sure Core is enabled
assertTrue(plugin.isEnabled());
// Initialize a fake command
Command mockCommand = mock(Command.class);
when(mockCommand.getName()).thenReturn("mv");
// Ensure that there are no worlds imported. This is a fresh setup.
assertEquals(0, creator.getCore().getMVWorldManager().getMVWorlds().size());
// Create the world
String[] normalArgs = new String[]{ "create", "newworld", "normal", "-g", "BogusGen"};
plugin.onCommand(mockCommandSender, mockCommand, "", normalArgs);
// This command should halt, not creating any worlds
assertEquals(0, creator.getCore().getMVWorldManager().getMVWorlds().size());
// Verify
verify(mockCommandSender).sendMessage("Invalid generator 'BogusGen'! " + ChatColor.RED + "Aborting world creation.");
}
@Test
public void testNullWorld() {
// Pull a core instance from the server.
@@ -21,6 +21,7 @@ import java.util.logging.LogRecord;
public class MVTestLogFormatter extends Formatter {
private static final DateFormat df = new SimpleDateFormat("HH:mm:ss");
@Override
public String format(LogRecord record) {
StringBuilder ret = new StringBuilder();
@@ -39,6 +39,7 @@ public class MockWorldFactory {
private static void registerWorld(World world) {
createdWorlds.put(world.getName(), world);
new File(TestInstanceCreator.worldsDirectory, world.getName()).mkdir();
}
private static World basics(String world, World.Environment env, WorldType type) {
@@ -213,6 +214,8 @@ public class MockWorldFactory {
}
public static void clearWorlds() {
for (String name : createdWorlds.keySet())
new File(TestInstanceCreator.worldsDirectory, name).delete();
createdWorlds.clear();
}
}
@@ -7,6 +7,7 @@
package com.onarandombox.MultiverseCore.test.utils;
import buscript.Buscript;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.listeners.MVEntityListener;
@@ -35,6 +36,8 @@ import org.powermock.core.MockGateway;
import java.io.File;
import java.lang.reflect.Field;
import com.onarandombox.MultiverseCore.localization.MessageProvider;
import com.onarandombox.MultiverseCore.localization.SimpleMessageProvider;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
@@ -60,6 +63,12 @@ public class TestInstanceCreator {
MockGateway.MOCK_STANDARD_METHODS = false;
core = PowerMockito.spy(new MultiverseCore());
PowerMockito.doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
return null; // don't run metrics in tests
}
}).when(core, "setupMetrics");
// Let's let all MV files go to bin/test
doReturn(pluginDirectory).when(core).getDataFolder();
@@ -70,6 +79,7 @@ public class TestInstanceCreator {
when(pdf.getAuthors()).thenReturn(new ArrayList<String>());
doReturn(pdf).when(core).getDescription();
doReturn(true).when(core).isEnabled();
doReturn(null).when(core).getResource(anyString());
core.setServerFolder(serverDirectory);
// Add Core to the list of loaded plugins
@@ -80,6 +90,8 @@ public class TestInstanceCreator {
when(mockPluginManager.getPlugins()).thenReturn(plugins);
when(mockPluginManager.getPlugin("Multiverse-Core")).thenReturn(core);
when(mockPluginManager.getPermission(anyString())).thenReturn(null);
// Tell Buscript Vault is not available.
when(mockPluginManager.getPermission("Vault")).thenReturn(null);
// Make some fake folders to fool the fake MV into thinking these worlds exist
File worldNormalFile = new File(core.getServerFolder(), "world");
@@ -178,12 +190,23 @@ public class TestInstanceCreator {
serverfield.setAccessible(true);
serverfield.set(core, mockServer);
// Set buscript
Buscript buscript = PowerMockito.spy(new Buscript(core));
Field buscriptfield = MultiverseCore.class.getDeclaredField("buscript");
buscriptfield.setAccessible(true);
buscriptfield.set(core, buscript);
when(buscript.getPlugin()).thenReturn(core);
// Set worldManager
WorldManager wm = PowerMockito.spy(new WorldManager(core));
Field worldmanagerfield = MultiverseCore.class.getDeclaredField("worldManager");
worldmanagerfield.setAccessible(true);
worldmanagerfield.set(core, wm);
// Set messageProvider
MessageProvider messageProvider = PowerMockito.spy(new SimpleMessageProvider(core));
core.setMessageProvider(messageProvider);
// Set playerListener
MVPlayerListener pl = PowerMockito.spy(new MVPlayerListener(core));
Field playerlistenerfield = MultiverseCore.class.getDeclaredField("playerListener");
@@ -28,6 +28,7 @@ public class WorldCreatorMatcher extends ArgumentMatcher<WorldCreator> {
this.careAboutGenerators = doICare;
}
@Override
public boolean matches(Object creator) {
Util.log("Checking world creators.");
if (creator == null) {