Compare commits

...
81 Commits
Author SHA1 Message Date
zml2008 646b3e3064 [maven-release-plugin] prepare release 5.5 2012-02-11 16:22:17 -08:00
zml2008 d3475208ef Add correct git tag defaults to the release plugin config 2012-02-11 16:16:47 -08:00
zml2008 7246da472d Added changelog for 5.5 2012-02-11 16:11:42 -08:00
zml2008 e1f917894a Removed WorldEdit.jar from the classpath to stop conflicts with Bukkit's plugin loader 2012-02-11 12:20:56 -08:00
zml2008 c14d25f860 Now using Bukkit's tagged logging 2012-02-11 12:20:56 -08:00
TomyLobo 57ed91cd28 Updated to new event system 2012-02-11 12:20:56 -08:00
MonsieurApple 47c84beb43 Merge pull request #190 from skeight/master
Fix for bug #728 (Multiverse + Worldguard region with exit flag set)
2012-02-10 11:40:34 -08:00
skeight 1e3032bdce More whitespace fixes... 2012-02-10 11:30:43 -08:00
skeight ed69684843 Fixing up whitespace 2012-02-10 11:29:48 -08:00
skeight 2eea5c7bf7 Fix for bug #728. Multiverse + WorldGuard region exit flag. 2012-02-10 09:06:05 -08:00
zml2008 16da53ae4e Improved compatibility with versions of CommandBook without GodComponent and updated pom dep for 2.0 2012-02-06 20:41:39 -08:00
Nicholas Steicke f45464b0d9 Added MySQL region storage method.
Also added ProtectionDatabaseException, and made use of it across the project
Closes #180
2012-02-07 00:11:55 +01:00
Wesley Wolfe 2351ade6fe Fix inconsistent permission check
Closes #188
2012-02-07 00:11:54 +01:00
Turtle9598 c19ccf9278 Made explosions display their animations even when the event was blocked.
Closes #184
2012-02-07 00:11:54 +01:00
zml2008 5c92762ba9 Configuration should be fixed for real. Finally. 2012-02-07 00:11:54 +01:00
zml2008 e665f966e6 These checks may not work correctly, so reverted 2012-02-07 00:11:53 +01:00
zml2008 7dcca7e505 Fixed default entries not appearing in the global configuration 2012-02-07 00:11:53 +01:00
zml2008 e25049b1d6 Added fallback support for those who don't have a version of CommandBook with GodComponent 2012-02-07 00:11:50 +01:00
zml2008 da9bc4a138 Added LIGHTNING flag to DefaultFlag's flagsList
Fixes #1026
2012-02-06 23:06:12 +01:00
zml2008 1224d3b443 Corrected formatting of configuration files
Fixes #1025
2012-02-06 23:05:39 +01:00
zml2008 d33be37694 Removed /god, /heal, and /stack from WorldGuard to CommandBook. CommandBook is now checked to see whether a player is godded. 2012-02-06 23:05:30 +01:00
zml2008 551ff26a65 Removed remaining usages of org.bukkit.util.config.Configuration 2012-01-23 16:46:13 -08:00
zml2008 74082f9c68 Updated Bukkit repo 2012-01-20 23:45:39 -08:00
zml2008 b93331e184 Removed some unused configuration options 2012-01-11 18:04:14 -08:00
zml2008 d5d26168b3 Added permission worldguard.region.wand to the region wand
Closes #930
2012-01-10 21:15:00 -08:00
TomyLobo 9d848e222b Fixed ProtectedRegion.compareTo.
It properly implements the Comparable interface now.
In particular, it now fulfills the criterion "sgn(x.compareTo(y)) == -sgn(y.compareTo(x))".
2012-01-09 14:47:59 +01:00
TomyLobo 46a2510e85 Fixed FlatRegionManager.getApplicableRegions to return parent regions as well.
Thanks FearThe1337 for noticing.
2012-01-09 14:10:23 +01:00
TomyLobo 0789a453a2 Added a .gitattributes file
This will make your diffs show method names instead of class names on the hunk headers.
2012-01-03 14:47:46 +01:00
zml2008 b30f7fe9c7 Removed usage of Material. 2011-12-31 17:57:09 -08:00
zml2008 525bd199b2 Added exp-drops flag to disable experience drops per-region. 2011-12-31 13:50:43 -08:00
TomyLobo dffd8b59f5 Fixed some warnings. 2011-12-26 11:02:38 +01:00
TomyLobo df206724bd Updated dependency version for WorldGuard from 5.0 to 5.1-SNAPSHOT.
This fixes a warning about raw types.
2011-12-26 10:57:52 +01:00
zml2008 41f31250a9 Added support for fireballs shot by players being blocked by the PVP flag. 2011-12-24 22:49:37 -08:00
zml2008 b29007275f Added dynamic command registration and updated for WE 5.0 API 2011-12-24 22:49:37 -08:00
TomyLobo 35f268319e Split off ender dragon block damage from creeper block damage. 2011-12-18 23:16:12 +01:00
zml2008 6e8a185b63 [maven-release-plugin] prepare for next development iteration 2011-12-17 20:16:48 -08:00
zml2008 120fff1fc4 [maven-release-plugin] prepare release 5.4 2011-12-17 20:16:41 -08:00
zml2008 f879bd5e3a Updated changelog for release 2011-12-17 19:37:24 -08:00
Turtle9598 01f9fd561d Made WorldGuard check to see if both the attacker & defender are in a pvp area. 2011-12-14 20:15:42 -05:00
DerFlash 6802a7d747 Raised the priority of WorldGuard's respawn event listener. 2011-12-11 08:34:14 -08:00
DerFlash b918b29014 Fixed not being able to fill milk buckets in build deny regions
Though added a check for use flag here
2011-12-11 08:29:42 -08:00
zml2008 4895a3313b Forgot to update /slay, /wg report, and /stoplag to new commands system 2011-12-10 12:52:32 -08:00
zml2008 59673c9e66 Simplified autogod config check 2011-12-09 17:57:40 -08:00
Turtle9598 b126255be7 Fixed god mode being assigned to ops if auto enable is false and there is no permissions system
This fixes Bug #873
2011-12-10 01:15:14 +01:00
TomyLobo 606c9f3fd8 Revert "Readded the legacy console sender."
This reverts commit b1256eedcf.
Reason: this breaks if someone modifies CommandSender
The only advantage of having this class is to keep WorldGuard working with old 1.8 builds and pre-1.8 builds.
2011-12-08 14:38:05 +01:00
zml2008 aa306a8df7 Added additional worldguard.stack.damaged permissions to allow stacking of tools with a different damage value 2011-12-07 22:27:00 -08:00
zml2008 b1256eedcf Readded the legacy console sender. 2011-12-07 22:25:41 -08:00
zml2008 4454df341f Commented ProtectedPolygonalRegion.volume() out until someone can fix it. 2011-12-07 21:33:47 -08:00
TomyLobo 5bcac17f1c Fixed compilation with Bukkit >= CB1564.
Sorry, this breaks compatibility with builds < CB1193.
2011-12-08 02:34:26 +01:00
TomyLobo 875b9f326c Removed deprecation of RegionManager.getApplicableRegions.
The underlying functionality has since been implemented.
Also: woo, no more warnings
2011-12-05 06:03:52 +01:00
zml2008 a0d27c6f86 Added WorldEdit as a softdepend. This may fix some issues where WorldEdit's classes cannot be found. 2011-12-04 21:02:39 +01:00
zml2008 1d47d12189 Hopefully fixed WorldConfiguration.getKeys 2011-12-04 10:02:07 -08:00
zml2008 67f78ae8b5 Added per-group region claim maximums 2011-12-04 00:54:33 -08:00
zml2008 5948855da7 Added some more 1.0.0 blocks I forgot 2011-12-02 18:55:29 -08:00
zml2008 f6ec46cdf6 Now actually registering world events 2011-11-30 20:18:03 -08:00
zml2008 ebd2755eb2 Wrong this. 2011-11-30 19:24:53 -08:00
zml2008 78f5827d3d Always the imports... 2011-11-30 19:04:50 -08:00
zml2008 0829070c67 Added some OSX filesystem dust to gitignore and fixed pom.xml comment 2011-11-30 19:01:05 -08:00
zml2008 8b4332e842 Updated for new commands format 2011-11-30 18:59:02 -08:00
zml2008 f904c91443 Updated for Bukkit 1.0 and handling new 1.0 block types in USE flag 2011-11-30 18:59:02 -08:00
Eric Puidokas 944539453e Fixed feed-delay flag 2011-11-29 19:40:08 -08:00
TomyLobo 5856b002df Added .gitignore 2011-11-28 04:39:03 +01:00
TomyLobo 12f68bc227 Fixed a warning 2011-11-28 04:37:30 +01:00
TomyLobo de6e20d60a Improved error messages for group and state flags. 2011-10-30 04:07:37 +01:00
Eric Puidokas 35e6ef5cd8 Implemented edge intersection checking 2011-10-19 23:48:02 +02:00
Eric Puidokas 27251dda2e Refactored and fixed getIntersectingRegions 2011-10-19 23:47:13 +02:00
Eric Puidokas 4bb967ab4a Added Cuboid -> Polygonal intersect tests 2011-10-19 16:21:14 +02:00
Eric Puidokas 7c1f878610 Fixed ProtectedCuboidRegion->ProtectedCuboidRegion intersection checking 2011-10-19 16:21:14 +02:00
Wizjany e8c4c9b218 Fixed sticky pistons not being blocked by the flag in some cases 2011-10-18 17:49:05 -04:00
Eric Puidokas bc37d365ab Added unit tests for ProtectedCuboidRegion.getIntersectingRegions 2011-10-18 02:43:00 +02:00
TomyLobo d9ae1bbd9f Made LegacyConsoleSender compatible with patched Bukkit versions that add methods to CommandSender again.
Don't remove this again, wizjany.
2011-10-16 12:26:22 +02:00
zml2008 e492b30178 Added food level support to godmode and /heal 2011-10-15 23:51:28 -07:00
TomyLobo 920860c298 Fixed some warnings 2011-10-13 15:39:52 -04:00
Wizjany 5f8a6e3423 Workaround for tnt activating as soon as it was placed, regardless of cancellation. 2011-10-11 20:11:07 -04:00
Wizjany 3e7a5056d5 Fixed changelog not getting packaged with the release. 2011-10-09 11:51:43 -04:00
Wizjany 2ec6f04763 Implement non-economy 'buying' of regions via addowner 2011-10-09 11:51:43 -04:00
Wizjany ecef9c9792 Hopefully fix region managers not being created correctly. 2011-10-04 17:43:27 -04:00
Wizjany 810501a508 Added the missing timer to the food flags. 2011-10-04 16:26:54 -04:00
Wizjany 6285a66d76 Fixed allowed/blocked commands not being checked early enough. 2011-10-02 13:36:09 -04:00
zml2008 72e4922e8e Fixed config generation for Windows users 2011-10-02 01:30:10 -07:00
sk89q c1f1885633 [maven-release-plugin] prepare for next development iteration 2011-10-01 20:52:04 -07:00
63 changed files with 3232 additions and 2594 deletions

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
*.java diff=java
+6
View File
@@ -0,0 +1,6 @@
.classpath
.project
.settings
target
.DS_Store
+40
View File
@@ -1,3 +1,43 @@
5.5:
- Removed WorldEdit.jar from the classpath to stop conflicts with Bukkit's plugin loader
- Now using Bukkit's tagged logging
- Updated to new event system
- Flush player flag state cache on world change
- Improved compatibility with versions of CommandBook without GodComponent and updated pom dep for 2.0
- Added MySQL region storage method.
- Made explosions display their animations even when the event was blocked.
- Added fallback support for those who don't have a version of CommandBook with GodComponent
- Added LIGHTNING flag to DefaultFlag's flagsList Fixes #1026
- Removed /god, /heal, /locate, and /stack from WorldGuard to CommandBook. CommandBook is now checked to see whether a player is godded.
- Removed remaining usages of org.bukkit.util.config.Configuration
- Removed some unused configuration options
- Added permission worldguard.region.wand to the region wand
- Fixed ProtectedRegion.compareTo.
- Fixed FlatRegionManager.getApplicableRegions to return parent regions as well.
- Added exp-drops flag to disable experience drops per-region.
- Fixed some warnings.
- Updated dependency version for WorldGuard from 5.0 to 5.1-SNAPSHOT.
- Added support for fireballs shot by players being blocked by the PVP flag.
- Now using dynamic command registration
- Split off ender dragon block damage from creeper block damage.
Contributions thanks to: narthollis, DarkArc, Wolvereness, and skeight
5.4:
- Fixed configuration generation on Windows
- Fixed intersection calculation for regions
- Fixed timer and feeding delay for food flags
- Fixed region managers not being created properly (This caused errors related to CREATURE_SPAWN)
- Added support for Minecraft 1.0.1 blocks
- Added support for enchantments and tool damage (worldguard.stack.damaged is the node) with /stack
- Made being in the wg-invincible group respect the configuration's auto-invincible setting
- Added per-group region claim limit maximum
- Added worldguard.region.addowner.unclaimed.* permission for non-economy region 'buying'
- Checking allowed/blocked commands now occurs earlier to override more plugins
- Made PVP flag check whether either player is in a pvp deny region for blocking
Contributions thanks to: epuidokas, wizjany, Turtle9598, and DerFlash
5.3:
- Added new config options and flags to better handle explosions of all types
- Added config options and flags for snow, ice, mushroom spread, grass spread,
+205 -192
View File
@@ -1,192 +1,205 @@
<!--
Maven build file for WorldGuard
Copyright (c) 2011 sk89q <http://www.sk89q.com>
CommandBook is available under the GNU General Public License v3
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sk89q</groupId>
<artifactId>worldguard</artifactId>
<version>5.3</version>
<name>WorldGuard</name>
<description>WorldGuard protects your Minecraft servers</description>
<scm>
<connection>scm:git:git://github.com/sk89q/worldguard.git</connection>
<url>https://github.com/sk89q/worldguard</url>
<developerConnection>scm:git:git@github.com:sk89q/worldguard.git</developerConnection>
</scm>
<repositories>
<!-- Repository for other dependencies of SK's -->
<repository>
<id>sk89q-mvn2</id>
<url>http://mvn2.sk89q.com/repo</url>
</repository>
<!-- Repository for Bukkit -->
<repository>
<id>bukkit-repo</id>
<url>http://repo.bukkit.org/artifactory/repo</url>
</repository>
</repositories>
<dependencies>
<!-- Required component -->
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldedit</artifactId>
<version>4.7</version>
</dependency>
<!-- Bukkit -->
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<!-- Additional libraries -->
<dependency>
<groupId>com.nijikokun</groupId>
<artifactId>iconomy</artifactId>
<version>5.0</version>
</dependency>
<dependency>
<groupId>org.khelekore</groupId>
<artifactId>prtree</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>net.sf.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>${basedir}/src/main/java</sourceDirectory>
<!-- Resources -->
<resources>
<resource>
<targetPath>.</targetPath>
<filtering>true</filtering>
<directory>${basedir}/src/main/resources/</directory>
<includes>
<include>plugin.yml</include>
</includes>
</resource>
<resource>
<targetPath>defaults/</targetPath>
<filtering>true</filtering>
<directory>${basedir}/src/main/resources/</directory>
<includes>
<include>config.yml</include>
<include>config_world.yml</include>
<include>blacklist.txt</include>
</includes>
</resource>
</resources>
<plugins>
<!-- Compile plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
</plugin>
<!-- JAR creation plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<archive>
<addMavenDescriptor>true</addMavenDescriptor>
<manifest>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
</manifest>
<manifestEntries>
<Class-Path>WorldEdit.jar WorldGuard/WorldEdit.jar lib/WorldEdit.jar ../lib/WorldEdit.jar ../WorldEdit.jar</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
<!-- Shade -->
<!-- We want to bundle in some dependencies -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<!-- We want to bundle in the modified CSV library -->
<includes>
<include>net.sf.opencsv:opencsv</include>
</includes>
</artifactSet>
</configuration>
</execution>
</executions>
</plugin>
<!-- Assembly -->
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2.1</version>
<configuration>
<descriptor>${basedir}/src/main/assembly/default.xml</descriptor>
</configuration>
<executions>
<execution>
<id>release</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Release -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.1</version>
<configuration>
<preparationGoals>assembly:assembly</preparationGoals>
<goals>assembly:assembly</goals>
</configuration>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<!-- Javadocs -->
<!-- TODO: Get Doclava working -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.8</version>
<configuration>
</configuration>
</plugin>
</plugins>
</reporting>
</project>
<!--
Maven build file for WorldGuard
Copyright (c) 2011 sk89q <http://www.sk89q.com>
WorldGuard is available under the GNU General Public License v3
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sk89q</groupId>
<artifactId>worldguard</artifactId>
<version>5.5</version>
<name>WorldGuard</name>
<description>WorldGuard protects your Minecraft servers</description>
<scm>
<connection>scm:git:git://github.com/sk89q/worldguard.git</connection>
<url>https://github.com/sk89q/worldguard</url>
<developerConnection>scm:git:git@github.com:sk89q/worldguard.git</developerConnection>
</scm>
<repositories>
<!-- Repository for zml's stuff -->
<repository>
<id>zml-repo</id>
<url>http://files.zachsthings.com/repo</url>
</repository>
<!-- Repository for other dependencies of SK's -->
<repository>
<id>sk89q-mvn2</id>
<url>http://mvn2.sk89q.com/repo</url>
</repository>
<!-- Repository for Bukkit -->
<repository>
<id>bukkit-repo</id>
<url>http://repo.bukkit.org/content/groups/public</url>
</repository>
</repositories>
<dependencies>
<!-- Required component -->
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldedit</artifactId>
<version>5.2</version>
</dependency>
<!-- Bukkit -->
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.1-R3</version>
</dependency>
<!-- CommandBook -->
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>commandbook</artifactId>
<version>2.0</version>
</dependency>
<!-- Additional libraries -->
<dependency>
<groupId>com.nijikokun</groupId>
<artifactId>iconomy</artifactId>
<version>5.0</version>
</dependency>
<dependency>
<groupId>org.khelekore</groupId>
<artifactId>prtree</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>net.sf.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>${basedir}/src/main/java</sourceDirectory>
<!-- Resources -->
<resources>
<resource>
<targetPath>.</targetPath>
<filtering>true</filtering>
<directory>${basedir}/src/main/resources/</directory>
<includes>
<include>plugin.yml</include>
</includes>
</resource>
<resource>
<targetPath>defaults/</targetPath>
<filtering>true</filtering>
<directory>${basedir}/src/main/resources/</directory>
<includes>
<include>config.yml</include>
<include>config_world.yml</include>
<include>blacklist.txt</include>
</includes>
</resource>
</resources>
<plugins>
<!-- Compile plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
</plugin>
<!-- JAR creation plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<archive>
<addMavenDescriptor>true</addMavenDescriptor>
<manifest>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
</manifest>
<manifestEntries>
<Class-Path>WorldGuard/WorldEdit.jar lib/WorldEdit.jar ../lib/WorldEdit.jar ../WorldEdit.jar</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
<!-- Shade -->
<!-- We want to bundle in some dependencies -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<!-- We want to bundle in the modified CSV library -->
<includes>
<include>net.sf.opencsv:opencsv</include>
</includes>
</artifactSet>
</configuration>
</execution>
</executions>
</plugin>
<!-- Assembly -->
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2.1</version>
<configuration>
<descriptor>${basedir}/src/main/assembly/default.xml</descriptor>
</configuration>
<executions>
<execution>
<id>release</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Release -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.2.2</version>
<configuration>
<preparationGoals>assembly:assembly</preparationGoals>
<goals>assembly:assembly</goals>
<tagNameFormat>@{project.version}</tagNameFormat>
</configuration>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<!-- Javadocs -->
<!-- TODO: Get Doclava working -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.8</version>
<configuration>
</configuration>
</plugin>
</plugins>
</reporting>
</project>
+184
View File
@@ -0,0 +1,184 @@
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL';
-- -----------------------------------------------------
-- Table `user`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `user` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(64) NOT NULL UNIQUE,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `group`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `group` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(64) NOT NULL UNIQUE,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `world`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `world` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(128) NOT NULL UNIQUE,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `region`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `region` (
`id` VARCHAR(128) NOT NULL ,
`world_id` INT UNSIGNED NOT NULL ,
`type` ENUM('cuboid','poly2d','global') NOT NULL ,
`priority` SMALLINT NOT NULL DEFAULT 0 ,
`parent` VARCHAR(128) NULL ,
PRIMARY KEY (`id`, `world_id`) ,
INDEX `parent` (`parent` ASC) ,
INDEX `fk_region_world` (`world_id` ASC) ,
CONSTRAINT `parent`
FOREIGN KEY (`parent` )
REFERENCES `region` (`id` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_region_world1`
FOREIGN KEY (`world_id` )
REFERENCES `world` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `region_flag`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `region_flag` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`region_id` VARCHAR(128) NOT NULL ,
`flag` VARCHAR(64) NOT NULL ,
`value` VARCHAR(256) NOT NULL ,
INDEX `fk_flags_region` (`region_id` ASC) ,
PRIMARY KEY (`id`) ,
CONSTRAINT `fk_flags_region1`
FOREIGN KEY (`region_id` )
REFERENCES `region` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `region_cuboid`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `region_cuboid` (
`region_id` VARCHAR(128) NOT NULL ,
`min_z` BIGINT NOT NULL ,
`min_y` BIGINT NOT NULL ,
`min_x` BIGINT NOT NULL ,
`max_z` BIGINT NOT NULL ,
`max_y` BIGINT NOT NULL ,
`max_x` BIGINT NOT NULL ,
PRIMARY KEY (`region_id`) ,
INDEX `fk_region_cuboid_region` (`region_id` ASC) ,
CONSTRAINT `fk_region_cuboid_region`
FOREIGN KEY (`region_id` )
REFERENCES `region` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `region_poly2d`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `region_poly2d` (
`region_id` VARCHAR(128) NOT NULL ,
`max_y` INT NOT NULL ,
`min_y` INT NOT NULL ,
PRIMARY KEY (`region_id`) ,
INDEX `fk_region_poly2d_region` (`region_id` ASC) ,
CONSTRAINT `fk_region_poly2d_region`
FOREIGN KEY (`region_id` )
REFERENCES `region` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `region_players`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `region_players` (
`region_id` VARCHAR(128) NOT NULL ,
`user_id` INT UNSIGNED NOT NULL ,
`owner` TINYINT(1) NOT NULL ,
PRIMARY KEY (`region_id`, `user_id`) ,
INDEX `fk_region_players_region` (`region_id` ASC) ,
INDEX `fk_region_players_user` (`user_id` ASC) ,
CONSTRAINT `fk_region_players_region`
FOREIGN KEY (`region_id` )
REFERENCES `region` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `fk_region_players_user`
FOREIGN KEY (`user_id` )
REFERENCES `user` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `region_groups`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `region_groups` (
`region_id` VARCHAR(128) NOT NULL ,
`group_id` INT UNSIGNED NOT NULL ,
`owner` TINYINT(1) NOT NULL ,
PRIMARY KEY (`region_id`, `group_id`) ,
INDEX `fk_region_groups_region` (`region_id` ASC) ,
INDEX `fk_region_groups_group` (`group_id` ASC) ,
CONSTRAINT `fk_region_groups_region`
FOREIGN KEY (`region_id` )
REFERENCES `region` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `fk_region_groups_group`
FOREIGN KEY (`group_id` )
REFERENCES `group` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `region_poly2d_point`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `region_poly2d_point` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT ,
`region_id` VARCHAR(128) NOT NULL ,
`z` BIGINT NOT NULL ,
`x` BIGINT NOT NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_region_poly2d_point_region_poly2d` (`region_id` ASC) ,
CONSTRAINT `fk_region_poly2d_point_region_poly2d`
FOREIGN KEY (`region_id` )
REFERENCES `region_poly2d` (`region_id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
+1
View File
@@ -28,6 +28,7 @@
<includes>
<include>LICENSE.txt</include>
<include>NOTICE.txt</include>
<include>CHANGELOG.txt</include>
<include>blacklist_table.sql</include>
</includes>
</fileSet>
@@ -41,10 +41,6 @@ import com.sk89q.worldguard.blacklist.events.BlacklistEvent;
* @author sk89q
*/
public abstract class Blacklist {
/**
* Logger.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
/**
* List of entries by block ID.
@@ -67,8 +63,11 @@ public abstract class Blacklist {
private boolean useAsWhitelist;
public Blacklist(Boolean useAsWhitelist) {
private final Logger logger;
public Blacklist(Boolean useAsWhitelist, Logger logger) {
this.useAsWhitelist = useAsWhitelist;
this.logger = logger;
}
/**
@@ -178,7 +177,7 @@ public abstract class Blacklist {
} catch (NumberFormatException e) {
id = getItemID(item.trim());
if (id == 0) {
logger.log(Level.WARNING, "WorldGuard: Unknown block name: "
logger.log(Level.WARNING, "Unknown block name: "
+ item);
break;
}
@@ -37,17 +37,15 @@ import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
* @author sk89q
*/
public class ConsoleLoggerHandler implements BlacklistLoggerHandler {
/**
* Logger.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
private String worldName;
private final Logger logger;
public ConsoleLoggerHandler(String worldName)
{
this.worldName = worldName;
public ConsoleLoggerHandler(String worldName, Logger logger) {
this.worldName = worldName;
this.logger = logger;
}
/**
@@ -59,55 +57,55 @@ public class ConsoleLoggerHandler implements BlacklistLoggerHandler {
// Block break
if (event instanceof BlockBreakBlacklistEvent) {
BlockBreakBlacklistEvent evt = (BlockBreakBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " tried to break " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Block place
} else if (event instanceof BlockPlaceBlacklistEvent) {
BlockPlaceBlacklistEvent evt = (BlockPlaceBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " tried to place " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Block interact
} else if (event instanceof BlockInteractBlacklistEvent) {
BlockInteractBlacklistEvent evt = (BlockInteractBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " tried to interact with " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Destroy with
} else if (event instanceof DestroyWithBlacklistEvent) {
DestroyWithBlacklistEvent evt = (DestroyWithBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " tried to destroy with " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Acquire
} else if (event instanceof ItemAcquireBlacklistEvent) {
ItemAcquireBlacklistEvent evt = (ItemAcquireBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " tried to acquire " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Drop
} else if (event instanceof ItemDropBlacklistEvent) {
ItemDropBlacklistEvent evt = (ItemDropBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " tried to drop " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Use
} else if (event instanceof ItemUseBlacklistEvent) {
ItemUseBlacklistEvent evt = (ItemUseBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " tried to use " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Unknown
} else {
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " caught unknown event: " + event.getClass().getCanonicalName());
}
}
@@ -42,35 +42,33 @@ import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
* @author sk89q
*/
public class DatabaseLoggerHandler implements BlacklistLoggerHandler {
/**
* Logger.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
/**
* DSN.
*/
private String dsn;
private final String dsn;
/**
* Username.
*/
private String user;
private final String user;
/**
* Password.
*/
private String pass;
private final String pass;
/**
* Table.
*/
private String table;
private final String table;
/**
* World name.
*/
private String worldName;
private final String worldName;
/**
* Database connection.
*/
private Connection conn;
private final Logger logger;
/**
* Construct the object.
@@ -81,12 +79,13 @@ public class DatabaseLoggerHandler implements BlacklistLoggerHandler {
* @param table
* @param worldName
*/
public DatabaseLoggerHandler(String dsn, String user, String pass, String table, String worldName) {
public DatabaseLoggerHandler(String dsn, String user, String pass, String table, String worldName, Logger logger) {
this.dsn = dsn;
this.user = user;
this.pass = pass;
this.table = table;
this.worldName = worldName;
this.logger = logger;
}
/**
@@ -106,10 +105,8 @@ public class DatabaseLoggerHandler implements BlacklistLoggerHandler {
* Log an event to the database.
*
* @param event
* @param name
* @param x
* @param y
* @param z
* @param player
* @param pos
* @param item
* @param comment
*/
@@ -52,10 +52,6 @@ import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
* @author sk89q
*/
public class FileLoggerHandler implements BlacklistLoggerHandler {
/**
* Logger.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
/**
* Regex for patterns in the path.
*/
@@ -83,6 +79,8 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
*/
private TreeMap<String,FileLoggerWriter> writers =
new TreeMap<String,FileLoggerWriter>();
private final Logger logger;
/**
* Construct the object.
@@ -90,9 +88,10 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
* @param pathPattern
* @param worldName
*/
public FileLoggerHandler(String pathPattern, String worldName) {
public FileLoggerHandler(String pathPattern, String worldName, Logger logger) {
this.pathPattern = pathPattern;
this.worldName = worldName;
this.logger = logger;
}
/**
@@ -102,13 +101,14 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
* @param cacheSize
* @param worldName
*/
public FileLoggerHandler(String pathPattern, int cacheSize, String worldName) {
public FileLoggerHandler(String pathPattern, int cacheSize, String worldName, Logger logger) {
if (cacheSize < 1) {
throw new IllegalArgumentException("Cache size cannot be less than 1");
}
this.pathPattern = pathPattern;
this.cacheSize = cacheSize;
this.worldName = worldName;
this.logger = logger;
}
/**
@@ -25,7 +25,7 @@ public class BukkitBlacklist extends Blacklist {
private WorldGuardPlugin plugin;
public BukkitBlacklist(Boolean useAsWhitelist, WorldGuardPlugin plugin) {
super(useAsWhitelist);
super(useAsWhitelist, plugin.getLogger());
this.plugin = plugin;
}
@@ -21,9 +21,10 @@ package com.sk89q.worldguard.bukkit;
import java.util.List;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.blocks.ItemID;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.block.Block;
@@ -110,7 +111,7 @@ public class BukkitUtil {
public static void dropSign(Block block) {
block.setTypeId(0);
block.getWorld().dropItemNaturally(block.getLocation(),
new ItemStack(Material.SIGN, 1));
new ItemStack(ItemID.SIGN, 1));
}
/**
@@ -179,7 +180,7 @@ public class BukkitUtil {
loc.setX(x + 0.5);
loc.setY(y);
loc.setZ(z + 0.5);
if (y <= 2 && world.getBlockAt(x,0,z).getType() == Material.AIR) {
if (y <= 2 && world.getBlockAt(x,0,z).getTypeId() == BlockID.AIR) {
world.getBlockAt(x,0,z).setTypeId(20);
loc.setY(2);
}
@@ -19,14 +19,18 @@
package com.sk89q.worldguard.bukkit;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.sk89q.commandbook.CommandBook;
import com.sk89q.commandbook.GodComponent;
import com.sk89q.util.yaml.YAMLFormat;
import com.sk89q.util.yaml.YAMLProcessor;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.util.config.Configuration;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.Blacklist;
@@ -71,21 +75,37 @@ public class ConfigurationManager {
*/
private Map<String, WorldConfiguration> worlds;
/**
* The global configuration for use when loading worlds
*/
private YAMLProcessor config;
/**
* List of people with god mode.
*/
@Deprecated
private Set<String> hasGodMode = new HashSet<String>();
/**
* List of people who can breathe underwater.
*/
private Set<String> hasAmphibious = new HashSet<String>();
private boolean hasCommandBookGodMode = false;
public boolean suppressTickSyncWarnings;
public boolean useRegionsScheduler;
public boolean activityHaltToggle = false;
public boolean autoGodMode;
public boolean usePlayerMove;
/**
* Region Storage Configuration method, and config values
*/
public boolean useSqlDatabase = false;
public String sqlDsn;
public String sqlUsername;
public String sqlPassword;
/**
* Construct the object.
@@ -105,18 +125,30 @@ public class ConfigurationManager {
plugin.createDefaultConfiguration(
new File(plugin.getDataFolder(), "config.yml"), "config.yml");
Configuration config = plugin.getConfiguration();
config.load();
config = new YAMLProcessor(new File(plugin.getDataFolder(), "config.yml"), true, YAMLFormat.EXTENDED);
try {
config.load();
} catch (IOException e) {
plugin.getLogger().severe("Error reading configuration for global config: ");
e.printStackTrace();
}
suppressTickSyncWarnings = config.getBoolean(
"suppress-tick-sync-warnings", false);
useRegionsScheduler = config.getBoolean(
"regions.use-scheduler", true);
autoGodMode = config.getBoolean(
"auto-invincible-permission", false);
"auto-invincible", config.getBoolean("auto-invincible-permission", true));
usePlayerMove = config.getBoolean(
"use-player-move-event", true);
useSqlDatabase = config.getBoolean(
"regions.sql.use", false);
sqlDsn = config.getString("regions.sql.dsn", "jdbc:mysql://localhost/worldguard");
sqlUsername = config.getString("regions.sql.username", "worldguard");
sqlPassword = config.getString("regions.sql.password", "worldguard");
// Load configurations for each world
for (World world : plugin.getServer().getWorlds()) {
get(world);
@@ -127,7 +159,9 @@ public class ConfigurationManager {
} catch (Throwable t) {
}
config.save();
if (!config.save()) {
plugin.getLogger().severe("Error saving configuration!");
}
}
/**
@@ -148,7 +182,7 @@ public class ConfigurationManager {
WorldConfiguration config = worlds.get(worldName);
if (config == null) {
config = new WorldConfiguration(plugin, worldName);
config = new WorldConfiguration(plugin, worldName, this.config);
worlds.put(worldName, config);
}
@@ -180,6 +214,7 @@ public class ConfigurationManager {
*
* @param player
*/
@Deprecated
public void enableGodMode(Player player) {
hasGodMode.add(player.getName());
}
@@ -189,6 +224,7 @@ public class ConfigurationManager {
*
* @param player
*/
@Deprecated
public void disableGodMode(Player player) {
hasGodMode.remove(player.getName());
}
@@ -200,6 +236,12 @@ public class ConfigurationManager {
* @return
*/
public boolean hasGodMode(Player player) {
if (hasCommandBookGodMode) {
GodComponent god = CommandBook.inst().getComponentManager().getComponent(GodComponent.class);
if (god != null) {
return god.hasGodMode(player);
}
}
return hasGodMode.contains(player.getName());
}
@@ -230,4 +272,19 @@ public class ConfigurationManager {
public boolean hasAmphibiousMode(Player player) {
return hasAmphibious.contains(player.getName());
}
public void updateCommandBookGodMode() {
try {
if (plugin.getServer().getPluginManager().isPluginEnabled("CommandBook")) {
Class.forName("com.sk89q.commandbook.GodComponent");
hasCommandBookGodMode = true;
return;
}
} catch (ClassNotFoundException ignore) {}
hasCommandBookGodMode = false;
}
public boolean hasCommandBookGodMode() {
return hasCommandBookGodMode;
}
}
@@ -148,6 +148,8 @@ public class FlagStateManager implements Runnable {
private void processFeed(ApplicableRegionSet applicable, Player player,
PlayerFlagState state) {
long now = System.currentTimeMillis();
Integer feedAmount = applicable.getFlag(DefaultFlag.FEED_AMOUNT);
Integer feedDelay = applicable.getFlag(DefaultFlag.FEED_DELAY);
Integer minHunger = applicable.getFlag(DefaultFlag.MIN_FOOD);
@@ -164,10 +166,12 @@ public class FlagStateManager implements Runnable {
}
if (feedDelay <= 0) {
player.setFoodLevel(feedAmount > 0 ? maxHunger : minHunger); // this will insta-kill if the flag is unset
} else {
player.setFoodLevel(feedAmount > 0 ? maxHunger : minHunger);
state.lastFeed = now;
} else if (now - state.lastFeed > feedDelay * 1000) {
// clamp health between minimum and maximum
player.setFoodLevel(Math.min(maxHunger, Math.max(minHunger, player.getFoodLevel() + feedAmount)));
state.lastFeed = now;
}
}
@@ -209,6 +213,7 @@ public class FlagStateManager implements Runnable {
*/
public static class PlayerFlagState {
public long lastHeal;
public long lastFeed;
public String lastGreeting;
public String lastFarewell;
public Boolean lastExitAllowed = null;
@@ -1,87 +0,0 @@
package com.sk89q.worldguard.bukkit;
import java.util.Set;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionAttachment;
import org.bukkit.permissions.PermissionAttachmentInfo;
import org.bukkit.plugin.Plugin;
/**
* Console sender.
*
* @author sk89q
*/
class LegacyConsoleSender implements CommandSender {
private Server server;
public LegacyConsoleSender(Server server) {
this.server = server;
}
public void sendMessage(String message) {
WorldGuardPlugin.logger.info(message);
}
public Server getServer() {
return server;
}
public String getName() {
return "CONSOLE";
}
public boolean isPermissionSet(String name) {
return true;
}
public boolean isPermissionSet(Permission perm) {
return true;
}
public boolean hasPermission(String name) {
return true;
}
public boolean hasPermission(Permission perm) {
return true;
}
public PermissionAttachment addAttachment(Plugin plugin, String name,
boolean value) {
throw new UnsupportedOperationException("Fake legacy console command sender does not support this");
}
public PermissionAttachment addAttachment(Plugin plugin) {
throw new UnsupportedOperationException("Fake legacy console command sender does not support this");
}
public PermissionAttachment addAttachment(Plugin plugin, String name,
boolean value, int ticks) {
throw new UnsupportedOperationException("Fake legacy console command sender does not support this");
}
public PermissionAttachment addAttachment(Plugin plugin, int ticks) {
throw new UnsupportedOperationException("Fake legacy console command sender does not support this");
}
public void removeAttachment(PermissionAttachment attachment) {
throw new UnsupportedOperationException("Fake legacy console command sender does not support this");
}
public void recalculatePermissions() {
}
public Set<PermissionAttachmentInfo> getEffectivePermissions() {
throw new UnsupportedOperationException("Fake legacy console command sender does not support this");
}
public boolean isOp() {
return true;
}
public void setOp(boolean value) {
}
}
@@ -30,6 +30,7 @@ import java.util.logging.Logger;
import org.bukkit.World;
import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
import com.sk89q.worldguard.protection.databases.CSVDatabase;
import com.sk89q.worldguard.protection.managers.RegionManager;
@@ -39,10 +40,6 @@ import com.sk89q.worldguard.protection.managers.RegionManager;
* @author sk89q
*/
public class LegacyWorldGuardMigration {
/**
* Logger for messages.
*/
protected static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
/**
* Port over the blacklist.
@@ -58,7 +55,7 @@ public class LegacyWorldGuardMigration {
File newFile = new File(plugin.getDataFolder(), newPath);
if (!newFile.exists() && oldFile.exists()) {
logger.warning("WorldGuard: WorldGuard will now update your blacklist "
plugin.getLogger().warning("WorldGuard will now update your blacklist "
+ "from an older version of WorldGuard.");
// Need to make root directories
@@ -68,9 +65,9 @@ public class LegacyWorldGuardMigration {
oldFile.renameTo(new File(plugin.getDataFolder(),
"blacklist.txt.old"));
} else {
logger.warning("WorldGuard: blacklist.txt has been converted " +
plugin.getLogger().warning("blacklist.txt has been converted " +
"for the main world at " + newPath + "");
logger.warning("WorldGuard: Your other worlds currently have no " +
plugin.getLogger().warning("Your other worlds currently have no " +
"blacklist defined!");
}
@@ -87,15 +84,15 @@ public class LegacyWorldGuardMigration {
File oldDatabase = new File(plugin.getDataFolder(), "regions.txt");
if (!oldDatabase.exists()) return;
logger.info("WorldGuard: The regions database has changed in 4.x. "
plugin.getLogger().info("The regions database has changed in 5.x. "
+ "Your old regions database will be converted to the new format "
+ "and set as your primarily world's database.");
+ "and set as your primary world's database.");
World w = plugin.getServer().getWorlds().get(0);
RegionManager mgr = plugin.getGlobalRegionManager().get(w);
// First load up the old database using the CSV loader
CSVDatabase db = new CSVDatabase(oldDatabase);
CSVDatabase db = new CSVDatabase(oldDatabase, plugin.getLogger());
db.load();
// Then save the new database
@@ -104,10 +101,9 @@ public class LegacyWorldGuardMigration {
oldDatabase.renameTo(new File(plugin.getDataFolder(), "regions.txt.old"));
logger.info("WorldGuard: Regions database converted!");
} catch (FileNotFoundException e) {
} catch (IOException e) {
logger.warning("WorldGuard: Failed to load regions: "
plugin.getLogger().info("Regions database converted!");
} catch (ProtectionDatabaseException e) {
plugin.getLogger().warning("Failed to load regions: "
+ e.getMessage());
}
}
@@ -19,6 +19,8 @@
package com.sk89q.worldguard.bukkit;
import com.sk89q.commandbook.CommandBook;
import com.sk89q.commandbook.GodComponent;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
@@ -73,9 +75,9 @@ public class RegionQueryUtil {
StateFlag.State regionState = plugin.getGlobalRegionManager().get(world).
getApplicableRegions(vec).getFlag(DefaultFlag.INVINCIBILITY);
if (regionState == StateFlag.State.ALLOW) {
return true;
return Boolean.TRUE;
} else if (regionState == StateFlag.State.DENY) {
return false;
return Boolean.FALSE;
} else {
return null;
}
@@ -23,16 +23,19 @@ import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sk89q.util.yaml.YAMLFormat;
import com.sk89q.util.yaml.YAMLProcessor;
import org.bukkit.block.Block;
import org.bukkit.entity.CreatureType;
import org.bukkit.entity.Player;
import org.bukkit.util.config.Configuration;
import com.sk89q.worldguard.blacklist.Blacklist;
import com.sk89q.worldguard.blacklist.BlacklistLogger;
@@ -61,14 +64,11 @@ public class WorldConfiguration {
"# Remove the {} and add your own entries.\r\n" +
"#\r\n";
private static final Logger logger = Logger
.getLogger("Minecraft.WorldGuard");
private WorldGuardPlugin plugin;
private String worldName;
private Configuration parentConfig;
private Configuration config;
private YAMLProcessor parentConfig;
private YAMLProcessor config;
private File configFile;
private File blacklistFile;
@@ -78,9 +78,7 @@ public class WorldConfiguration {
/* Configuration data start */
public boolean opPermissions;
public boolean fireSpreadDisableToggle;
public boolean enforceOneSession;
public boolean itemDurability;
// public boolean classicWater;
public boolean simulateSponge;
public int spongeRadius;
public boolean disableExpDrops;
@@ -99,13 +97,9 @@ public class WorldConfiguration {
public boolean blockTNTBlockDamage;
public boolean blockCreeperExplosions;
public boolean blockCreeperBlockDamage;
public boolean blockEnderDragonBlockDamage;
public boolean blockFireballExplosions;
public boolean blockFireballBlockDamage;
// public int loginProtection;
// public int spawnProtection;
// public boolean kickOnDeath;
// public boolean exactRespawn;
// public boolean teleportToHome;
public boolean disableContactDamage;
public boolean disableFallDamage;
public boolean disableLavaDamage;
@@ -153,31 +147,34 @@ public class WorldConfiguration {
public boolean regionInvinciblityRemovesMobs;
public boolean disableDeathMessages;
public boolean disableObsidianGenerators;
private Map<String, Integer> maxRegionCounts;
/* Configuration data end */
/**
* Construct the object.
*
* @param plugin
* @param worldName
* @param plugin The WorldGuardPlugin instance
* @param worldName The world name that this WorldConfiguration is for.
* @param parentConfig The parent configuration to read defaults from
*/
public WorldConfiguration(WorldGuardPlugin plugin, String worldName) {
public WorldConfiguration(WorldGuardPlugin plugin, String worldName, YAMLProcessor parentConfig) {
File baseFolder = new File(plugin.getDataFolder(), "worlds/" + worldName);
configFile = new File(baseFolder, "config.yml");
blacklistFile = new File(baseFolder, "blacklist.txt");
this.plugin = plugin;
this.worldName = worldName;
this.parentConfig = plugin.getConfiguration();
this.parentConfig = parentConfig;
plugin.createDefaultConfiguration(configFile, "config_world.yml");
plugin.createDefaultConfiguration(blacklistFile, "blacklist.txt");
config = new Configuration(this.configFile);
config = new YAMLProcessor(this.configFile, true, YAMLFormat.EXTENDED);
loadConfiguration();
logger.info("WorldGuard: Loaded configuration for world '" + worldName + '"');
plugin.getLogger().info("Loaded configuration for world '" + worldName + '"');
}
private boolean getBoolean(String node, boolean def) {
@@ -210,6 +207,7 @@ public class WorldConfiguration {
}
}
@SuppressWarnings("unused")
private double getDouble(String node, double def) {
double val = parentConfig.getDouble(node, def);
@@ -248,21 +246,47 @@ public class WorldConfiguration {
return res;
}
private List<String> getKeys(String node) {
List<String> res = parentConfig.getKeys(node);
if (res == null || res.size() == 0) {
res = config.getKeys(node);
}
if (res == null) {
res = new ArrayList<String>();
}
return res;
}
private Object getProperty(String node) {
Object res = parentConfig.getProperty(node);
if (config.getProperty(node) != null) {
res = config.getProperty(node);
}
return res;
}
/**
* Load the configuration.
*/
private void loadConfiguration() {
config.load();
try {
config.load();
} catch (IOException e) {
plugin.getLogger().severe("Error reading configuration for world " + worldName + ": ");
e.printStackTrace();
}
opPermissions = getBoolean("op-permissions", true);
enforceOneSession = getBoolean("protection.enforce-single-session", true);
itemDurability = getBoolean("protection.item-durability", true);
removeInfiniteStacks = getBoolean("protection.remove-infinite-stacks", false);
disableExpDrops = getBoolean("protection.disable-xp-orb-drops", false);
disableObsidianGenerators = getBoolean("protection.disable-obsidian-generators", false);
// classicWater = getBoolean("simulation.classic-water", false);
simulateSponge = getBoolean("simulation.sponge.enable", true);
spongeRadius = Math.max(1, getInt("simulation.sponge.radius", 3)) - 1;
redstoneSponges = getBoolean("simulation.sponge.redstone", false);
@@ -286,17 +310,12 @@ public class WorldConfiguration {
blockCreeperExplosions = getBoolean("mobs.block-creeper-explosions", false);
blockCreeperBlockDamage = getBoolean("mobs.block-creeper-block-damage", false);
blockEnderDragonBlockDamage = getBoolean("mobs.block-enderdragon-block-damage", false);
blockFireballExplosions = getBoolean("mobs.block-fireball-explosions", false);
blockFireballBlockDamage = getBoolean("mobs.block-fireball-block-damage", false);
antiWolfDumbness = getBoolean("mobs.anti-wolf-dumbness", false);
disableEndermanGriefing = getBoolean("mobs.disable-enderman-griefing", false);
// loginProtection = getInt("spawn.login-protection", 3);
// spawnProtection = getInt("spawn.spawn-protection", 0);
// kickOnDeath = getBoolean("spawn.kick-on-death", false);
// exactRespawn = getBoolean("spawn.exact-respawn", false);
// teleportToHome = getBoolean("spawn.teleport-to-home-on-death", false);
disableFallDamage = getBoolean("player-damage.disable-fall-damage", false);
disableLavaDamage = getBoolean("player-damage.disable-lava-damage", false);
disableFireDamage = getBoolean("player-damage.disable-fire-damage", false);
@@ -339,7 +358,19 @@ public class WorldConfiguration {
regionWand = getInt("regions.wand", 287);
maxClaimVolume = getInt("regions.max-claim-volume", 30000);
claimOnlyInsideExistingRegions = getBoolean("regions.claim-only-inside-existing-regions", false);
maxRegionCountPerPlayer = getInt("regions.max-region-count-per-player", 7);
maxRegionCountPerPlayer = getInt("regions.max-region-count-per-player.default", 7);
maxRegionCounts = new HashMap<String, Integer>();
maxRegionCounts.put(null, maxRegionCountPerPlayer);
for (String key : getKeys("regions.max-region-count-per-player")) {
if (!key.equalsIgnoreCase("default")) {
Object val = getProperty("regions.max-region-count-per-player." + key);
if (val != null && val instanceof Number) {
maxRegionCounts.put(key, ((Number) val).intValue());
}
}
}
// useiConomy = getBoolean("iconomy.enable", false);
// buyOnClaim = getBoolean("iconomy.buy-on-claim", false);
@@ -350,7 +381,7 @@ public class WorldConfiguration {
CreatureType creature = CreatureType.fromName(creatureName);
if (creature == null) {
logger.warning("WorldGuard: Unknown mob type '" + creatureName + "'");
plugin.getLogger().warning("Unknown mob type '" + creatureName + "'");
} else {
blockCreatureSpawn.add(creature);
}
@@ -390,55 +421,52 @@ public class WorldConfiguration {
this.blacklist = null;
} else {
this.blacklist = blist;
logger.log(Level.INFO, "WorldGuard: Blacklist loaded.");
plugin.getLogger().log(Level.INFO, "Blacklist loaded.");
BlacklistLogger blacklistLogger = blist.getLogger();
if (logDatabase) {
blacklistLogger.addHandler(new DatabaseLoggerHandler(dsn, user, pass, table, worldName));
blacklistLogger.addHandler(new DatabaseLoggerHandler(dsn, user, pass, table, worldName, plugin.getLogger()));
}
if (logConsole) {
blacklistLogger.addHandler(new ConsoleLoggerHandler(worldName));
blacklistLogger.addHandler(new ConsoleLoggerHandler(worldName, plugin.getLogger()));
}
if (logFile) {
FileLoggerHandler handler =
new FileLoggerHandler(logFilePattern, logFileCacheSize, worldName);
new FileLoggerHandler(logFilePattern, logFileCacheSize, worldName, plugin.getLogger());
blacklistLogger.addHandler(handler);
}
}
} catch (FileNotFoundException e) {
logger.log(Level.WARNING, "WorldGuard blacklist does not exist.");
plugin.getLogger().log(Level.WARNING, "WorldGuard blacklist does not exist.");
} catch (IOException e) {
logger.log(Level.WARNING, "Could not load WorldGuard blacklist: "
plugin.getLogger().log(Level.WARNING, "Could not load WorldGuard blacklist: "
+ e.getMessage());
}
// Print an overview of settings
if (getBoolean("summary-on-start", true)) {
logger.log(Level.INFO, enforceOneSession
? "WorldGuard: (" + worldName + ") Single session is enforced."
: "WorldGuard: (" + worldName + ") Single session is NOT ENFORCED.");
logger.log(Level.INFO, blockTNTExplosions
? "WorldGuard: (" + worldName + ") TNT ignition is blocked."
: "WorldGuard: (" + worldName + ") TNT ignition is PERMITTED.");
logger.log(Level.INFO, blockLighter
? "WorldGuard: (" + worldName + ") Lighters are blocked."
: "WorldGuard: (" + worldName + ") Lighters are PERMITTED.");
logger.log(Level.INFO, preventLavaFire
? "WorldGuard: (" + worldName + ") Lava fire is blocked."
: "WorldGuard: (" + worldName + ") Lava fire is PERMITTED.");
plugin.getLogger().log(Level.INFO, blockTNTExplosions
? "(" + worldName + ") TNT ignition is blocked."
: "(" + worldName + ") TNT ignition is PERMITTED.");
plugin.getLogger().log(Level.INFO, blockLighter
? "(" + worldName + ") Lighters are blocked."
: "(" + worldName + ") Lighters are PERMITTED.");
plugin.getLogger().log(Level.INFO, preventLavaFire
? "(" + worldName + ") Lava fire is blocked."
: "(" + worldName + ") Lava fire is PERMITTED.");
if (disableFireSpread) {
logger.log(Level.INFO, "WorldGuard: (" + worldName + ") All fire spread is disabled.");
plugin.getLogger().log(Level.INFO, "(" + worldName + ") All fire spread is disabled.");
} else {
if (disableFireSpreadBlocks.size() > 0) {
logger.log(Level.INFO, "WorldGuard: (" + worldName
plugin.getLogger().log(Level.INFO, "(" + worldName
+ ") Fire spread is limited to "
+ disableFireSpreadBlocks.size() + " block types.");
} else {
logger.log(Level.INFO, "WorldGuard: (" + worldName
plugin.getLogger().log(Level.INFO, "(" + worldName
+ ") Fire spread is UNRESTRICTED.");
}
}
@@ -503,4 +531,18 @@ public class WorldConfiguration {
public ChestProtection getChestProtection() {
return chestProtection;
}
public int getMaxRegionCount(Player player) {
int max = -1;
for (String group : plugin.getGroups(player)) {
if (maxRegionCounts.containsKey(group)) {
int groupMax = maxRegionCounts.get(group);
if (max < groupMax) max = groupMax;
}
}
if (max <= -1) {
max = maxRegionCountPerPlayer;
}
return max;
}
}
@@ -24,12 +24,12 @@ import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockDamageEvent;
@@ -37,7 +37,6 @@ import org.bukkit.event.block.BlockFadeEvent;
import org.bukkit.event.block.BlockFormEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockListener;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.block.BlockPistonExtendEvent;
import org.bukkit.event.block.BlockPistonRetractEvent;
@@ -48,11 +47,10 @@ import org.bukkit.event.block.LeavesDecayEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.block.BlockIgniteEvent.IgniteCause;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.PluginManager;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.BlockType;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.events.BlockBreakBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockPlaceBlacklistEvent;
@@ -66,11 +64,7 @@ import com.sk89q.worldguard.protection.managers.RegionManager;
*
* @author sk89q
*/
public class WorldGuardBlockListener extends BlockListener {
/**
* Logger for messages.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
public class WorldGuardBlockListener implements Listener {
private WorldGuardPlugin plugin;
@@ -87,39 +81,9 @@ public class WorldGuardBlockListener extends BlockListener {
* Register events.
*/
public void registerEvents() {
registerEvent("BLOCK_DAMAGE", Priority.High);
registerEvent("BLOCK_BREAK", Priority.High);
registerEvent("BLOCK_FROMTO", Priority.Normal);
registerEvent("BLOCK_IGNITE", Priority.High);
registerEvent("BLOCK_PHYSICS", Priority.Normal);
registerEvent("BLOCK_PLACE", Priority.High);
registerEvent("BLOCK_BURN", Priority.High);
registerEvent("SIGN_CHANGE", Priority.High);
registerEvent("REDSTONE_CHANGE", Priority.High);
registerEvent("LEAVES_DECAY", Priority.High);
registerEvent("BLOCK_FORM", Priority.High);
registerEvent("BLOCK_SPREAD", Priority.High);
registerEvent("BLOCK_FADE", Priority.High);
registerEvent("BLOCK_PISTON_EXTEND", Priority.High);
registerEvent("BLOCK_PISTON_RETRACT", Priority.High);
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
/**
* Register an event, but not failing if the event is not implemented.
*
* @param typeName
* @param priority
*/
private void registerEvent(String typeName, Priority priority) {
try {
Event.Type type = Event.Type.valueOf(typeName);
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvent(type, this, priority, plugin);
} catch (IllegalArgumentException e) {
logger.info("WorldGuard: Unable to register missing event type " + typeName);
}
}
/**
* Get the world configuration given a world.
*
@@ -129,7 +93,7 @@ public class WorldGuardBlockListener extends BlockListener {
protected WorldConfiguration getWorldConfig(World world) {
return plugin.getGlobalStateManager().get(world);
}
/**
* Get the world configuration given a player.
*
@@ -139,11 +103,11 @@ public class WorldGuardBlockListener extends BlockListener {
protected WorldConfiguration getWorldConfig(Player player) {
return plugin.getGlobalStateManager().get(player.getWorld());
}
/**
* Called when a block is damaged.
*/
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onBlockDamage(BlockDamageEvent event) {
if (event.isCancelled()) {
return;
@@ -154,7 +118,7 @@ public class WorldGuardBlockListener extends BlockListener {
// Cake are damaged and not broken when they are eaten, so we must
// handle them a bit separately
if (blockDamaged.getType() == Material.CAKE_BLOCK) {
if (blockDamaged.getTypeId() == BlockID.CAKE_BLOCK) {
if (!plugin.getGlobalRegionManager().canBuild(player, blockDamaged)) {
player.sendMessage(ChatColor.DARK_RED + "You're not invited to this tea party!");
event.setCancelled(true);
@@ -166,7 +130,7 @@ public class WorldGuardBlockListener extends BlockListener {
/**
* Called when a block is broken.
*/
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onBlockBreak(BlockBreakEvent event) {
if (event.isCancelled()) {
return;
@@ -219,7 +183,7 @@ public class WorldGuardBlockListener extends BlockListener {
/**
* Called when fluids flow.
*/
@Override
@EventHandler
public void onBlockFromTo(BlockFromToEvent event) {
if (event.isCancelled()) {
return;
@@ -316,7 +280,7 @@ public class WorldGuardBlockListener extends BlockListener {
/**
* Called when a block gets ignited.
*/
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onBlockIgnite(BlockIgniteEvent event) {
if (event.isCancelled()) {
return;
@@ -418,7 +382,7 @@ public class WorldGuardBlockListener extends BlockListener {
/**
* Called when a block is destroyed from burning.
*/
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onBlockBurn(BlockBurnEvent event) {
if (event.isCancelled()) {
@@ -474,7 +438,7 @@ public class WorldGuardBlockListener extends BlockListener {
/**
* Called when block physics occurs.
*/
@Override
@EventHandler
public void onBlockPhysics(BlockPhysicsEvent event) {
if (event.isCancelled()) {
@@ -510,7 +474,7 @@ public class WorldGuardBlockListener extends BlockListener {
/**
* Called when a player places a block.
*/
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onBlockPlace(BlockPlaceEvent event) {
if (event.isCancelled()) {
@@ -541,7 +505,7 @@ public class WorldGuardBlockListener extends BlockListener {
}
}
if (wcfg.signChestProtection && wcfg.getChestProtection().isChest(blockPlaced.getType())) {
if (wcfg.signChestProtection && wcfg.getChestProtection().isChest(blockPlaced.getTypeId())) {
if (wcfg.isAdjacentChestProtected(event.getBlock(), player)) {
player.sendMessage(ChatColor.DARK_RED + "This spot is for a chest that you don't have permission for.");
event.setCancelled(true);
@@ -565,7 +529,7 @@ public class WorldGuardBlockListener extends BlockListener {
/**
* Called when redstone changes.
*/
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onBlockRedstoneChange(BlockRedstoneEvent event) {
Block blockTo = event.getBlock();
@@ -601,7 +565,7 @@ public class WorldGuardBlockListener extends BlockListener {
/**
* Called when a sign is changed.
*/
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onSignChange(SignChangeEvent event) {
Player player = event.getPlayer();
@@ -616,7 +580,7 @@ public class WorldGuardBlockListener extends BlockListener {
return;
}
if (event.getBlock().getType() != Material.SIGN_POST) {
if (event.getBlock().getTypeId() != BlockID.SIGN_POST) {
player.sendMessage(ChatColor.RED
+ "The [Lock] sign must be a sign post, not a wall sign.");
@@ -634,10 +598,10 @@ public class WorldGuardBlockListener extends BlockListener {
return;
}
Material below = event.getBlock().getRelative(0, -1, 0).getType();
int below = event.getBlock().getRelative(0, -1, 0).getTypeId();
if (below == Material.TNT || below == Material.SAND
|| below == Material.GRAVEL || below == Material.SIGN_POST) {
if (below == BlockID.TNT || below == BlockID.SAND
|| below == BlockID.GRAVEL || below == BlockID.SIGN_POST) {
player.sendMessage(ChatColor.RED
+ "That is not a safe block that you're putting this sign on.");
@@ -668,7 +632,7 @@ public class WorldGuardBlockListener extends BlockListener {
}
}
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onLeavesDecay(LeavesDecayEvent event) {
if (event.isCancelled()) {
return;
@@ -698,6 +662,7 @@ public class WorldGuardBlockListener extends BlockListener {
/**
* Called when a block is formed based on world conditions.
*/
@EventHandler(priority = EventPriority.HIGH)
public void onBlockForm(BlockFormEvent event) {
if (event.isCancelled()) {
return;
@@ -711,9 +676,9 @@ public class WorldGuardBlockListener extends BlockListener {
return;
}
Material type = event.getNewState().getType();
int type = event.getNewState().getTypeId();
if (type == Material.ICE) {
if (type == BlockID.ICE) {
if (wcfg.disableIceFormation) {
event.setCancelled(true);
return;
@@ -725,7 +690,7 @@ public class WorldGuardBlockListener extends BlockListener {
}
}
if (type == Material.SNOW) {
if (type == BlockID.SNOW) {
if (wcfg.disableSnowFormation) {
event.setCancelled(true);
return;
@@ -741,6 +706,7 @@ public class WorldGuardBlockListener extends BlockListener {
/**
* Called when a block spreads based on world conditions.
*/
@EventHandler(priority = EventPriority.HIGH)
public void onBlockSpread(BlockSpreadEvent event) {
if (event.isCancelled()) {
return;
@@ -754,9 +720,9 @@ public class WorldGuardBlockListener extends BlockListener {
return;
}
Material fromType = event.getSource().getType();
int fromType = event.getSource().getTypeId();
if (fromType == Material.RED_MUSHROOM || fromType == Material.BROWN_MUSHROOM) {
if (fromType == BlockID.RED_MUSHROOM || fromType == BlockID.BROWN_MUSHROOM) {
if (wcfg.disableMushroomSpread) {
event.setCancelled(true);
return;
@@ -768,7 +734,7 @@ public class WorldGuardBlockListener extends BlockListener {
}
}
if (fromType == Material.GRASS) {
if (fromType == BlockID.GRASS) {
if (wcfg.disableGrassGrowth) {
event.setCancelled(true);
return;
@@ -784,6 +750,7 @@ public class WorldGuardBlockListener extends BlockListener {
/**
* Called when a block fades.
*/
@EventHandler(priority = EventPriority.HIGH)
public void onBlockFade(BlockFadeEvent event) {
if (event.isCancelled()) {
return;
@@ -792,9 +759,9 @@ public class WorldGuardBlockListener extends BlockListener {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
Material type = event.getBlock().getType();
int type = event.getBlock().getTypeId();
if (type == Material.ICE) {
if (type == BlockID.ICE) {
if (wcfg.disableIceMelting) {
event.setCancelled(true);
return;
@@ -806,7 +773,7 @@ public class WorldGuardBlockListener extends BlockListener {
}
}
if (type == Material.SNOW) {
if (type == BlockID.SNOW) {
if (wcfg.disableSnowMelting) {
event.setCancelled(true);
return;
@@ -822,6 +789,7 @@ public class WorldGuardBlockListener extends BlockListener {
/**
* Called when a piston extends
*/
@EventHandler(priority = EventPriority.HIGH)
public void onBlockPistonExtend(BlockPistonExtendEvent event) {
if (event.isCancelled()) {
return;
@@ -847,6 +815,7 @@ public class WorldGuardBlockListener extends BlockListener {
/**
* Called when a piston retracts
*/
@EventHandler(priority = EventPriority.HIGH)
public void onBlockPistonRetract(BlockPistonRetractEvent event) {
if (event.isCancelled()) {
return;
@@ -857,7 +826,7 @@ public class WorldGuardBlockListener extends BlockListener {
if (wcfg.useRegions && event.isSticky()) {
if (!(plugin.getGlobalRegionManager().allows(DefaultFlag.PISTONS, event.getRetractLocation()))
&& !(plugin.getGlobalRegionManager().allows(DefaultFlag.PISTONS, event.getBlock().getLocation()))) {
|| !(plugin.getGlobalRegionManager().allows(DefaultFlag.PISTONS, event.getBlock().getLocation()))) {
event.setCancelled(true);
}
}
@@ -23,14 +23,15 @@ import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import java.util.Set;
import java.util.logging.Logger;
import com.sk89q.worldedit.blocks.BlockID;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Creature;
import org.bukkit.entity.CreatureType;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.EnderDragon;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Fireball;
import org.bukkit.entity.LivingEntity;
@@ -41,8 +42,9 @@ import org.bukkit.entity.Skeleton;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.entity.Tameable;
import org.bukkit.entity.Wolf;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.CreeperPowerEvent;
import org.bukkit.event.entity.EndermanPickupEvent;
@@ -54,9 +56,9 @@ import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.EntityInteractEvent;
import org.bukkit.event.entity.EntityListener;
import org.bukkit.event.entity.EntityRegainHealthEvent;
import org.bukkit.event.entity.ExplosionPrimeEvent;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.entity.PigZapEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
@@ -64,8 +66,6 @@ import org.bukkit.event.painting.PaintingBreakByEntityEvent;
import org.bukkit.event.painting.PaintingBreakEvent;
import org.bukkit.event.painting.PaintingPlaceEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.PluginManager;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.blacklist.events.BlockBreakBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
@@ -78,11 +78,7 @@ import com.sk89q.worldguard.protection.managers.RegionManager;
*
* @author sk89q
*/
public class WorldGuardEntityListener extends EntityListener {
/**
* Logger for messages.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
public class WorldGuardEntityListener implements Listener {
private WorldGuardPlugin plugin;
@@ -99,44 +95,13 @@ public class WorldGuardEntityListener extends EntityListener {
* Register events.
*/
public void registerEvents() {
// PluginManager pm = plugin.getServer().getPluginManager();
registerEvent("ENTITY_DAMAGE", Priority.High);
registerEvent("ENTITY_COMBUST", Priority.High);
registerEvent("ENTITY_EXPLODE", Priority.High);
registerEvent("EXPLOSION_PRIME", Priority.High);
registerEvent("CREATURE_SPAWN", Priority.High);
registerEvent("ENTITY_INTERACT", Priority.High);
registerEvent("CREEPER_POWER", Priority.High);
registerEvent("PIG_ZAP", Priority.High);
registerEvent("PAINTING_BREAK", Priority.High);
registerEvent("PAINTING_PLACE", Priority.High);
registerEvent("ENTITY_REGAIN_HEALTH", Priority.High);
registerEvent("ENDERMAN_PICKUP", Priority.High);
registerEvent("ENDERMAN_PLACE", Priority.High);
registerEvent("ENTITY_DEATH", Priority.High);
}
/**
* Register an event, but not failing if the event is not implemented.
*
* @param typeName
* @param priority
*/
private void registerEvent(String typeName, Priority priority) {
try {
Event.Type type = Event.Type.valueOf(typeName);
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvent(type, this, priority, plugin);
} catch (IllegalArgumentException e) {
logger.info("WorldGuard: Unable to register missing event type " + typeName);
}
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
/**
* Called when an entity interacts with another object.
*/
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onEntityInteract(EntityInteractEvent event) {
Entity entity = event.getEntity();
Block block = event.getBlock();
@@ -144,7 +109,7 @@ public class WorldGuardEntityListener extends EntityListener {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(entity.getWorld());
if (block.getType() == Material.SOIL) {
if (block.getTypeId() == BlockID.SOIL) {
if (entity instanceof Creature && wcfg.disableCreatureCropTrampling) {
event.setCancelled(true);
}
@@ -154,12 +119,15 @@ public class WorldGuardEntityListener extends EntityListener {
/**
* Called when an entity dies.
*/
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onEntityDeath(EntityDeathEvent event) {
WorldConfiguration wcfg = plugin.getGlobalStateManager().get(event.getEntity().getWorld());
if (wcfg.disableExpDrops) {
if (wcfg.disableExpDrops || !plugin.getGlobalRegionManager().allows(DefaultFlag.EXP_DROPS,
event.getEntity().getLocation())) {
event.setDroppedExp(0);
}
try {
if (event instanceof PlayerDeathEvent && wcfg.disableDeathMessages) {
((PlayerDeathEvent) event).setDeathMessage("");
@@ -196,7 +164,7 @@ public class WorldGuardEntityListener extends EntityListener {
if (wcfg.disableLavaDamage && type == DamageCause.LAVA) {
event.setCancelled(true);
if (cfg.hasGodMode(player)) player.setFireTicks(0);
player.setFireTicks(0);
return;
}
@@ -287,9 +255,10 @@ public class WorldGuardEntityListener extends EntityListener {
if (attacker != null && attacker instanceof Player) {
if (wcfg.useRegions) {
Vector pt = toVector(defender.getLocation());
Vector pt2 = toVector(attacker.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.PVP)) {
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.PVP) || !mgr.getApplicableRegions(pt2).allows(DefaultFlag.PVP)) {
((Player) attacker).sendMessage(ChatColor.DARK_RED + "You are in a no-PvP area.");
event.setCancelled(true);
return;
@@ -319,13 +288,24 @@ public class WorldGuardEntityListener extends EntityListener {
return;
}
if (wcfg.useRegions) {
Fireball fireball = (Fireball) attacker;
Vector pt = toVector(defender.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (!set.allows(DefaultFlag.GHAST_FIREBALL)) {
event.setCancelled(true);
return;
if (fireball.getShooter() instanceof Player) {
Vector pt2 = toVector(fireball.getShooter().getLocation());
if (!set.allows(DefaultFlag.PVP) || !mgr.getApplicableRegions(pt2).allows(DefaultFlag.PVP)) {
((Player) fireball.getShooter()).sendMessage(ChatColor.DARK_RED + "You are in a no-PvP area.");
event.setCancelled(true);
return;
}
} else {
if (!set.allows(DefaultFlag.GHAST_FIREBALL)) {
event.setCancelled(true);
return;
}
}
}
}
@@ -417,7 +397,7 @@ public class WorldGuardEntityListener extends EntityListener {
/**
* Called on entity damage.
*/
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onEntityDamage(EntityDamageEvent event) {
if (event.isCancelled()) {
return;
@@ -458,8 +438,8 @@ public class WorldGuardEntityListener extends EntityListener {
}
if (type == DamageCause.DROWNING && wcfg.pumpkinScuba
&& (player.getInventory().getHelmet().getType() == Material.PUMPKIN
|| player.getInventory().getHelmet().getType() == Material.JACK_O_LANTERN)) {
&& (player.getInventory().getHelmet().getTypeId() == BlockID.PUMPKIN
|| player.getInventory().getHelmet().getTypeId() == BlockID.JACKOLANTERN)) {
player.setRemainingAir(player.getMaximumAir());
event.setCancelled(true);
return;
@@ -498,7 +478,7 @@ public class WorldGuardEntityListener extends EntityListener {
/**
* Called on entity combust.
*/
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onEntityCombust(EntityCombustEvent event) {
if (event.isCancelled()) {
return;
@@ -522,7 +502,7 @@ public class WorldGuardEntityListener extends EntityListener {
/**
* Called on entity explode.
*/
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onEntityExplode(EntityExplodeEvent event) {
if (event.isCancelled()) {
return;
@@ -540,8 +520,13 @@ public class WorldGuardEntityListener extends EntityListener {
return;
}
if (ent instanceof LivingEntity) {
if (wcfg.blockCreeperBlockDamage || wcfg.blockCreeperExplosions) {
if (ent instanceof Creeper) {
if (wcfg.blockCreeperBlockDamage) {
event.blockList().clear();
return;
}
if (wcfg.blockCreeperExplosions) {
event.setCancelled(true);
return;
}
@@ -552,14 +537,37 @@ public class WorldGuardEntityListener extends EntityListener {
for (Block block : event.blockList()) {
if (!mgr.getApplicableRegions(toVector(block)).allows(DefaultFlag.CREEPER_EXPLOSION)) {
event.setCancelled(true);
event.blockList().clear();
return;
}
}
}
}
} else if (ent instanceof EnderDragon) {
if (wcfg.blockEnderDragonBlockDamage) {
event.blockList().clear();
return;
}
if (wcfg.useRegions) {
if (wcfg.useRegions) {
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
for (Block block : event.blockList()) {
if (!mgr.getApplicableRegions(toVector(block)).allows(DefaultFlag.ENDERDRAGON_BLOCK_DAMAGE)) {
event.blockList().clear();
return;
}
}
}
}
} else if (ent instanceof TNTPrimed) {
if (wcfg.blockTNTBlockDamage || wcfg.blockTNTExplosions) {
if (wcfg.blockTNTBlockDamage) {
event.blockList().clear();
return;
}
if (wcfg.blockTNTExplosions) {
event.setCancelled(true);
return;
}
@@ -569,13 +577,18 @@ public class WorldGuardEntityListener extends EntityListener {
for (Block block : event.blockList()) {
if (!mgr.getApplicableRegions(toVector(block)).allows(DefaultFlag.TNT)) {
event.setCancelled(true);
event.blockList().clear();
return;
}
}
}
} else if (ent instanceof Fireball) {
if (wcfg.blockFireballBlockDamage || wcfg.blockFireballExplosions) {
if (wcfg.blockFireballBlockDamage) {
event.blockList().clear();
return;
}
if (wcfg.blockFireballExplosions) {
event.setCancelled(true);
return;
}
@@ -585,7 +598,7 @@ public class WorldGuardEntityListener extends EntityListener {
for (Block block : event.blockList()) {
if (!mgr.getApplicableRegions(toVector(block)).allows(DefaultFlag.GHAST_FIREBALL)) {
event.setCancelled(true);
event.blockList().clear();
return;
}
}
@@ -595,7 +608,7 @@ public class WorldGuardEntityListener extends EntityListener {
if (wcfg.signChestProtection) {
for (Block block : event.blockList()) {
if (wcfg.isChestProtected(block)) {
event.setCancelled(true);
event.blockList().clear();
return;
}
}
@@ -606,7 +619,7 @@ public class WorldGuardEntityListener extends EntityListener {
/**
* Called on explosion prime
*/
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onExplosionPrime(ExplosionPrimeEvent event) {
if (event.isCancelled()) {
return;
@@ -626,7 +639,7 @@ public class WorldGuardEntityListener extends EntityListener {
/**
* Called on creature spawn.
*/
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onCreatureSpawn(CreatureSpawnEvent event) {
if (event.isCancelled()) {
return;
@@ -672,7 +685,7 @@ public class WorldGuardEntityListener extends EntityListener {
/**
* Called on pig zap.
*/
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onPigZap(PigZapEvent event) {
if (event.isCancelled()) {
return;
@@ -689,7 +702,7 @@ public class WorldGuardEntityListener extends EntityListener {
/**
* Called on creeper power.
*/
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onCreeperPower(CreeperPowerEvent event) {
if (event.isCancelled()) {
return;
@@ -706,7 +719,7 @@ public class WorldGuardEntityListener extends EntityListener {
/**
* Called when a painting is removed.
*/
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onPaintingBreak(PaintingBreakEvent breakEvent) {
if (breakEvent.isCancelled()) {
return;
@@ -749,7 +762,7 @@ public class WorldGuardEntityListener extends EntityListener {
/**
* Called on painting place.
*/
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onPaintingPlace(PaintingPlaceEvent event) {
if (event.isCancelled()) {
return;
@@ -783,6 +796,7 @@ public class WorldGuardEntityListener extends EntityListener {
/**
* Called on entity health regain.
*/
@EventHandler(priority = EventPriority.HIGH)
public void onEntityRegainHealth(EntityRegainHealthEvent event) {
if (event.isCancelled()) {
return;
@@ -803,7 +817,7 @@ public class WorldGuardEntityListener extends EntityListener {
/**
* Called when an enderman picks a block up.
*/
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onEndermanPickup(EndermanPickupEvent event) {
if (event.isCancelled()) {
return;
@@ -831,7 +845,7 @@ public class WorldGuardEntityListener extends EntityListener {
/**
* Called when an enderman places a block.
*/
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onEndermanPlace(EndermanPlaceEvent event) {
if (event.isCancelled()) {
return;
@@ -856,6 +870,16 @@ public class WorldGuardEntityListener extends EntityListener {
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onFoodLevelChange(FoodLevelChangeEvent event) {
if (event.getEntity() instanceof Player) {
Player player = (Player) event.getEntity();
if (event.getFoodLevel() < player.getFoodLevel() && isInvincible(player)) {
event.setCancelled(true);
}
}
}
/**
* Check if a player is invincible, via either god mode or region flag. If
* the region denies invincibility, the player must have an extra permission
@@ -24,17 +24,19 @@ import java.util.Iterator;
import java.util.Set;
import java.util.logging.Logger;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.blocks.ItemID;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.Event.Result;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerBedEnterEvent;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
@@ -44,7 +46,6 @@ import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerItemHeldEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerListener;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent;
@@ -57,6 +58,7 @@ import com.sk89q.worldedit.blocks.BlockType;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.events.BlockBreakBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockInteractBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockPlaceBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemAcquireBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemDropBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
@@ -71,12 +73,7 @@ import com.sk89q.worldguard.protection.regions.ProtectedRegion;
/**
* Handles all events thrown in relation to a player.
*/
public class WorldGuardPlayerListener extends PlayerListener {
/**
* Logger for messages.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
public class WorldGuardPlayerListener implements Listener {
private WorldGuardPlugin plugin;
@@ -93,68 +90,142 @@ public class WorldGuardPlayerListener extends PlayerListener {
* Register events.
*/
public void registerEvents() {
// PluginManager pm = plugin.getServer().getPluginManager();
final PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvents(this, plugin);
registerEvent("PLAYER_INTERACT", Priority.High);
registerEvent("PLAYER_DROP_ITEM", Priority.High);
registerEvent("PLAYER_PICKUP_ITEM", Priority.High);
registerEvent("PLAYER_JOIN", Priority.Normal);
registerEvent("PLAYER_LOGIN", Priority.Normal);
registerEvent("PLAYER_QUIT", Priority.Normal);
registerEvent("PLAYER_BUCKET_FILL", Priority.High);
registerEvent("PLAYER_BUCKET_EMPTY", Priority.High);
registerEvent("PLAYER_RESPAWN", Priority.High);
registerEvent("PLAYER_ITEM_HELD", Priority.High);
registerEvent("PLAYER_BED_ENTER", Priority.High);
registerEvent("PLAYER_COMMAND_PREPROCESS", Priority.High);
if (plugin.getGlobalStateManager().usePlayerMove) {
registerEvent("PLAYER_MOVE", Priority.High);
pm.registerEvents(new PlayerMoveHandler(), plugin);
}
}
private class PlayerMoveHandler implements Listener {
/**
* Called when a player attempts to move.
*
* @param event
*/
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerMove(PlayerMoveEvent event) {
Player player = event.getPlayer();
World world = player.getWorld();
/**
* Register an event, but not failing if the event is not implemented.
*
* @param typeName
* @param priority
*/
private void registerEvent(String typeName, Priority priority) {
try {
Event.Type type = Event.Type.valueOf(typeName);
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvent(type, this, priority, plugin);
} catch (IllegalArgumentException e) {
logger.info("WorldGuard: Unable to register missing event type " + typeName);
}
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
/**
* Called when a player attempts to log in to the server.
*/
/*
@Override
public void onPlayerLogin(PlayerLoginEvent event) {
Player player = event.getPlayer();
if (player.getVehicle() != null) return; // handled in vehicle listener
if (wcfg.useRegions) {
// Did we move a block?
if (event.getFrom().getBlockX() != event.getTo().getBlockX()
|| event.getFrom().getBlockY() != event.getTo().getBlockY()
|| event.getFrom().getBlockZ() != event.getTo().getBlockZ()) {
PlayerFlagState state = plugin.getFlagStateManager().getState(player);
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
//Flush states in multiworld scenario
if (state.lastWorld != null && !state.lastWorld.equals(world)) {
plugin.getFlagStateManager().forget(player);
state = plugin.getFlagStateManager().getState(player);
}
LocalPlayer localPlayer = plugin.wrapPlayer(player);
boolean hasBypass = plugin.getGlobalRegionManager().hasBypass(player, world);
if (wcfg.enforceOneSession) {
String name = player.getName();
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
Vector pt = new Vector(event.getTo().getBlockX(), event.getTo().getBlockY(), event.getTo().getBlockZ());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
for (Player pl : plugin.getServer().getOnlinePlayers()) {
if (pl.getName().equalsIgnoreCase(name)) {
pl.kickPlayer("Logged in from another location.");
boolean entryAllowed = set.allows(DefaultFlag.ENTRY, localPlayer);
if (!hasBypass && !entryAllowed) {
player.sendMessage(ChatColor.DARK_RED + "You are not permitted to enter this area.");
Location newLoc = event.getFrom();
newLoc.setX(newLoc.getBlockX() + 0.5);
newLoc.setY(newLoc.getBlockY());
newLoc.setZ(newLoc.getBlockZ() + 0.5);
event.setTo(newLoc);
return;
}
// Have to set this state
if (state.lastExitAllowed == null) {
state.lastExitAllowed = mgr.getApplicableRegions(toVector(event.getFrom()))
.allows(DefaultFlag.EXIT, localPlayer);
}
boolean exitAllowed = set.allows(DefaultFlag.EXIT, localPlayer);
if (!hasBypass && exitAllowed && !state.lastExitAllowed) {
player.sendMessage(ChatColor.DARK_RED + "You are not permitted to leave this area.");
Location newLoc = event.getFrom();
newLoc.setX(newLoc.getBlockX() + 0.5);
newLoc.setY(newLoc.getBlockY());
newLoc.setZ(newLoc.getBlockZ() + 0.5);
event.setTo(newLoc);
return;
}
String greeting = set.getFlag(DefaultFlag.GREET_MESSAGE);
String farewell = set.getFlag(DefaultFlag.FAREWELL_MESSAGE);
Boolean notifyEnter = set.getFlag(DefaultFlag.NOTIFY_ENTER);
Boolean notifyLeave = set.getFlag(DefaultFlag.NOTIFY_LEAVE);
if (state.lastFarewell != null && (farewell == null
|| !state.lastFarewell.equals(farewell))) {
String replacedFarewell = plugin.replaceMacros(
player, BukkitUtil.replaceColorMacros(state.lastFarewell));
player.sendMessage(ChatColor.AQUA + " ** " + replacedFarewell);
}
if (greeting != null && (state.lastGreeting == null
|| !state.lastGreeting.equals(greeting))) {
String replacedGreeting = plugin.replaceMacros(
player, BukkitUtil.replaceColorMacros(greeting));
player.sendMessage(ChatColor.AQUA + " ** " + replacedGreeting);
}
if ((notifyLeave == null || !notifyLeave)
&& state.notifiedForLeave != null && state.notifiedForLeave) {
plugin.broadcastNotification(ChatColor.GRAY + "WG: "
+ ChatColor.LIGHT_PURPLE + player.getName()
+ ChatColor.GOLD + " left NOTIFY region");
}
if (notifyEnter != null && notifyEnter && (state.notifiedForEnter == null
|| !state.notifiedForEnter)) {
StringBuilder regionList = new StringBuilder();
for (ProtectedRegion region : set) {
if (regionList.length() != 0) {
regionList.append(", ");
}
regionList.append(region.getId());
}
plugin.broadcastNotification(ChatColor.GRAY + "WG: "
+ ChatColor.LIGHT_PURPLE + player.getName()
+ ChatColor.GOLD + " entered NOTIFY region: "
+ ChatColor.WHITE
+ regionList);
}
state.lastGreeting = greeting;
state.lastFarewell = farewell;
state.notifiedForEnter = notifyEnter;
state.notifiedForLeave = notifyLeave;
state.lastExitAllowed = exitAllowed;
state.lastWorld = event.getTo().getWorld();
state.lastBlockX = event.getTo().getBlockX();
state.lastBlockY = event.getTo().getBlockY();
state.lastBlockZ = event.getTo().getBlockZ();
}
}
}
}
*/
}
/**
* Called when a player joins a server.
*/
@Override
@SuppressWarnings("deprecation")
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
World world = player.getWorld();
@@ -176,7 +247,7 @@ public class WorldGuardPlayerListener extends PlayerListener {
}
if (removed > 10) {
logger.info("WG Halt-Act: " + removed + " entities (>10) auto-removed from "
plugin.getLogger().info("Halt-Act: " + removed + " entities (>10) auto-removed from "
+ player.getWorld().toString());
}
}
@@ -186,8 +257,8 @@ public class WorldGuardPlayerListener extends PlayerListener {
+ "Fire spread is currently globally disabled for this world.");
}
if (plugin.inGroup(player, "wg-invincible")
|| (cfg.autoGodMode && plugin.hasPermission(player, "worldguard.auto-invincible"))) {
if (!cfg.hasCommandBookGodMode() && cfg.autoGodMode && (plugin.inGroup(player, "wg-invincible")
|| plugin.hasPermission(player, "worldguard.auto-invincible"))) {
cfg.enableGodMode(player);
}
@@ -208,7 +279,7 @@ public class WorldGuardPlayerListener extends PlayerListener {
/**
* Called when a player leaves a server.
*/
@Override
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
Player player = event.getPlayer();
World world = player.getWorld();
@@ -253,7 +324,7 @@ public class WorldGuardPlayerListener extends PlayerListener {
/**
* Called when a player interacts with an item.
*/
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerInteract(PlayerInteractEvent event) {
Player player = event.getPlayer();
World world = player.getWorld();
@@ -283,120 +354,6 @@ public class WorldGuardPlayerListener extends PlayerListener {
}
}
}
/**
* Called when a player attempts to move.
*
* @param event
*/
@Override
public void onPlayerMove(PlayerMoveEvent event) {
Player player = event.getPlayer();
World world = player.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (player.getVehicle() != null) return; // handled in vehicle listener
if (wcfg.useRegions) {
// Did we move a block?
if (event.getFrom().getBlockX() != event.getTo().getBlockX()
|| event.getFrom().getBlockY() != event.getTo().getBlockY()
|| event.getFrom().getBlockZ() != event.getTo().getBlockZ()) {
PlayerFlagState state = plugin.getFlagStateManager().getState(player);
LocalPlayer localPlayer = plugin.wrapPlayer(player);
boolean hasBypass = plugin.getGlobalRegionManager().hasBypass(player, world);
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
Vector pt = new Vector(event.getTo().getBlockX(), event.getTo().getBlockY(), event.getTo().getBlockZ());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
boolean entryAllowed = set.allows(DefaultFlag.ENTRY, localPlayer);
if (!hasBypass && !entryAllowed) {
player.sendMessage(ChatColor.DARK_RED + "You are not permitted to enter this area.");
Location newLoc = event.getFrom();
newLoc.setX(newLoc.getBlockX() + 0.5);
newLoc.setY(newLoc.getBlockY());
newLoc.setZ(newLoc.getBlockZ() + 0.5);
event.setTo(newLoc);
return;
}
// Have to set this state
if (state.lastExitAllowed == null) {
state.lastExitAllowed = mgr.getApplicableRegions(toVector(event.getFrom()))
.allows(DefaultFlag.EXIT, localPlayer);
}
boolean exitAllowed = set.allows(DefaultFlag.EXIT, localPlayer);
if (!hasBypass && exitAllowed && !state.lastExitAllowed) {
player.sendMessage(ChatColor.DARK_RED + "You are not permitted to leave this area.");
Location newLoc = event.getFrom();
newLoc.setX(newLoc.getBlockX() + 0.5);
newLoc.setY(newLoc.getBlockY());
newLoc.setZ(newLoc.getBlockZ() + 0.5);
event.setTo(newLoc);
return;
}
String greeting = set.getFlag(DefaultFlag.GREET_MESSAGE);
String farewell = set.getFlag(DefaultFlag.FAREWELL_MESSAGE);
Boolean notifyEnter = set.getFlag(DefaultFlag.NOTIFY_ENTER);
Boolean notifyLeave = set.getFlag(DefaultFlag.NOTIFY_LEAVE);
if (state.lastFarewell != null && (farewell == null
|| !state.lastFarewell.equals(farewell))) {
String replacedFarewell = plugin.replaceMacros(
player, BukkitUtil.replaceColorMacros(state.lastFarewell));
player.sendMessage(ChatColor.AQUA + " ** " + replacedFarewell);
}
if (greeting != null && (state.lastGreeting == null
|| !state.lastGreeting.equals(greeting))) {
String replacedGreeting = plugin.replaceMacros(
player, BukkitUtil.replaceColorMacros(greeting));
player.sendMessage(ChatColor.AQUA + " ** " + replacedGreeting);
}
if ((notifyLeave == null || !notifyLeave)
&& state.notifiedForLeave != null && state.notifiedForLeave) {
plugin.broadcastNotification(ChatColor.GRAY + "WG: "
+ ChatColor.LIGHT_PURPLE + player.getName()
+ ChatColor.GOLD + " left NOTIFY region");
}
if (notifyEnter != null && notifyEnter && (state.notifiedForEnter == null
|| !state.notifiedForEnter)) {
StringBuilder regionList = new StringBuilder();
for (ProtectedRegion region : set) {
if (regionList.length() != 0) {
regionList.append(", ");
}
regionList.append(region.getId());
}
plugin.broadcastNotification(ChatColor.GRAY + "WG: "
+ ChatColor.LIGHT_PURPLE + player.getName()
+ ChatColor.GOLD + " entered NOTIFY region: "
+ ChatColor.WHITE
+ regionList);
}
state.lastGreeting = greeting;
state.lastFarewell = farewell;
state.notifiedForEnter = notifyEnter;
state.notifiedForLeave = notifyLeave;
state.lastExitAllowed = exitAllowed;
state.lastWorld = event.getTo().getWorld();
state.lastBlockX = event.getTo().getBlockX();
state.lastBlockY = event.getTo().getBlockY();
state.lastBlockZ = event.getTo().getBlockZ();
}
}
}
/**
* Called when a player left clicks air.
@@ -418,7 +375,7 @@ public class WorldGuardPlayerListener extends PlayerListener {
Player player = event.getPlayer();
Block block = event.getClickedBlock();
Material type = block.getType();
int type = block.getTypeId();
World world = player.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
@@ -430,11 +387,11 @@ public class WorldGuardPlayerListener extends PlayerListener {
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (type == Material.STONE_BUTTON
|| type == Material.LEVER
|| type == Material.WOODEN_DOOR
|| type == Material.TRAP_DOOR
|| type == Material.NOTE_BLOCK) {
if (type == BlockID.STONE_BUTTON
|| type == BlockID.LEVER
|| type == BlockID.WOODEN_DOOR
|| type == BlockID.TRAP_DOOR
|| type == BlockID.NOTE_BLOCK) {
if (!plugin.getGlobalRegionManager().hasBypass(player, world)
&& !set.allows(DefaultFlag.USE)
&& !set.canBuild(localPlayer)) {
@@ -445,7 +402,7 @@ public class WorldGuardPlayerListener extends PlayerListener {
}
}
if (block.getRelative(event.getBlockFace()).getType() == Material.FIRE) {
if (block.getRelative(event.getBlockFace()).getTypeId() == BlockID.FIRE) {
if (!plugin.getGlobalRegionManager().hasBypass(player, world)
&& !set.canBuild(localPlayer)) {
event.setUseInteractedBlock(Result.DENY);
@@ -456,7 +413,7 @@ public class WorldGuardPlayerListener extends PlayerListener {
}
if (type == Material.TNT && player.getItemInHand().getType() == Material.FLINT_AND_STEEL) {
if (type == BlockID.TNT && player.getItemInHand().getTypeId() == ItemID.FLINT_AND_TINDER) {
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new BlockBreakBlacklistEvent(plugin.wrapPlayer(player),
@@ -512,7 +469,7 @@ public class WorldGuardPlayerListener extends PlayerListener {
Block block = event.getClickedBlock();
World world = block.getWorld();
Material type = block.getType();
int type = block.getTypeId();
Player player = event.getPlayer();
ItemStack item = player.getItemInHand();
@@ -520,11 +477,14 @@ public class WorldGuardPlayerListener extends PlayerListener {
WorldConfiguration wcfg = cfg.get(world);
// Infinite stack removal
if ((type == Material.CHEST
|| type == Material.JUKEBOX
|| type == Material.DISPENSER
|| type == Material.FURNACE
|| type == Material.BURNING_FURNACE)
if ((type == BlockID.CHEST
|| type == BlockID.JUKEBOX
|| type == BlockID.DISPENSER
|| type == BlockID.FURNACE
|| type == BlockID.BURNING_FURNACE
|| type == BlockID.BREWING_STAND
|| type == BlockID.ENCHANTMENT_TABLE
|| type == BlockID.CAULDRON)
&& wcfg.removeInfiniteStacks
&& !plugin.hasPermission(player, "worldguard.override.infinite-stack")) {
for (int slot = 0; slot < 40; slot++) {
@@ -542,7 +502,7 @@ public class WorldGuardPlayerListener extends PlayerListener {
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (item.getTypeId() == wcfg.regionWand) {
if (item.getTypeId() == wcfg.regionWand && plugin.hasPermission(player, "worldguard.region.wand")) {
if (set.size() > 0) {
player.sendMessage(ChatColor.YELLOW + "Can you build? "
+ (set.canBuild(localPlayer) ? "Yes" : "No"));
@@ -563,19 +523,29 @@ public class WorldGuardPlayerListener extends PlayerListener {
event.setCancelled(true);
return;
}
if (item.getType() == Material.INK_SACK
if (item.getTypeId() == BlockID.TNT) {
Block placedOn = block.getRelative(event.getBlockFace());
if (!plugin.getGlobalRegionManager().hasBypass(player, world)
&& !plugin.getGlobalRegionManager().allows(
DefaultFlag.TNT, placedOn.getLocation())) {
event.setUseItemInHand(Result.DENY);
event.setCancelled(true);
}
}
if (item.getTypeId() == ItemID.INK_SACK
&& item.getData() != null
&& item.getData().getData() == 15 // bonemeal
&& type == Material.GRASS) {
&& type == BlockID.GRASS) {
if (!plugin.getGlobalRegionManager().hasBypass(player, world)
&& !set.canBuild(localPlayer)) {
event.setCancelled(true);
event.setUseInteractedBlock(Result.DENY);
event.setUseItemInHand(Result.DENY);
}
}
if (type == Material.BED_BLOCK) {
if (type == BlockID.BED) {
if (!plugin.getGlobalRegionManager().hasBypass(player, world)
&& !set.allows(DefaultFlag.SLEEP)) {
player.sendMessage(ChatColor.DARK_RED + "You're not allowed to use that bed.");
@@ -585,11 +555,12 @@ public class WorldGuardPlayerListener extends PlayerListener {
}
}
if (type == Material.CHEST
|| type == Material.JUKEBOX //stores the (arguably) most valuable item
|| type == Material.DISPENSER
|| type == Material.FURNACE
|| type == Material.BURNING_FURNACE) {
if (type == BlockID.CHEST
|| type == BlockID.JUKEBOX //stores the (arguably) most valuable item
|| type == BlockID.DISPENSER
|| type == BlockID.FURNACE
|| type == BlockID.BURNING_FURNACE
|| type == BlockID.BREWING_STAND) {
if (!plugin.getGlobalRegionManager().hasBypass(player, world)
&& !set.allows(DefaultFlag.CHEST_ACCESS)
&& !set.canBuild(localPlayer)) {
@@ -599,16 +570,24 @@ public class WorldGuardPlayerListener extends PlayerListener {
return;
}
}
if (type == Material.LEVER
|| type == Material.STONE_BUTTON
|| type == Material.NOTE_BLOCK
|| type == Material.DIODE_BLOCK_OFF
|| type == Material.DIODE_BLOCK_ON
|| type == Material.WOODEN_DOOR
|| type == Material.TRAP_DOOR
|| type == Material.FENCE_GATE
|| type == Material.WORKBENCH) {
if (type == BlockID.LEVER
|| type == BlockID.STONE_BUTTON
|| type == BlockID.NOTE_BLOCK
|| type == BlockID.REDSTONE_REPEATER_OFF
|| type == BlockID.REDSTONE_REPEATER_ON
|| type == BlockID.WOODEN_DOOR
|| type == BlockID.TRAP_DOOR
|| type == BlockID.FENCE_GATE
|| type == BlockID.JUKEBOX //stores the (arguably) most valuable item
|| type == BlockID.DISPENSER
|| type == BlockID.FURNACE
|| type == BlockID.BURNING_FURNACE
|| type == BlockID.WORKBENCH
|| type == BlockID.BREWING_STAND
|| type == BlockID.ENCHANTMENT_TABLE
|| type == BlockID.CAULDRON
|| type == BlockID.DRAGON_EGG) {
if (!plugin.getGlobalRegionManager().hasBypass(player, world)
&& !set.allows(DefaultFlag.USE)
&& !set.canBuild(localPlayer)) {
@@ -619,7 +598,7 @@ public class WorldGuardPlayerListener extends PlayerListener {
}
}
if (type == Material.CAKE_BLOCK) {
if (type == BlockID.CAKE_BLOCK) {
if (!plugin.getGlobalRegionManager().hasBypass(player, world)
&& !set.canBuild(localPlayer)) {
player.sendMessage(ChatColor.DARK_RED + "You're not invited to this tea party!");
@@ -628,8 +607,8 @@ public class WorldGuardPlayerListener extends PlayerListener {
return;
}
}
if (BlockType.isRailBlock(type.getId()) && item.getType() == Material.MINECART) {
if (BlockType.isRailBlock(type) && item.getTypeId() == ItemID.MINECART) {
if (!plugin.getGlobalRegionManager().hasBypass(player, world)
&& !set.canBuild(localPlayer)
&& !set.allows(DefaultFlag.PLACE_VEHICLE)) {
@@ -640,7 +619,7 @@ public class WorldGuardPlayerListener extends PlayerListener {
}
}
if (item.getType() == Material.BOAT) {
if (item.getTypeId() == ItemID.WOOD_BOAT) {
if (!plugin.getGlobalRegionManager().hasBypass(player, world)
&& !set.canBuild(localPlayer)
&& !set.allows(DefaultFlag.PLACE_VEHICLE)) {
@@ -653,10 +632,13 @@ public class WorldGuardPlayerListener extends PlayerListener {
}
if (wcfg.getBlacklist() != null) {
if((block.getType() != Material.CHEST
&& block.getType() != Material.DISPENSER
&& block.getType() != Material.FURNACE
&& block.getType() != Material.BURNING_FURNACE)) {
if(type != BlockID.CHEST
&& type != BlockID.DISPENSER
&& type != BlockID.FURNACE
&& type != BlockID.BURNING_FURNACE
&& type != BlockID.BREWING_STAND
&& type != BlockID.ENCHANTMENT_TABLE
&& type != BlockID.CAULDRON) {
if (!wcfg.getBlacklist().check(
new ItemUseBlacklistEvent(plugin.wrapPlayer(player), toVector(block),
item.getTypeId()), false, false)) {
@@ -674,12 +656,25 @@ public class WorldGuardPlayerListener extends PlayerListener {
return;
}
// Workaround for http://leaky.bukkit.org/issues/1034
if (item.getTypeId() == BlockID.TNT) {
Block placedOn = block.getRelative(event.getBlockFace());
if (!wcfg.getBlacklist().check(
new BlockPlaceBlacklistEvent(plugin.wrapPlayer(player), toVector(placedOn),
item.getTypeId()), false, false)) {
event.setUseItemInHand(Result.DENY);
event.setCancelled(true);
return;
}
}
}
if ((block.getType() == Material.CHEST
|| block.getType() == Material.DISPENSER
|| block.getType() == Material.FURNACE
|| block.getType() == Material.BURNING_FURNACE)) {
if ((type == BlockID.CHEST
|| type == BlockID.DISPENSER
|| type == BlockID.FURNACE
|| type == BlockID.BURNING_FURNACE
|| type == BlockID.ENCHANTMENT_TABLE
|| type == BlockID.BREWING_STAND)) {
if (wcfg.isChestProtected(block, player)) {
player.sendMessage(ChatColor.DARK_RED + "The chest is protected.");
@@ -690,7 +685,7 @@ public class WorldGuardPlayerListener extends PlayerListener {
}
/*if (wcfg.useRegions && wcfg.useiConomy && cfg.getiConomy() != null
&& (type == Material.SIGN_POST || type == Material.SIGN || type == Material.WALL_SIGN)) {
&& (type == BlockID.SIGN_POST || type == ItemID.SIGN || type == BlockID.WALL_SIGN)) {
BlockState block = blockClicked.getState();
if (((Sign)block).getLine(0).equalsIgnoreCase("[WorldGuard]")
@@ -745,17 +740,17 @@ public class WorldGuardPlayerListener extends PlayerListener {
* @param event
*/
private void handlePhysicalInteract(PlayerInteractEvent event) {
if (event.isCancelled() == true) return;
if (event.isCancelled()) return;
Player player = event.getPlayer();
Block block = event.getClickedBlock(); //not actually clicked but whatever
Material type = block.getType();
int type = block.getTypeId();
World world = player.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (block.getType() == Material.SOIL && wcfg.disablePlayerCropTrampling) {
if (block.getTypeId() == BlockID.SOIL && wcfg.disablePlayerCropTrampling) {
event.setCancelled(true);
return;
}
@@ -766,7 +761,7 @@ public class WorldGuardPlayerListener extends PlayerListener {
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (type == Material.STONE_PLATE || type == Material.WOOD_PLATE) {
if (type == BlockID.STONE_PRESSURE_PLATE || type == BlockID.WOODEN_PRESSURE_PLATE) {
if (!plugin.getGlobalRegionManager().hasBypass(player, world)
&& !set.allows(DefaultFlag.USE)
&& !set.canBuild(localPlayer)) {
@@ -812,7 +807,7 @@ public class WorldGuardPlayerListener extends PlayerListener {
if (wcfg.useRegions && !event.isBlock() && block != null) {
Vector pt = toVector(block.getRelative(event.getBlockFace()));
if (block.getType() == Material.WALL_SIGN) {
if (block.getTypeId() == BlockID.WALL_SIGN) {
pt = pt.subtract(0, 1, 0);
}
@@ -848,7 +843,7 @@ public class WorldGuardPlayerListener extends PlayerListener {
/**
* Called when a player attempts to drop an item.
*/
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerDropItem(PlayerDropItemEvent event) {
if (event.isCancelled()) {
return;
@@ -872,7 +867,7 @@ public class WorldGuardPlayerListener extends PlayerListener {
/**
* Called when a player attempts to pickup an item.
*/
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerPickupItem(PlayerPickupItemEvent event) {
if (event.isCancelled()) {
return;
@@ -896,7 +891,7 @@ public class WorldGuardPlayerListener extends PlayerListener {
/**
* Called when a bucket is filled.
*/
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerBucketFill(PlayerBucketFillEvent event) {
Player player = event.getPlayer();
World world = player.getWorld();
@@ -904,7 +899,14 @@ public class WorldGuardPlayerListener extends PlayerListener {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (!plugin.getGlobalRegionManager().canBuild(
if (event.getItemStack().getTypeId() == ItemID.MILK_BUCKET) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.USE, player.getLocation().add(0, 1, 0))) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission to use this in this area.");
event.setCancelled(true);
return;
}
} else if (!plugin.getGlobalRegionManager().canBuild(
player, event.getBlockClicked().getRelative(event.getBlockFace()))) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
@@ -924,7 +926,7 @@ public class WorldGuardPlayerListener extends PlayerListener {
/**
* Called when a bucket is empty.
*/
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event) {
Player player = event.getPlayer();
World world = player.getWorld();
@@ -952,7 +954,7 @@ public class WorldGuardPlayerListener extends PlayerListener {
/**
* Called when a player is respawned.
*/
@Override
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerRespawn(PlayerRespawnEvent event) {
Player player = event.getPlayer();
Location location = player.getLocation();
@@ -987,7 +989,7 @@ public class WorldGuardPlayerListener extends PlayerListener {
/**
* Called when a player changes their held item.
*/
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onItemHeldChange(PlayerItemHeldEvent event) {
Player player = event.getPlayer();
@@ -1008,7 +1010,7 @@ public class WorldGuardPlayerListener extends PlayerListener {
/**
* Called when a player enters a bed.
*/
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerBedEnter(PlayerBedEnterEvent event) {
if (event.isCancelled()) {
return;
@@ -1037,7 +1039,7 @@ public class WorldGuardPlayerListener extends PlayerListener {
/**
* Called on command run.
*/
@Override
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
Player player = event.getPlayer();
World world = player.getWorld();
@@ -33,6 +33,9 @@ import java.util.logging.Filter;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import com.sk89q.bukkit.util.CommandsManagerRegistration;
import com.sk89q.minecraft.util.commands.*;
import com.sk89q.wepif.PermissionsResolverManager;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
@@ -44,13 +47,6 @@ import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import com.sk89q.bukkit.migration.PermissionsResolverManager;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissionsException;
import com.sk89q.minecraft.util.commands.CommandUsageException;
import com.sk89q.minecraft.util.commands.CommandsManager;
import com.sk89q.minecraft.util.commands.MissingNestedCommandException;
import com.sk89q.minecraft.util.commands.WrappedCommandException;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.TickSyncDelayLoggerFilter;
@@ -66,10 +62,6 @@ import com.sk89q.worldguard.protection.managers.RegionManager;
* @author sk89q
*/
public class WorldGuardPlugin extends JavaPlugin {
/**
* Logger for messages.
*/
static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
/**
* Manager for commands. This automatically handles nested commands,
@@ -88,14 +80,6 @@ public class WorldGuardPlugin extends JavaPlugin {
*/
private final ConfigurationManager configuration;
/**
* Processes queries for permissions information. The permissions manager
* is from WorldEdit and it automatically handles looking up permissions
* systems and picking the right one. WorldGuard just needs to call
* the permission methods.
*/
private PermissionsResolverManager perms;
/**
* Used for scheduling flags.
*/
@@ -108,7 +92,7 @@ public class WorldGuardPlugin extends JavaPlugin {
public WorldGuardPlugin() {
configuration = new ConfigurationManager(this);
globalRegionManager = new GlobalRegionManager(this);
final WorldGuardPlugin plugin = this;
commands = new CommandsManager<CommandSender>() {
@Override
@@ -116,25 +100,37 @@ public class WorldGuardPlugin extends JavaPlugin {
return plugin.hasPermission(player, perm);
}
};
// Register command classes
commands.register(ToggleCommands.class);
commands.register(ProtectionCommands.class);
commands.register(GeneralCommands.class);
}
/**
* Called on plugin enable.
*/
@SuppressWarnings("deprecation")
public void onEnable() {
// Set the proper command injector
commands.setInjector(new SimpleInjector(this));
// Register command classes
final CommandsManagerRegistration reg = new CommandsManagerRegistration(this, commands);
reg.register(ToggleCommands.class);
reg.register(ProtectionCommands.class);
getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
@Override
public void run() {
if (!getGlobalStateManager().hasCommandBookGodMode()) {
reg.register(GeneralCommands.class);
}
}
}, 0L);
// Need to create the plugins/WorldGuard folder
getDataFolder().mkdirs();
// Set up permissions
perms = new PermissionsResolverManager(this, getDescription().getName(), logger);
perms.load();
PermissionsResolverManager.initialize(this);
// This must be done before configuration is laoded
// This must be done before configuration is loaded
LegacyWorldGuardMigration.migrateBlacklist(this);
// Load the configuration
@@ -167,22 +163,24 @@ public class WorldGuardPlugin extends JavaPlugin {
(new WorldGuardEntityListener(this)).registerEvents();
(new WorldGuardWeatherListener(this)).registerEvents();
(new WorldGuardVehicleListener(this)).registerEvents();
(new WorldGuardServerListener(this)).registerEvents();
// handle worlds separately to initialize already loaded worlds
WorldGuardWorldListener worldListener = (new WorldGuardWorldListener(this));
for (World world : getServer().getWorlds()) {
worldListener.initWorld(world);
}
worldListener.registerEvents();
// Check god mode for existing players, if any
for (Player player : getServer().getOnlinePlayers()) {
if (inGroup(player, "wg-invincible") ||
(configuration.autoGodMode && hasPermission(player, "worldguard.auto-invincible"))) {
configuration.enableGodMode(player);
if (!configuration.hasCommandBookGodMode()) {
// Check god mode for existing players, if any
for (Player player : getServer().getOnlinePlayers()) {
if (inGroup(player, "wg-invincible") ||
(configuration.autoGodMode && hasPermission(player, "worldguard.auto-invincible"))) {
configuration.enableGodMode(player);
}
}
}
logger.info("WorldGuard " + this.getDescription().getVersion() + " enabled.");
}
/**
@@ -192,8 +190,6 @@ public class WorldGuardPlugin extends JavaPlugin {
globalRegionManager.unload();
configuration.unload();
this.getServer().getScheduler().cancelTasks(this);
logger.info("WorldGuard " + getDescription().getVersion() + " disabled.");
}
/**
@@ -203,7 +199,7 @@ public class WorldGuardPlugin extends JavaPlugin {
public boolean onCommand(CommandSender sender, Command cmd, String label,
String[] args) {
try {
commands.execute(cmd.getName(), args, sender, this, sender);
commands.execute(cmd.getName(), args, sender, sender);
} catch (CommandPermissionsException e) {
sender.sendMessage(ChatColor.RED + "You don't have permission.");
} catch (MissingNestedCommandException e) {
@@ -272,7 +268,7 @@ public class WorldGuardPlugin extends JavaPlugin {
*/
public boolean inGroup(Player player, String group) {
try {
return perms.inGroup(player.getName(), group);
return PermissionsResolverManager.getInstance().inGroup(player, group);
} catch (Throwable t) {
t.printStackTrace();
return false;
@@ -287,7 +283,7 @@ public class WorldGuardPlugin extends JavaPlugin {
*/
public String[] getGroups(Player player) {
try {
return perms.getGroups(player.getName());
return PermissionsResolverManager.getInstance().getGroups(player);
} catch (Throwable t) {
t.printStackTrace();
return new String[0];
@@ -345,7 +341,7 @@ public class WorldGuardPlugin extends JavaPlugin {
// Invoke the permissions resolver
if (sender instanceof Player) {
Player player = (Player) sender;
return perms.hasPermission(player.getWorld().getName(), player.getName(), perm);
return PermissionsResolverManager.getInstance().hasPermission(player.getWorld().getName(), player.getName(), perm);
}
return false;
@@ -556,12 +552,7 @@ public class WorldGuardPlugin extends JavaPlugin {
if (filter.equalsIgnoreCase("#console")
|| filter.equalsIgnoreCase("*console*")
|| filter.equalsIgnoreCase("!")) {
try {
return getServer().getConsoleSender();
} catch (Throwable t) {
// Legacy support
return new LegacyConsoleSender(getServer());
}
return getServer().getConsoleSender();
}
return matchSinglePlayer(sender, filter);
@@ -690,11 +681,11 @@ public class WorldGuardPlugin extends JavaPlugin {
null;
try {
JarFile file = new JarFile(getFile());
ZipEntry copy = file.getEntry("defaults" + File.separator + defaultName);
ZipEntry copy = file.getEntry("defaults/" + defaultName);
if (copy == null) throw new FileNotFoundException();
input = file.getInputStream(copy);
} catch (IOException e) {
logger.severe(getDescription().getName() + ": Unable to read default configuration: " + defaultName);
getLogger().severe("Unable to read default configuration: " + defaultName);
}
if (input != null) {
@@ -708,7 +699,7 @@ public class WorldGuardPlugin extends JavaPlugin {
output.write(buf, 0, length);
}
logger.info("WorldGuard: Default configuration file written: "
getLogger().info("Default configuration file written: "
+ actual.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
@@ -0,0 +1,34 @@
package com.sk89q.worldguard.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.PluginManager;
/**
* @author zml2008
*/
public class WorldGuardServerListener implements Listener {
private final WorldGuardPlugin plugin;
public WorldGuardServerListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
public void registerEvents() {
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvents(this, plugin);
}
@EventHandler
public void onPluginEnable(PluginEnableEvent event) {
plugin.getGlobalStateManager().updateCommandBookGodMode();
}
@EventHandler
public void onPluginDisable(PluginDisableEvent event) {
plugin.getGlobalStateManager().updateCommandBookGodMode();
}
}
@@ -10,17 +10,14 @@ import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Vehicle;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.vehicle.VehicleDestroyEvent;
import org.bukkit.event.vehicle.VehicleListener;
import org.bukkit.event.vehicle.VehicleMoveEvent;
import org.bukkit.plugin.PluginManager;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.FlagStateManager.PlayerFlagState;
@@ -29,12 +26,7 @@ import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
public class WorldGuardVehicleListener extends VehicleListener {
/**
* Logger for messages.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
public class WorldGuardVehicleListener implements Listener {
private WorldGuardPlugin plugin;
@@ -51,30 +43,13 @@ public class WorldGuardVehicleListener extends VehicleListener {
* Register events.
*/
public void registerEvents() {
registerEvent("VEHICLE_MOVE", Event.Priority.Normal);
registerEvent("VEHICLE_DESTROY", Event.Priority.Normal);
}
/**
* Register an event, but not failing if the event is not implemented.
*
* @param typeName
* @param priority
*/
private void registerEvent(String typeName, Event.Priority priority) {
try {
Event.Type type = Event.Type.valueOf(typeName);
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvent(type, this, priority, plugin);
} catch (IllegalArgumentException e) {
logger.info("WorldGuard: Unable to register missing event type " + typeName);
}
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
/**
* Called when a vehicle is destroyed.
*/
@Override
@EventHandler
public void onVehicleDestroy(VehicleDestroyEvent event) {
Vehicle vehicle = event.getVehicle();
Entity destroyer = event.getAttacker();
@@ -105,7 +80,7 @@ public class WorldGuardVehicleListener extends VehicleListener {
/**
* Called when a vehicle moves.
*/
@Override
@EventHandler
public void onVehicleMove(VehicleMoveEvent event) {
Vehicle vehicle = event.getVehicle();
if (vehicle.getPassenger() == null
@@ -23,25 +23,18 @@ import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import java.util.logging.Logger;
import org.bukkit.Location;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.weather.LightningStrikeEvent;
import org.bukkit.event.weather.ThunderChangeEvent;
import org.bukkit.event.weather.WeatherChangeEvent;
import org.bukkit.event.weather.WeatherListener;
import org.bukkit.plugin.PluginManager;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
public class WorldGuardWeatherListener extends WeatherListener {
/**
* Logger for messages.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
public class WorldGuardWeatherListener implements Listener {
/**
* Plugin.
@@ -58,30 +51,10 @@ public class WorldGuardWeatherListener extends WeatherListener {
}
public void registerEvents() {
// PluginManager pm = plugin.getServer().getPluginManager();
registerEvent("LIGHTNING_STRIKE", Priority.High);
registerEvent("THUNDER_CHANGE", Priority.High);
registerEvent("WEATHER_CHANGE", Priority.High);
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
/**
* Register an event, but not failing if the event is not implemented.
*
* @param typeName
* @param priority
*/
private void registerEvent(String typeName, Priority priority) {
try {
Event.Type type = Event.Type.valueOf(typeName);
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvent(type, this, priority, plugin);
} catch (IllegalArgumentException e) {
logger.info("WorldGuard: Unable to register missing event type " + typeName);
}
}
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onWeatherChange(WeatherChangeEvent event) {
if (event.isCancelled()) {
return;
@@ -100,7 +73,7 @@ public class WorldGuardWeatherListener extends WeatherListener {
}
}
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onThunderChange(ThunderChangeEvent event) {
if (event.isCancelled()) {
return;
@@ -120,7 +93,7 @@ public class WorldGuardWeatherListener extends WeatherListener {
}
}
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onLightningStrike(LightningStrikeEvent event) {
if (event.isCancelled()) {
return;
@@ -9,18 +9,12 @@ import java.util.logging.Logger;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.event.world.WorldListener;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.plugin.PluginManager;
public class WorldGuardWorldListener extends WorldListener {
/**
* Logger for messages.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
public class WorldGuardWorldListener implements Listener {
private WorldGuardPlugin plugin;
@@ -37,31 +31,13 @@ public class WorldGuardWorldListener extends WorldListener {
* Register events.
*/
public void registerEvents() {
// PluginManager pm = plugin.getServer().getPluginManager();
registerEvent("CHUNK_LOAD", Event.Priority.Normal);
registerEvent("WORLD_LOAD", Event.Priority.Normal);
}
/**
* Register an event, but not failing if the event is not implemented.
*
* @param typeName
* @param priority
*/
private void registerEvent(String typeName, Event.Priority priority) {
try {
Event.Type type = Event.Type.valueOf(typeName);
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvent(type, this, priority, plugin);
} catch (IllegalArgumentException e) {
logger.info("WorldGuard: Unable to register missing event type " + typeName);
}
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
/**
* Called when a chunk is loaded.
*/
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
@@ -76,7 +52,7 @@ public class WorldGuardWorldListener extends WorldListener {
}
if (removed > 50) {
logger.info("WG Halt-Act: " + removed + " entities (>50) auto-removed from "
plugin.getLogger().info("Halt-Act: " + removed + " entities (>50) auto-removed from "
+ event.getChunk().toString());
}
}
@@ -85,6 +61,7 @@ public class WorldGuardWorldListener extends WorldListener {
/**
* Called when a world is loaded.
*/
@EventHandler
public void onWorldLoad(WorldLoadEvent event) {
initWorld(event.getWorld());
}
@@ -33,13 +33,16 @@ import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
public class GeneralCommands {
private final WorldGuardPlugin plugin;
public GeneralCommands(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@Command(aliases = {"god"},
usage = "[player]",
desc = "Enable godmode on a player",
flags = "s", min = 0, max = 1)
public static void god(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
@SuppressWarnings("deprecation")
@Command(aliases = {"god"}, usage = "[player]",
desc = "Enable godmode on a player", flags = "s", max = 1)
public void god(CommandContext args, CommandSender sender) throws CommandException {
ConfigurationManager config = plugin.getGlobalStateManager();
Iterable<Player> targets = null;
@@ -82,12 +85,10 @@ public class GeneralCommands {
}
}
@Command(aliases = {"ungod"},
usage = "[player]",
desc = "Disable godmode on a player",
flags = "s", min = 0, max = 1)
public static void ungod(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
@SuppressWarnings("deprecation")
@Command(aliases = {"ungod"}, usage = "[player]",
desc = "Disable godmode on a player", flags = "s", max = 1)
public void ungod(CommandContext args, CommandSender sender) throws CommandException {
ConfigurationManager config = plugin.getGlobalStateManager();
Iterable<Player> targets = null;
@@ -129,12 +130,8 @@ public class GeneralCommands {
}
}
@Command(aliases = {"heal"},
usage = "[player]",
desc = "Heal a player",
flags = "s", min = 0, max = 1)
public static void heal(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
@Command(aliases = {"heal"}, usage = "[player]", desc = "Heal a player", flags = "s", max = 1)
public void heal(CommandContext args,CommandSender sender) throws CommandException {
Iterable<Player> targets = null;
boolean included = false;
@@ -154,6 +151,7 @@ public class GeneralCommands {
for (Player player : targets) {
player.setHealth(20);
player.setFoodLevel(20);
// Tell the user
if (player.equals(sender)) {
@@ -175,12 +173,8 @@ public class GeneralCommands {
}
}
@Command(aliases = {"slay"},
usage = "[player]",
desc = "Slay a player",
flags = "s", min = 0, max = 1)
public static void slay(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
@Command(aliases = {"slay"}, usage = "[player]", desc = "Slay a player", flags = "s", max = 1)
public void slay(CommandContext args, CommandSender sender) throws CommandException {
Iterable<Player> targets = null;
boolean included = false;
@@ -221,13 +215,9 @@ public class GeneralCommands {
}
}
@Command(aliases = {"locate"},
usage = "[player]",
desc = "Locate a player",
flags = "", min = 0, max = 1)
@Command(aliases = {"locate"}, usage = "[player]", desc = "Locate a player", max = 1)
@CommandPermissions({"worldguard.locate"})
public static void locate(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
public void locate(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
@@ -243,16 +233,13 @@ public class GeneralCommands {
}
}
@Command(aliases = {"stack", ";"},
usage = "",
desc = "Stack items",
flags = "", min = 0, max = 0)
@Command(aliases = {"stack", ";"}, usage = "", desc = "Stack items", max = 0)
@CommandPermissions({"worldguard.stack"})
public static void stack(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
public void stack(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
boolean ignoreMax = plugin.hasPermission(player, "worldguard.stack.illegitimate");
boolean ignoreDamaged = plugin.hasPermission(player, "worldguard.stack.damaged");
ItemStack[] items = player.getInventory().getContents();
int len = items.length;
@@ -286,8 +273,9 @@ public class GeneralCommands {
// Same type?
// Blocks store their color in the damage value
if (item2.getTypeId() == item.getTypeId() &&
(!ItemType.usesDamageValue(item.getTypeId())
|| item.getDurability() == item2.getDurability())) {
((!ItemType.usesDamageValue(item.getTypeId()) && ignoreDamaged)
|| item.getDurability() == item2.getDurability()) &&
item.getEnchantments().equals(item2.getEnchantments())) {
// This stack won't fit in the parent stack
if (item2.getAmount() > needed) {
item.setAmount(64);
@@ -23,22 +23,22 @@ import org.bukkit.command.CommandSender;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.NestedCommand;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
public class ProtectionCommands {
@Command(aliases = {"region"},
desc = "Region management commands")
@NestedCommand({RegionCommands.class, RegionMemberCommands.class})
public static void region(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
@SuppressWarnings("unused")
private final WorldGuardPlugin plugin;
public ProtectionCommands(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@Command(aliases = {"worldguard"},
desc = "WorldGuard commands")
@Command(aliases = {"region", "regions", "rg"}, desc = "Region management commands")
@NestedCommand({RegionCommands.class, RegionMemberCommands.class})
public void region(CommandContext args, CommandSender sender) {}
@Command(aliases = {"worldguard", "wg"}, desc = "WorldGuard commands")
@NestedCommand({WorldGuardCommands.class})
public static void worldGuard(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
}
public void worldGuard(CommandContext args, CommandSender sender) {}
}
+129 -101
View File
@@ -19,8 +19,9 @@
package com.sk89q.worldguard.bukkit.commands;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import org.bukkit.ChatColor;
@@ -53,17 +54,26 @@ import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion.CircularInheritanceException;
import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
import com.sk89q.worldguard.protection.databases.migrators.AbstractDatabaseMigrator;
import com.sk89q.worldguard.protection.databases.migrators.MigrationException;
import com.sk89q.worldguard.protection.databases.migrators.MigratorKey;
import com.sk89q.worldguard.util.RegionUtil;
public class RegionCommands {
private final WorldGuardPlugin plugin;
private MigratorKey migrateDBRequest;
private Date migrateDBRequestDate;
@Command(aliases = {"define", "def", "d"},
usage = "<id> [<owner1> [<owner2> [<owners...>]]]",
desc = "Defines a region",
flags = "", min = 1, max = -1)
public RegionCommands(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@Command(aliases = {"define", "def", "d"}, usage = "<id> [<owner1> [<owner2> [<owners...>]]]",
desc = "Defines a region", min = 1)
@CommandPermissions({"worldguard.region.define"})
public static void define(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
public void define(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
WorldEditPlugin worldEdit = plugin.getWorldEdit();
@@ -116,18 +126,15 @@ public class RegionCommands {
try {
mgr.save();
sender.sendMessage(ChatColor.YELLOW + "Region saved as " + id + ".");
} catch (IOException e) {
throw new CommandException("Failed to write regions file: "
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to write regions: "
+ e.getMessage());
}
}
@Command(aliases = {"redefine", "update", "move"},
usage = "<id>",
desc = "Re-defines the shape of a region",
flags = "", min = 1, max = 1)
public static void redefine(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
@Command(aliases = {"redefine", "update", "move"}, usage = "<id>",
desc = "Re-defines the shape of a region", min = 1, max = 1)
public void redefine(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
@@ -193,19 +200,16 @@ public class RegionCommands {
try {
mgr.save();
} catch (IOException e) {
throw new CommandException("Failed to write regions file: "
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to write regions: "
+ e.getMessage());
}
}
@Command(aliases = {"claim"},
usage = "<id> [<owner1> [<owner2> [<owners...>]]]",
desc = "Claim a region",
flags = "", min = 1, max = -1)
@Command(aliases = {"claim"}, usage = "<id> [<owner1> [<owner2> [<owners...>]]]",
desc = "Claim a region", min = 1)
@CommandPermissions({"worldguard.region.claim"})
public static void claim(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
public void claim(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
LocalPlayer localPlayer = plugin.wrapPlayer(player);
@@ -259,8 +263,9 @@ public class RegionCommands {
if (!plugin.hasPermission(sender, "worldguard.region.unlimited")) {
// Check whether the player has created too many regions
if (wcfg.maxRegionCountPerPlayer >= 0
&& mgr.getRegionCountOfPlayer(localPlayer) >= wcfg.maxRegionCountPerPlayer) {
int maxRegionCount = wcfg.getMaxRegionCount(player);
if (maxRegionCount >= 0
&& mgr.getRegionCountOfPlayer(localPlayer) >= maxRegionCount) {
throw new CommandException("You own too many regions, delete one first to claim a new one.");
}
}
@@ -326,18 +331,15 @@ public class RegionCommands {
try {
mgr.save();
sender.sendMessage(ChatColor.YELLOW + "Region saved as " + id + ".");
} catch (IOException e) {
throw new CommandException("Failed to write regions file: "
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to write regions: "
+ e.getMessage());
}
}
@Command(aliases = {"select", "sel", "s"},
usage = "<id>",
desc = "Load a region as a WorldEdit selection",
flags = "", min = 1, max = 1)
public static void select(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
@Command(aliases = {"select", "sel", "s"}, usage = "<id>",
desc = "Load a region as a WorldEdit selection", min = 1, max = 1)
public void select(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
@@ -381,12 +383,9 @@ public class RegionCommands {
}
}
@Command(aliases = {"info", "i"},
usage = "[world] <id>",
desc = "Get information about a region",
flags = "", min = 1, max = 2)
public static void info(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
@Command(aliases = {"info", "i"}, usage = "[world] <id>",
desc = "Get information about a region", min = 1, max = 2)
public void info(CommandContext args, CommandSender sender) throws CommandException {
Player player = null;
LocalPlayer localPlayer = null;
@@ -468,13 +467,10 @@ public class RegionCommands {
sender.sendMessage(ChatColor.LIGHT_PURPLE + "Bounds: " + c);
}
@Command(aliases = {"list"},
usage = "[.player] [page] [world]",
desc = "Get a list of regions",
flags = "", min = 0, max = 3)
@Command(aliases = {"list"}, usage = "[.player] [page] [world]",
desc = "Get a list of regions", max = 3)
// @CommandPermissions({"worldguard.region.list"})
public static void list(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
public void list(CommandContext args, CommandSender sender) throws CommandException {
World world;
int page = 0;
@@ -559,7 +555,7 @@ public class RegionCommands {
int pages = (int) Math.ceil(size / (float) listSize);
sender.sendMessage(ChatColor.RED
+ (name == "" ? "Regions (page " : "Regions for " + name + " (page ")
+ (name.equals("") ? "Regions (page " : "Regions for " + name + " (page ")
+ (page + 1) + " of " + pages + "):");
if (page < pages) {
@@ -573,12 +569,9 @@ public class RegionCommands {
}
}
@Command(aliases = {"flag", "f"},
usage = "<id> <flag> [value]",
desc = "Set flags",
flags = "", min = 2, max = -1)
public static void flag(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
@Command(aliases = {"flag", "f"}, usage = "<id> <flag> [value]",
desc = "Set flags", min = 2)
public void flag(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
@@ -679,7 +672,7 @@ public class RegionCommands {
if (value != null) {
try {
setFlag(region, foundFlag, plugin, sender, value);
setFlag(region, foundFlag, sender, value);
} catch (InvalidFlagFormat e) {
throw new CommandException(e.getMessage());
}
@@ -696,24 +689,21 @@ public class RegionCommands {
try {
mgr.save();
} catch (IOException e) {
throw new CommandException("Failed to write regions file: "
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to write regions: "
+ e.getMessage());
}
}
public static <V> void setFlag(ProtectedRegion region,
Flag<V> flag, WorldGuardPlugin plugin, CommandSender sender, String value)
public <V> void setFlag(ProtectedRegion region,
Flag<V> flag, CommandSender sender, String value)
throws InvalidFlagFormat {
region.setFlag(flag, flag.parseInput(plugin, sender, value));
}
@Command(aliases = {"setpriority", "priority", "pri"},
usage = "<id> <priority>",
desc = "Set the priority of a region",
flags = "", min = 2, max = 2)
public static void setPriority(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
@Command(aliases = {"setpriority", "priority", "pri"}, usage = "<id> <priority>",
desc = "Set the priority of a region", min = 2, max = 2)
public void setPriority(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
@@ -748,18 +738,15 @@ public class RegionCommands {
try {
mgr.save();
} catch (IOException e) {
throw new CommandException("Failed to write regions file: "
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to write regions: "
+ e.getMessage());
}
}
@Command(aliases = {"setparent", "parent", "par"},
usage = "<id> [parent-id]",
desc = "Set the parent of a region",
flags = "", min = 1, max = 2)
public static void setParent(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
@Command(aliases = {"setparent", "parent", "par"}, usage = "<id> [parent-id]",
desc = "Set the parent of a region", min = 1, max = 2)
public void setParent(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
@@ -822,18 +809,15 @@ public class RegionCommands {
try {
mgr.save();
} catch (IOException e) {
throw new CommandException("Failed to write regions file: "
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to write regions: "
+ e.getMessage());
}
}
@Command(aliases = {"remove", "delete", "del", "rem"},
usage = "<id>",
desc = "Remove a region",
flags = "", min = 1, max = 1)
public static void remove(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
@Command(aliases = {"remove", "delete", "del", "rem"}, usage = "<id>",
desc = "Remove a region", min = 1, max = 1)
public void remove(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
@@ -863,18 +847,15 @@ public class RegionCommands {
try {
mgr.save();
} catch (IOException e) {
throw new CommandException("Failed to write regions file: "
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to write regions: "
+ e.getMessage());
}
}
@Command(aliases = {"load", "reload"},
usage = "[world]",
desc = "Reload regions from file",
flags = "", min = 0, max = 1)
public static void load(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
@Command(aliases = {"load", "reload"}, usage = "[world]",
desc = "Reload regions from file", max = 1)
public void load(CommandContext args, CommandSender sender) throws CommandException {
World world = null;
@@ -889,8 +870,8 @@ public class RegionCommands {
mgr.load();
sender.sendMessage(ChatColor.YELLOW
+ "Regions for '" + world.getName() + "' load.");
} catch (IOException e) {
throw new CommandException("Failed to read regions file: "
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to read regions: "
+ e.getMessage());
}
} else {
@@ -899,8 +880,8 @@ public class RegionCommands {
try {
mgr.load();
} catch (IOException e) {
throw new CommandException("Failed to read regions file: "
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to read regions: "
+ e.getMessage());
}
}
@@ -910,12 +891,9 @@ public class RegionCommands {
}
}
@Command(aliases = {"save", "write"},
usage = "[world]",
desc = "Re-save regions to file",
flags = "", min = 0, max = 1)
public static void save(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
@Command(aliases = {"save", "write"}, usage = "[world]",
desc = "Re-save regions to file", max = 1)
public void save(CommandContext args, CommandSender sender) throws CommandException {
World world = null;
@@ -930,8 +908,8 @@ public class RegionCommands {
mgr.save();
sender.sendMessage(ChatColor.YELLOW
+ "Regions for '" + world.getName() + "' saved.");
} catch (IOException e) {
throw new CommandException("Failed to write regions file: "
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to write regions: "
+ e.getMessage());
}
} else {
@@ -940,8 +918,8 @@ public class RegionCommands {
try {
mgr.save();
} catch (IOException e) {
throw new CommandException("Failed to write regions file: "
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to write regions: "
+ e.getMessage());
}
}
@@ -950,4 +928,54 @@ public class RegionCommands {
+ "Region databases saved.");
}
}
@Command(aliases = {"migratedb"}, usage = "<from> <to>",
desc = "Migrate from one Protection Database to another.", min = 1)
@CommandPermissions({"worldguard.region.migratedb"})
public void migratedb(CommandContext args, CommandSender sender) throws CommandException {
String from = args.getString(0).toLowerCase().trim();
String to = args.getString(1).toLowerCase().trim();
if (from.equals(to)) {
throw new CommandException("Will not migrate with common source and target.");
}
Map<MigratorKey, Class<? extends AbstractDatabaseMigrator>> migrators = AbstractDatabaseMigrator.getMigrators();
MigratorKey key = new MigratorKey(from,to);
if (!migrators.containsKey(key)) {
throw new CommandException("No migrator found for that combination and direction.");
}
long lastRequest = 10000000;
if (this.migrateDBRequestDate != null) {
lastRequest = new Date().getTime() - this.migrateDBRequestDate.getTime();
}
if (this.migrateDBRequest == null || lastRequest > 60000) {
this.migrateDBRequest = key;
this.migrateDBRequestDate = new Date();
throw new CommandException("This command is potentially dangerous.\n" +
"Please ensure you have made a backup of your data, and then re-enter the command exactly to procede.");
}
Class<? extends AbstractDatabaseMigrator> cls = migrators.get(key);
try {
AbstractDatabaseMigrator migrator = cls.getConstructor(WorldGuardPlugin.class).newInstance(plugin);
migrator.migrate();
} catch (IllegalArgumentException e) {
} catch (SecurityException e) {
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
} catch (NoSuchMethodException e) {
} catch (MigrationException e) {
throw new CommandException("Error migrating database: " + e.getMessage());
}
sender.sendMessage(ChatColor.YELLOW + "Regions have been migrated successfuly.\n" +
"If you wish to use the destination format as your new backend, please update your config and reload WorldGuard.");
}
}
@@ -19,8 +19,6 @@
package com.sk89q.worldguard.bukkit.commands;
import java.io.IOException;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
@@ -31,20 +29,25 @@ import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
import com.sk89q.worldguard.util.RegionUtil;
// @TODO: A lot of code duplication here! Need to fix.
public class RegionMemberCommands {
private final WorldGuardPlugin plugin;
public RegionMemberCommands(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@Command(aliases = {"addmember", "addmember"},
usage = "<id> <members...>",
desc = "Add a member to a region",
flags = "", min = 2, max = -1)
public static void addMember(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
@Command(aliases = {"addmember", "addmember"}, usage = "<id> <members...>",
desc = "Add a member to a region", min = 2)
public void addMember(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
@@ -74,18 +77,15 @@ public class RegionMemberCommands {
try {
mgr.save();
} catch (IOException e) {
throw new CommandException("Failed to write regions file: "
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to write regions: "
+ e.getMessage());
}
}
@Command(aliases = {"addowner", "addowner"},
usage = "<id> <owners...>",
desc = "Add an owner to a region",
flags = "", min = 2, max = -1)
public static void addOwner(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
@Command(aliases = {"addowner", "addowner"}, usage = "<id> <owners...>",
desc = "Add an owner to a region", min = 2)
public void addOwner(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
@@ -99,13 +99,26 @@ public class RegionMemberCommands {
if (region == null) {
throw new CommandException("Could not find a region by that ID.");
}
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.addowner.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.addowner.member." + id.toLowerCase());
Boolean flag = region.getFlag(DefaultFlag.BUYABLE);
DefaultDomain owners = region.getOwners();
if (flag != null && flag == true && owners != null && owners.size() == 0) {
if (!plugin.hasPermission(player, "worldguard.region.unlimited")) {
int maxRegionCount = plugin.getGlobalStateManager().get(world).getMaxRegionCount(player);
if (maxRegionCount >= 0 && mgr.getRegionCountOfPlayer(localPlayer)
>= maxRegionCount) {
throw new CommandException("You already own the maximum allowed amount of regions.");
}
}
plugin.checkPermission(sender, "worldguard.region.addowner.unclaimed." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.addowner." + id.toLowerCase());
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.addowner.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.addowner.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.addowner." + id.toLowerCase());
}
}
RegionUtil.addToDomain(region.getOwners(), args.getPaddedSlice(2, 0), 0);
@@ -115,18 +128,15 @@ public class RegionMemberCommands {
try {
mgr.save();
} catch (IOException e) {
throw new CommandException("Failed to write regions file: "
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to write regions: "
+ e.getMessage());
}
}
@Command(aliases = {"removemember", "remmember", "removemem", "remmem"},
usage = "<id> <owners...>",
desc = "Remove an owner to a region",
flags = "", min = 2, max = -1)
public static void removeMember(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
@Command(aliases = {"removemember", "remmember", "removemem", "remmem"}, usage = "<id> <owners...>",
desc = "Remove an owner to a region", min = 2)
public void removeMember(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
@@ -156,17 +166,15 @@ public class RegionMemberCommands {
try {
mgr.save();
} catch (IOException e) {
throw new CommandException("Failed to write regions file: "
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to write regions: "
+ e.getMessage());
}
}
@Command(aliases = {"removeowner", "remowner"},
usage = "<id> <owners...>",
desc = "Remove an owner to a region",
flags = "", min = 2, max = -1)
public static void removeOwner(CommandContext args, WorldGuardPlugin plugin,
@Command(aliases = {"removeowner", "remowner"}, usage = "<id> <owners...>",
desc = "Remove an owner to a region", min = 2)
public void removeOwner(CommandContext args,
CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
@@ -197,8 +205,8 @@ public class RegionMemberCommands {
try {
mgr.save();
} catch (IOException e) {
throw new CommandException("Failed to write regions file: "
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to write regions: "
+ e.getMessage());
}
}
@@ -35,13 +35,16 @@ import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
public class ToggleCommands {
private final WorldGuardPlugin plugin;
@Command(aliases = {"stopfire"},
usage = "[<world>]", desc = "Disables all fire spread temporarily",
flags = "", min = 0, max = 1)
public ToggleCommands(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@Command(aliases = {"stopfire"}, usage = "[<world>]",
desc = "Disables all fire spread temporarily", max = 1)
@CommandPermissions({"worldguard.fire-toggle.stop"})
public static void stopFire(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
public void stopFire(CommandContext args, CommandSender sender) throws CommandException {
World world;
@@ -67,12 +70,10 @@ public class ToggleCommands {
wcfg.fireSpreadDisableToggle = true;
}
@Command(aliases = {"allowfire"},
usage = "[<world>]", desc = "Allows all fire spread temporarily",
flags = "", min = 0, max = 1)
@Command(aliases = {"allowfire"}, usage = "[<world>]",
desc = "Allows all fire spread temporarily", max = 1)
@CommandPermissions({"worldguard.fire-toggle.stop"})
public static void allowFire(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
public void allowFire(CommandContext args, CommandSender sender) throws CommandException {
World world;
@@ -96,12 +97,10 @@ public class ToggleCommands {
wcfg.fireSpreadDisableToggle = false;
}
@Command(aliases = {"halt-activity"},
usage = "", desc = "Attempts to cease as much activity in order to stop lag",
flags = "c", min = 0, max = 0)
@Command(aliases = {"halt-activity", "stoplag", "haltactivity"},
desc = "Attempts to cease as much activity in order to stop lag", flags = "c", max = 0)
@CommandPermissions({"worldguard.halt-activity"})
public static void stopLag(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
public void stopLag(CommandContext args, CommandSender sender) throws CommandException {
ConfigurationManager configManager = plugin.getGlobalStateManager();
@@ -39,26 +39,23 @@ import com.sk89q.worldguard.util.PastebinPoster;
import com.sk89q.worldguard.util.PastebinPoster.PasteCallback;
public class WorldGuardCommands {
private final WorldGuardPlugin plugin;
@Command(aliases = {"version"},
usage = "",
desc = "Get the WorldGuard version",
flags = "", min = 0, max = 0)
public static void version(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
public WorldGuardCommands(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@Command(aliases = {"version"}, desc = "Get the WorldGuard version", max = 0)
public void version(CommandContext args, CommandSender sender) throws CommandException {
sender.sendMessage(ChatColor.YELLOW
+ "WorldGuard " + plugin.getDescription().getVersion());
sender.sendMessage(ChatColor.YELLOW
+ "http://www.sk89q.com");
}
@Command(aliases = {"reload"},
usage = "",
desc = "Reload WorldGuard configuration",
flags = "", min = 0, max = 0)
@Command(aliases = {"reload"}, desc = "Reload WorldGuard configuration", max = 0)
@CommandPermissions({"worldguard.reload"})
public static void relload(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
public void reload(CommandContext args, CommandSender sender) throws CommandException {
LoggerToChatHandler handler = null;
Logger minecraftLogger = null;
@@ -86,13 +83,9 @@ public class WorldGuardCommands {
}
}
@Command(aliases = {"report"},
usage = "",
desc = "Writes a report on WorldGuard",
flags = "p", min = 0, max = 0)
@Command(aliases = {"report"}, desc = "Writes a report on WorldGuard", flags = "p", max = 0)
@CommandPermissions({"worldguard.report"})
public static void report(CommandContext args, WorldGuardPlugin plugin,
final CommandSender sender) throws CommandException {
public void report(CommandContext args, final CommandSender sender) throws CommandException {
File dest = new File(plugin.getDataFolder(), "report.txt");
ReportWriter report = new ReportWriter(plugin);
@@ -126,12 +119,9 @@ public class WorldGuardCommands {
}
@Command(aliases = {"flushstates", "clearstates"},
usage = "[player]",
desc = "Flush the state manager",
flags = "", min = 0, max = 1)
usage = "[player]", desc = "Flush the state manager", max = 1)
@CommandPermissions("worldguard.flushstates")
public static void flushStates(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
public void flushStates(CommandContext args, CommandSender sender) throws CommandException {
if (args.argsLength() == 0) {
plugin.getFlagStateManager().forgetAll();
sender.sendMessage("Cleared all states.");
@@ -62,6 +62,15 @@ public interface ChestProtection {
* @param material
* @return
*/
@Deprecated
public boolean isChest(Material material);
/**
* Returns whether a material is a chest.
*
* @param type
* @return
*/
public boolean isChest(int type);
}
@@ -19,6 +19,7 @@
package com.sk89q.worldguard.chest;
import com.sk89q.worldedit.blocks.BlockID;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
@@ -33,10 +34,10 @@ import org.bukkit.entity.Player;
public class SignChestProtection implements ChestProtection {
public boolean isProtected(Block block, Player player) {
if (isChest(block.getType())) {
if (isChest(block.getTypeId())) {
Block below = block.getRelative(0, -1, 0);
return isProtectedSignAround(below, player);
} else if (block.getType() == Material.SIGN_POST) {
} else if (block.getTypeId() == BlockID.SIGN_POST) {
return isProtectedSignAndChestBinary(block, player);
} else {
Block above = block.getRelative(0, 1, 0);
@@ -56,23 +57,23 @@ public class SignChestProtection implements ChestProtection {
side = searchBlock;
res = isProtectedSign(side, player);
if (res != null && res == true) return res;
if (res != null && res) return res;
side = searchBlock.getRelative(-1, 0, 0);
res = isProtectedSignAndChest(side, player);
if (res != null && res == true) return res;
if (res != null && res) return res;
side = searchBlock.getRelative(1, 0, 0);
res = isProtectedSignAndChest(side, player);
if (res != null && res == true) return res;
if (res != null && res) return res;
side = searchBlock.getRelative(0, 0, -1);
res = isProtectedSignAndChest(side, player);
if (res != null && res == true) return res;
if (res != null && res) return res;
side = searchBlock.getRelative(0, 0, 1);
res = isProtectedSignAndChest(side, player);
if (res != null && res == true) return res;
if (res != null && res) return res;
return false;
}
@@ -106,7 +107,7 @@ public class SignChestProtection implements ChestProtection {
}
private Boolean isProtectedSignAndChest(Block block, Player player) {
if (!isChest(block.getRelative(0, 1, 0).getType())) {
if (!isChest(block.getRelative(0, 1, 0).getTypeId())) {
return null;
}
return isProtectedSign(block, player);
@@ -114,7 +115,7 @@ public class SignChestProtection implements ChestProtection {
private boolean isProtectedSignAndChestBinary(Block block, Player player) {
Boolean res = isProtectedSignAndChest(block, player);
if (res == null || res == false) {
if (res == null || !res) {
return false;
}
return true;
@@ -146,11 +147,16 @@ public class SignChestProtection implements ChestProtection {
return false;
}
@Deprecated
public boolean isChest(Material material) {
return material == Material.CHEST
|| material == Material.DISPENSER
|| material == Material.FURNACE
|| material == Material.BURNING_FURNACE;
return isChest(material.getId());
}
public boolean isChest(int type) {
return type == BlockID.CHEST
|| type == BlockID.DISPENSER
|| type == BlockID.FURNACE
|| type == BlockID.BURNING_FURNACE;
}
}
@@ -21,8 +21,6 @@ package com.sk89q.worldguard.protection;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.logging.Logger;
@@ -36,7 +34,10 @@ import com.sk89q.worldguard.bukkit.BukkitUtil;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
import com.sk89q.worldguard.protection.databases.ProtectionDatabase;
import com.sk89q.worldguard.protection.databases.YAMLDatabase;
import com.sk89q.worldguard.protection.databases.MySQLDatabase;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.managers.FlatRegionManager;
import com.sk89q.worldguard.protection.managers.RegionManager;
@@ -50,8 +51,6 @@ import com.sk89q.worldguard.protection.managers.RegionManager;
*/
public class GlobalRegionManager {
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
/**
* Reference to the plugin.
*/
@@ -134,33 +133,47 @@ public class GlobalRegionManager {
*/
public RegionManager load(World world) {
String name = world.getName();
File file = getPath(name);
ProtectionDatabase database = null;
File file = null;
try {
if (!config.useSqlDatabase) {
file = getPath(name);
database = new YAMLDatabase(file, plugin.getLogger());
// Store the last modification date so we can track changes
lastModified.put(name, file.lastModified());
} else {
database = new MySQLDatabase(config, name, plugin.getLogger());
}
// Create a manager
RegionManager manager = new FlatRegionManager(new YAMLDatabase(file));
RegionManager manager = new FlatRegionManager(database);
managers.put(name, manager);
manager.load();
logger.info("WorldGuard: " + manager.getRegions().size()
plugin.getLogger().info(manager.getRegions().size()
+ " regions loaded for '" + name + "'");
// Store the last modification date so we can track changes
lastModified.put(name, file.lastModified());
return manager;
} catch (FileNotFoundException e) {
logger.warning("WorldGuard: Region file for world \""
+ name + "\" missing or inaccessible.");
} catch (IOException e) {
logger.warning("WorldGuard: Failed to load regions from file "
+ file.getAbsolutePath() + " : " + e.getMessage());
} catch (ProtectionDatabaseException e) {
String logStr = "Failed to load regions from ";
if (config.useSqlDatabase) {
logStr += "SQL Database <" + config.sqlDsn + "> ";
} else {
logStr += "file \"" + file + "\" ";
}
plugin.getLogger().info(logStr + " : " + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
logger.warning("WorldGuard: Error loading regions for world \""
+ name + "\":" + e.getMessage());
plugin.getLogger().info("Error loading regions for world \""
+ name + "\": " + e.toString() + "\n\t" + e.getMessage());
e.printStackTrace();
}
// @TODO: THIS CREATES PROBLEMS!!
// @TODO: THIS CREATES PROBLEMS!!one!!1!!eleven!!1!!!
return null;
}
@@ -179,6 +192,8 @@ public class GlobalRegionManager {
* have changed.
*/
public void reloadChanged() {
if (config.useSqlDatabase) return;
for (String name : managers.keySet()) {
File file = getPath(name);
@@ -19,8 +19,6 @@
package com.sk89q.worldguard.protection.databases;
import java.io.IOException;
import com.sk89q.worldguard.protection.managers.RegionManager;
public abstract class AbstractProtectionDatabase implements ProtectionDatabase {
@@ -28,9 +26,9 @@ public abstract class AbstractProtectionDatabase implements ProtectionDatabase {
/**
* Load the list of regions into a region manager.
*
* @throws IOException
* @throws ProtectionDatabaseException
*/
public void load(RegionManager manager) throws IOException {
public void load(RegionManager manager) throws ProtectionDatabaseException {
load();
manager.setRegions(getRegions());
}
@@ -38,9 +36,9 @@ public abstract class AbstractProtectionDatabase implements ProtectionDatabase {
/**
* Save the list of regions from a region manager.
*
* @throws IOException
* @throws ProtectionDatabaseException
*/
public void save(RegionManager manager) throws IOException {
public void save(RegionManager manager) throws ProtectionDatabaseException {
setRegions(manager.getRegions());
save();
}
@@ -48,12 +48,12 @@ import com.sk89q.worldguard.util.ArrayReader;
* @author sk89q
*/
public class CSVDatabase extends AbstractProtectionDatabase {
private static Logger logger = Logger.getLogger("Minecraft.WorldGuard");
private final Logger logger;
/**
* References the CSV file.
*/
private File file;
private final File file;
/**
* Holds the list of regions.
*/
@@ -65,29 +65,31 @@ public class CSVDatabase extends AbstractProtectionDatabase {
*
* @param file
*/
public CSVDatabase(File file) {
public CSVDatabase(File file, Logger logger) {
this.file = file;
this.logger = logger;
}
/**
* Saves the database.
*/
public void save() throws IOException {
public void save() throws ProtectionDatabaseException {
throw new UnsupportedOperationException("CSV format is no longer implemented");
}
/**
* Load the database from file.
*/
public void load() throws IOException {
public void load() throws ProtectionDatabaseException {
Map<String,ProtectedRegion> regions =
new HashMap<String,ProtectedRegion>();
Map<ProtectedRegion,String> parentSets =
new LinkedHashMap<ProtectedRegion, String>();
CSVReader reader = new CSVReader(new FileReader(file));
CSVReader reader = null;
try {
reader = new CSVReader(new FileReader(file));
String[] line;
while ((line = reader.readNext()) != null) {
@@ -162,6 +164,8 @@ public class CSVDatabase extends AbstractProtectionDatabase {
}
}
}
} catch (IOException e) {
throw new ProtectionDatabaseException(e);
} finally {
try {
reader.close();
@@ -0,0 +1,969 @@
// $Id$
/*
* MySQL WordGuard Region Database
* Copyright (C) 2011 Nicholas Steicke <http://narthollis.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection.databases;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.BlockVector2D;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.regions.GlobalProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion.CircularInheritanceException;
public class MySQLDatabase extends AbstractProtectionDatabase {
private final Logger logger;
private Map<String, ProtectedRegion> regions;
private Map<String, ProtectedRegion> cuboidRegions;
private Map<String, ProtectedRegion> poly2dRegions;
private Map<String, ProtectedRegion> globalRegions;
private Map<ProtectedRegion, String> parentSets;
private final ConfigurationManager config;
private Connection conn;
private String world;
private int worldDbId = -1; // The database will never have an id of -1;
public MySQLDatabase(ConfigurationManager config, String world, Logger logger) throws ProtectionDatabaseException {
this.config = config;
this.world = world;
this.logger = logger;
try {
connect();
PreparedStatement worldStmt = conn.prepareStatement(
"SELECT `id` FROM " +
"`world` " +
"WHERE `name` = ? LIMIT 0,1"
);
worldStmt.setString(1, this.world);
ResultSet worldResult = worldStmt.executeQuery();
if (worldResult.first()) {
this.worldDbId = worldResult.getInt("id");
} else {
PreparedStatement insertWorldStatement = this.conn.prepareStatement(
"INSERT INTO " +
"`world` " +
"(`id`, `name`) VALUES (null, ?)",
Statement.RETURN_GENERATED_KEYS
);
insertWorldStatement.setString(1, world);
insertWorldStatement.execute();
ResultSet generatedKeys = insertWorldStatement.getGeneratedKeys();
if (generatedKeys.first()) {
this.worldDbId = generatedKeys.getInt(1);
}
}
} catch (SQLException ex) {
logger.log(Level.SEVERE, ex.getMessage(), ex);
// We havn't connected to the databases, or there was an error
// initialising the world record, so there is no point continuing
return;
}
if (this.worldDbId <= 0) {
logger.log(Level.SEVERE, "Could not find or create the world");
// There was an error initialising the world record, so there is
// no point continuing
return;
}
}
private void connect() throws SQLException {
if (conn == null || conn.isClosed()) {
conn = DriverManager.getConnection(config.sqlDsn, config.sqlUsername, config.sqlPassword);
}
}
private void loadFlags(ProtectedRegion region) {
// @TODO: Iterate _ONCE_
try {
PreparedStatement flagsStatement = this.conn.prepareStatement(
"SELECT " +
"`region_flag`.`flag`, " +
"`region_flag`.`value` " +
"FROM `region_flag` " +
"WHERE `region_flag`.`region_id` = ? "
);
flagsStatement.setString(1, region.getId().toLowerCase());
ResultSet flagsResultSet = flagsStatement.executeQuery();
Map<String,Object> regionFlags = new HashMap<String,Object>();
while (flagsResultSet.next()) {
regionFlags.put(
flagsResultSet.getString("flag"),
flagsResultSet.getObject("value")
);
}
// @TODO: Make this better
for (Flag<?> flag : DefaultFlag.getFlags()) {
Object o = regionFlags.get(flag.getName());
if (o != null) {
setFlag(region, flag, o);
}
}
} catch (SQLException ex) {
logger.warning(
"Unable to load flags for region "
+ region.getId().toLowerCase() + ": " + ex.getMessage()
);
}
}
private <T> void setFlag(ProtectedRegion region, Flag<T> flag, Object rawValue) {
T val = flag.unmarshal(rawValue);
if (val == null) {
logger.warning("Failed to parse flag '" + flag.getName()
+ "' with value '" + rawValue.toString() + "'");
return;
}
region.setFlag(flag, val);
}
private void loadOwnersAndMembers(ProtectedRegion region) {
DefaultDomain owners = new DefaultDomain();
DefaultDomain members = new DefaultDomain();
try {
PreparedStatement usersStatement = this.conn.prepareStatement(
"SELECT " +
"`user`.`name`, " +
"`region_players`.`owner` " +
"FROM `region_players` " +
"LEFT JOIN `user` ON ( " +
"`region_players`.`user_id` = " +
"`user`.`id`) " +
"WHERE `region_players`.`region_id` = ? "
);
usersStatement.setString(1, region.getId().toLowerCase());
ResultSet userSet = usersStatement.executeQuery();
while(userSet.next()) {
if (userSet.getBoolean("owner")) {
owners.addPlayer(userSet.getString("name"));
} else {
members.addPlayer(userSet.getString("name"));
}
}
} catch (SQLException ex) {
logger.warning("Unable to load users for region " + region.getId().toLowerCase() + ": " + ex.getMessage());
}
try {
PreparedStatement groupsStatement = this.conn.prepareStatement(
"SELECT " +
"`group`.`name`, " +
"`region_groups`.`owner` " +
"FROM `region_groups` " +
"LEFT JOIN `group` ON ( " +
"`region_groups`.`group_id` = " +
"`group`.`id`) " +
"WHERE `region_groups`.`region_id` = ? "
);
groupsStatement.setString(1, region.getId().toLowerCase());
ResultSet groupSet = groupsStatement.executeQuery();
while(groupSet.next()) {
if (groupSet.getBoolean("owner")) {
owners.addGroup(groupSet.getString("name"));
} else {
members.addGroup(groupSet.getString("name"));
}
}
} catch (SQLException ex) {
logger.warning("Unable to load groups for region " + region.getId().toLowerCase() + ": " + ex.getMessage());
}
region.setOwners(owners);
region.setMembers(members);
}
private void loadGlobal() {
Map<String,ProtectedRegion> regions =
new HashMap<String,ProtectedRegion>();
try {
PreparedStatement globalRegionStatement = this.conn.prepareStatement(
"SELECT " +
"`region`.`id`, " +
"`region`.`priority`, " +
"`parent`.`id` AS `parent` " +
"FROM `region` " +
"LEFT JOIN `region` AS `parent` " +
"ON (`region`.`parent` = `parent`.`id`) " +
"WHERE `region`.`type` = 'global' " +
"AND `region`.`world_id` = ? "
);
globalRegionStatement.setInt(1, this.worldDbId);
ResultSet globalResultSet = globalRegionStatement.executeQuery();
while (globalResultSet.next()) {
ProtectedRegion region = new GlobalProtectedRegion(globalResultSet.getString("id"));
region.setPriority(globalResultSet.getInt("priority"));
this.loadFlags(region);
this.loadOwnersAndMembers(region);
regions.put(globalResultSet.getString("id"), region);
String parentId = globalResultSet.getString("parent");
if (parentId != null) {
parentSets.put(region, parentId);
}
}
} catch (SQLException ex) {
ex.printStackTrace();
logger.warning("Unable to load regions from sql database: " + ex.getMessage());
Throwable t = ex.getCause();
while (t != null) {
logger.warning("\t\tCause: " + t.getMessage());
t = t.getCause();
}
}
globalRegions = regions;
}
private void loadCuboid() {
Map<String,ProtectedRegion> regions =
new HashMap<String,ProtectedRegion>();
try {
PreparedStatement cuboidRegionStatement = this.conn.prepareStatement(
"SELECT " +
"`region_cuboid`.`min_z`, " +
"`region_cuboid`.`min_y`, " +
"`region_cuboid`.`min_x`, " +
"`region_cuboid`.`max_z`, " +
"`region_cuboid`.`max_y`, " +
"`region_cuboid`.`max_x`, " +
"`region`.`id`, " +
"`region`.`priority`, " +
"`parent`.`id` AS `parent` " +
"FROM `region_cuboid` " +
"LEFT JOIN `region` " +
"ON (`region_cuboid`.`region_id` = `region`.`id`) " +
"LEFT JOIN `region` AS `parent` " +
"ON (`region`.`parent` = `parent`.`id`) " +
"WHERE `region`.`world_id` = ? "
);
cuboidRegionStatement.setInt(1, this.worldDbId);
ResultSet cuboidResultSet = cuboidRegionStatement.executeQuery();
while (cuboidResultSet.next()) {
Vector pt1 = new Vector(
cuboidResultSet.getInt("min_x"),
cuboidResultSet.getInt("min_y"),
cuboidResultSet.getInt("min_z")
);
Vector pt2 = new Vector(
cuboidResultSet.getInt("max_x"),
cuboidResultSet.getInt("max_y"),
cuboidResultSet.getInt("max_z")
);
BlockVector min = Vector.getMinimum(pt1, pt2).toBlockVector();
BlockVector max = Vector.getMaximum(pt1, pt2).toBlockVector();
ProtectedRegion region = new ProtectedCuboidRegion(
cuboidResultSet.getString("id"),
min,
max
);
region.setPriority(cuboidResultSet.getInt("priority"));
this.loadFlags(region);
this.loadOwnersAndMembers(region);
regions.put(cuboidResultSet.getString("id"), region);
String parentId = cuboidResultSet.getString("parent");
if (parentId != null) {
parentSets.put(region, parentId);
}
}
} catch (SQLException ex) {
ex.printStackTrace();
logger.warning("Unable to load regions from sql database: " + ex.getMessage());
Throwable t = ex.getCause();
while (t != null) {
logger.warning("\t\tCause: " + t.getMessage());
t = t.getCause();
}
}
cuboidRegions = regions;
}
private void loadPoly2d() {
Map<String,ProtectedRegion> regions =
new HashMap<String,ProtectedRegion>();
try {
PreparedStatement poly2dRegionStatement = this.conn.prepareStatement(
"SELECT " +
"`region_poly2d`.`min_y`, " +
"`region_poly2d`.`max_y`, " +
"`region`.`id`, " +
"`region`.`priority`, " +
"`parent`.`id` AS `parent` " +
"FROM `region_poly2d` " +
"LEFT JOIN `region` " +
"ON (`region_poly2d`.`region_id` = `region`.`id`) " +
"LEFT JOIN `region` AS `parent` " +
"ON (`region`.`parent` = `parent`.`id`) " +
"WHERE `region`.`world_id` = ? "
);
poly2dRegionStatement.setInt(1, this.worldDbId);
ResultSet poly2dResultSet = poly2dRegionStatement.executeQuery();
PreparedStatement poly2dVectorStatement = this.conn.prepareStatement(
"SELECT " +
"`region_poly2d_point`.`x`, " +
"`region_poly2d_point`.`z` " +
"FROM `region_poly2d_point` " +
"WHERE `region_poly2d_point`.`region_id` = ? "
);
while (poly2dResultSet.next()) {
String id = poly2dResultSet.getString("id");
Integer minY = poly2dResultSet.getInt("min_y");
Integer maxY = poly2dResultSet.getInt("max_y");
List<BlockVector2D> points = new ArrayList<BlockVector2D>();
poly2dVectorStatement.setString(1, id);
ResultSet poly2dVectorResultSet = poly2dVectorStatement.executeQuery();
while(poly2dVectorResultSet.next()) {
points.add(new BlockVector2D(
poly2dVectorResultSet.getInt("x"),
poly2dVectorResultSet.getInt("z")
));
}
ProtectedRegion region = new ProtectedPolygonalRegion(id, points, minY, maxY);
region.setPriority(poly2dResultSet.getInt("priority"));
this.loadFlags(region);
this.loadOwnersAndMembers(region);
regions.put(poly2dResultSet.getString("id"), region);
String parentId = poly2dResultSet.getString("parent");
if (parentId != null) {
parentSets.put(region, parentId);
}
}
} catch (SQLException ex) {
ex.printStackTrace();
logger.warning("Unable to load regions from sql database: " + ex.getMessage());
Throwable t = ex.getCause();
while (t != null) {
logger.warning("\t\tCause: " + t.getMessage());
t = t.getCause();
}
}
poly2dRegions = regions;
}
public void load() throws ProtectionDatabaseException {
try {
connect();
} catch (SQLException ex) {
throw new ProtectionDatabaseException(ex);
}
parentSets = new HashMap<ProtectedRegion,String>();
// We load the cuboid regions first, as this is likely to be the
// largest dataset. This should save time in regards to the putAll()s
this.loadCuboid();
Map<String,ProtectedRegion> regions = this.cuboidRegions;
this.cuboidRegions = null;
this.loadPoly2d();
regions.putAll(this.poly2dRegions);
this.poly2dRegions = null;
this.loadGlobal();
regions.putAll(this.globalRegions);
this.globalRegions = null;
// Relink parents // Taken verbatim from YAMLDatabase
for (Map.Entry<ProtectedRegion, String> entry : parentSets.entrySet()) {
ProtectedRegion parent = regions.get(entry.getValue());
if (parent != null) {
try {
entry.getKey().setParent(parent);
} catch (CircularInheritanceException e) {
logger.warning("Circular inheritance detect with '"
+ entry.getValue() + "' detected as a parent");
}
} else {
logger.warning("Unknown region parent: " + entry.getValue());
}
}
this.regions = regions;
}
/*
* Returns the database id for the user
* If it doesn't exits it adds the user and returns the id.
*/
private Map<String,Integer> getUserIds(String... usernames) {
Map<String,Integer> users = new HashMap<String,Integer>();
if (usernames.length < 1) return users;
try {
PreparedStatement findUsersStatement = this.conn.prepareStatement(
String.format(
"SELECT " +
"`user`.`id`, " +
"`user`.`name` " +
"FROM `user` " +
"WHERE `name` IN (%s)",
RegionDBUtil.preparePlaceHolders(usernames.length)
)
);
RegionDBUtil.setValues(findUsersStatement, usernames);
ResultSet findUsersResults = findUsersStatement.executeQuery();
while(findUsersResults.next()) {
users.put(findUsersResults.getString("name"), findUsersResults.getInt("id"));
}
PreparedStatement insertUserStatement = this.conn.prepareStatement(
"INSERT INTO " +
"`user` ( " +
"`id`, " +
"`name`" +
") VALUES (null, ?)",
Statement.RETURN_GENERATED_KEYS
);
for(int i=0, len=usernames.length; i<len; i++) {
if (!users.containsKey(usernames[i])) {
insertUserStatement.setString(1, usernames[i]);
insertUserStatement.execute();
ResultSet generatedKeys = insertUserStatement.getGeneratedKeys();
if (generatedKeys.first()) {
users.put(usernames[i], generatedKeys.getInt(1));
} else {
logger.warning("Could not get the database id for user " + usernames[i]);
}
}
}
} catch (SQLException ex) {
ex.printStackTrace();
logger.warning("Could not get the database id for the users " + usernames.toString() + "\n\t" + ex.getMessage());
Throwable t = ex.getCause();
while (t != null) {
logger.warning(t.getMessage());
t = t.getCause();
}
}
return users;
}
/*
* Returns the database id for the groups
* If it doesn't exits it adds the group and returns the id.
*/
private Map<String,Integer> getGroupIds(String... groupnames) {
Map<String,Integer> groups = new HashMap<String,Integer>();
if (groupnames.length < 1) return groups;
try {
PreparedStatement findGroupsStatement = this.conn.prepareStatement(
String.format(
"SELECT " +
"`group`.`id`, " +
"`group`.`name` " +
"FROM `group` " +
"WHERE `name` IN (%s)",
RegionDBUtil.preparePlaceHolders(groupnames.length)
)
);
RegionDBUtil.setValues(findGroupsStatement, groupnames);
ResultSet findGroupsResults = findGroupsStatement.executeQuery();
while(findGroupsResults.next()) {
groups.put(findGroupsResults.getString("name"), findGroupsResults.getInt("id"));
}
PreparedStatement insertGroupStatement = this.conn.prepareStatement(
"INSERT INTO " +
"`group` ( " +
"`id`, " +
"`name`" +
") VALUES (null, ?)",
Statement.RETURN_GENERATED_KEYS
);
for(int i=0, len=groupnames.length; i<len; i++) {
if (!groups.containsKey(groupnames[i])) {
insertGroupStatement.setString(1, groupnames[i]);
insertGroupStatement.execute();
ResultSet generatedKeys = insertGroupStatement.getGeneratedKeys();
if (generatedKeys.first()) {
groups.put(groupnames[i], generatedKeys.getInt(1));
} else {
logger.warning("Could not get the database id for user " + groupnames[i]);
}
}
}
} catch (SQLException ex) {
logger.warning("Could not get the database id for the groups " + groupnames.toString() + ex.getMessage());
}
return groups;
}
/*
* As we don't get notified on the creation/removal of regions:
* 1) We get a list of all of the in-database regions
* 2) We iterate over all of the in-memory regions
* 2a) If the region is in the database, we update the database and
* remove the region from the in-database list
* b) If the region is not in the database, we insert it
* 3) We iterate over what remains of the in-database list and remove
* them from the database
*
* TODO: Look at adding/removing/updating the database when the in
* memory region is created/remove/updated
*
* @see com.sk89q.worldguard.protection.databases.ProtectionDatabase#save()
*/
public void save() throws ProtectionDatabaseException {
try {
connect();
} catch (SQLException ex) {
throw new ProtectionDatabaseException(ex);
}
List<String> regionsInDatabase = new ArrayList<String>();
try {
PreparedStatement getAllRegionsStatement = this.conn.prepareStatement(
"SELECT `region`.`id` FROM " +
"`region` " +
"WHERE `world_id` = ? "
);
getAllRegionsStatement.setInt(1, this.worldDbId);
ResultSet getAllRegionsResult = getAllRegionsStatement.executeQuery();
while(getAllRegionsResult.next()) {
regionsInDatabase.add(getAllRegionsResult.getString("id"));
}
} catch (SQLException ex) {
logger.warning("Could not get region list for save comparison: " + ex.getMessage());
}
for (Map.Entry<String, ProtectedRegion> entry : regions.entrySet()) {
String name = entry.getKey();
ProtectedRegion region = entry.getValue();
try {
if (regionsInDatabase.contains(name)) {
regionsInDatabase.remove(name);
if (region instanceof ProtectedCuboidRegion) {
updateRegionCuboid( (ProtectedCuboidRegion) region );
} else if (region instanceof ProtectedPolygonalRegion) {
updateRegionPoly2D( (ProtectedPolygonalRegion) region );
} else if (region instanceof GlobalProtectedRegion) {
updateRegionGlobal( (GlobalProtectedRegion) region );
} else {
this.updateRegion(region, region.getClass().getCanonicalName());
}
} else {
if (region instanceof ProtectedCuboidRegion) {
insertRegionCuboid( (ProtectedCuboidRegion) region );
} else if (region instanceof ProtectedPolygonalRegion) {
insertRegionPoly2D( (ProtectedPolygonalRegion) region );
} else if (region instanceof GlobalProtectedRegion) {
insertRegionGlobal( (GlobalProtectedRegion) region );
} else {
this.insertRegion(region, region.getClass().getCanonicalName());
}
}
} catch (SQLException ex) {
logger.warning("Could not save region " + region.getId().toLowerCase() + ": " + ex.getMessage());
throw new ProtectionDatabaseException(ex);
}
}
for (Map.Entry<String, ProtectedRegion> entry : regions.entrySet()) {
try {
if (entry.getValue().getParent() == null) continue;
PreparedStatement setParentStatement = this.conn.prepareStatement(
"UPDATE `region` SET " +
"`parent` = ? " +
"WHERE `id` = ? "
);
setParentStatement.setString(1, entry.getValue().getParent().getId().toLowerCase());
setParentStatement.setString(2, entry.getValue().getId().toLowerCase());
setParentStatement.execute();
} catch (SQLException ex) {
logger.warning("Could not save region parents " + entry.getValue().getId().toLowerCase() + ": " + ex.getMessage());
throw new ProtectionDatabaseException(ex);
}
}
for (String name : regionsInDatabase) {
try {
PreparedStatement removeRegion = this.conn.prepareStatement(
"DELETE FROM `region` WHERE `id` = ? "
);
removeRegion.setString(1, name);
removeRegion.execute();
} catch (SQLException ex) {
logger.warning("Could not remove region from database " + name + ": " + ex.getMessage());
}
}
}
private void updateFlags(ProtectedRegion region) throws SQLException {
PreparedStatement clearCurrentFlagStatement = this.conn.prepareStatement(
"DELETE FROM `region_flag` " +
"WHERE `region_id` = ? "
);
clearCurrentFlagStatement.setString(1, region.getId().toLowerCase());
clearCurrentFlagStatement.execute();
for (Map.Entry<Flag<?>, Object> entry : region.getFlags().entrySet()) {
if (entry.getValue() == null) continue;
Object flag = marshalFlag(entry.getKey(), entry.getValue());
PreparedStatement insertFlagStatement = this.conn.prepareStatement(
"INSERT INTO `region_flag` ( " +
"`id`, " +
"`region_id`, " +
"`flag`, " +
"`value` " +
") VALUES (null, ?, ?, ?)"
);
insertFlagStatement.setString(1, region.getId().toLowerCase());
insertFlagStatement.setString(2, entry.getKey().getName());
insertFlagStatement.setObject(3, flag);
insertFlagStatement.execute();
}
}
private void updatePlayerAndGroups(ProtectedRegion region, Boolean owners) throws SQLException {
DefaultDomain domain;
if (owners) {
domain = region.getOwners();
} else {
domain = region.getMembers();
}
PreparedStatement deleteUsersForRegion = this.conn.prepareStatement(
"DELETE FROM `region_players` " +
"WHERE `region_id` = ? " +
"AND `owner` = ?"
);
deleteUsersForRegion.setString(1, region.getId().toLowerCase());
deleteUsersForRegion.setBoolean(2, owners);
deleteUsersForRegion.execute();
PreparedStatement insertUsersForRegion = this.conn.prepareStatement(
"INSERT INTO `region_players` " +
"(`region_id`, `user_id`, `owner`) VALUES (?, ?, ?)"
);
Map<String,Integer> players = getUserIds(domain.getPlayers().toArray(new String[0]));
for (Integer player : players.values()) {
insertUsersForRegion.setString(1, region.getId().toLowerCase());
insertUsersForRegion.setInt(2, player);
insertUsersForRegion.setBoolean(3, owners);
insertUsersForRegion.execute();
}
PreparedStatement deleteGroupsForRegion = this.conn.prepareStatement(
"DELETE FROM `region_groups` " +
"WHERE `region_id` = ? " +
"AND `owner` = ?"
);
deleteGroupsForRegion.setString(1, region.getId().toLowerCase());
deleteGroupsForRegion.setBoolean(2, owners);
deleteGroupsForRegion.execute();
PreparedStatement insertGroupsForRegion = this.conn.prepareStatement(
"INSERT INTO `region_groups` " +
"(`region_id`, `group_id`, `owner`) VALUES (?, ?, ?)"
);
Map<String,Integer> groups = getGroupIds(domain.getGroups().toArray(new String[0]));
for (Integer group : groups.values()) {
insertGroupsForRegion.setString(1, region.getId().toLowerCase());
insertGroupsForRegion.setInt(2, group);
insertGroupsForRegion.setBoolean(3, owners);
insertGroupsForRegion.execute();
}
}
@SuppressWarnings("unchecked")
private <V> Object marshalFlag(Flag<V> flag, Object val) {
return flag.marshal( (V) val );
}
private void insertRegion(ProtectedRegion region, String type) throws SQLException {
PreparedStatement insertRegionStatement = this.conn.prepareStatement(
"INSERT INTO `region` (" +
"`id`, " +
"`world_id`, " +
"`type`, " +
"`priority`, " +
"`parent` " +
") VALUES (?, " + this.worldDbId + ", ?, ?, null)"
);
insertRegionStatement.setString(1, region.getId().toLowerCase());
insertRegionStatement.setString(2, type);
insertRegionStatement.setInt(3, region.getPriority());
insertRegionStatement.execute();
updateFlags(region);
updatePlayerAndGroups(region, false);
updatePlayerAndGroups(region, true);
}
private void insertRegionCuboid(ProtectedCuboidRegion region) throws SQLException {
insertRegion(region, "cuboid");
PreparedStatement insertCuboidRegionStatement = this.conn.prepareStatement(
"INSERT INTO `region_cuboid` (" +
"`region_id`, " +
"`min_z`, " +
"`min_y`, " +
"`min_x`, " +
"`max_z`, " +
"`max_y`, " +
"`max_x` " +
") VALUES (?, ?, ?, ?, ?, ?, ?)"
);
BlockVector min = region.getMinimumPoint();
BlockVector max = region.getMaximumPoint();
insertCuboidRegionStatement.setString(1, region.getId().toLowerCase());
insertCuboidRegionStatement.setInt(2, min.getBlockZ());
insertCuboidRegionStatement.setInt(3, min.getBlockY());
insertCuboidRegionStatement.setInt(4, min.getBlockX());
insertCuboidRegionStatement.setInt(5, max.getBlockZ());
insertCuboidRegionStatement.setInt(6, max.getBlockY());
insertCuboidRegionStatement.setInt(7, max.getBlockX());
insertCuboidRegionStatement.execute();
}
private void insertRegionPoly2D(ProtectedPolygonalRegion region) throws SQLException {
insertRegion(region, "poly2d");
PreparedStatement insertPoly2dRegionStatement = this.conn.prepareStatement(
"INSERT INTO `region_poly2d` (" +
"`region_id`, " +
"`max_y`, " +
"`min_y` " +
") VALUES (?, ?, ?)"
);
insertPoly2dRegionStatement.setString(1, region.getId().toLowerCase());
insertPoly2dRegionStatement.setInt(2, region.getMaximumPoint().getBlockY());
insertPoly2dRegionStatement.setInt(3, region.getMinimumPoint().getBlockY());
insertPoly2dRegionStatement.execute();
updatePoly2dPoints(region);
}
private void updatePoly2dPoints(ProtectedPolygonalRegion region) throws SQLException {
PreparedStatement clearPoly2dPointsForRegionStatement = this.conn.prepareStatement(
"DELETE FROM `region_poly2d_point` " +
"WHERE `region_id` = ? "
);
clearPoly2dPointsForRegionStatement.setString(1, region.getId().toLowerCase());
clearPoly2dPointsForRegionStatement.execute();
PreparedStatement insertPoly2dPointStatement = this.conn.prepareStatement(
"INSERT INTO `region_poly2d_point` (" +
"`id`, " +
"`region_id`, " +
"`z`, " +
"`x` " +
") VALUES (null, ?, ?, ?)"
);
for (BlockVector2D point : region.getPoints()) {
insertPoly2dPointStatement.setString(1, region.getId().toLowerCase());
insertPoly2dPointStatement.setInt(2, point.getBlockZ());
insertPoly2dPointStatement.setInt(3, point.getBlockX());
insertPoly2dPointStatement.execute();
}
}
private void insertRegionGlobal(GlobalProtectedRegion region) throws SQLException {
insertRegion(region, "global");
}
private void updateRegion(ProtectedRegion region, String type) throws SQLException {
PreparedStatement updateRegionStatement = this.conn.prepareStatement(
"UPDATE `region` SET " +
"`priority` = ? WHERE `id` = ? "
);
updateRegionStatement.setInt(1, region.getPriority());
updateRegionStatement.setString(2, region.getId().toLowerCase());
updateRegionStatement.execute();
updateFlags(region);
updatePlayerAndGroups(region, false);
updatePlayerAndGroups(region, true);
}
private void updateRegionCuboid(ProtectedCuboidRegion region) throws SQLException {
updateRegion(region, "cuboid");
PreparedStatement updateCuboidRegionStatement = this.conn.prepareStatement(
"UPDATE `region_cuboid` SET " +
"`min_z` = ?, " +
"`min_y` = ?, " +
"`min_x` = ?, " +
"`max_z` = ?, " +
"`max_y` = ?, " +
"`max_x` = ? " +
"WHERE `region_id` = ? "
);
BlockVector min = region.getMinimumPoint();
BlockVector max = region.getMaximumPoint();
updateCuboidRegionStatement.setInt(1, min.getBlockZ());
updateCuboidRegionStatement.setInt(2, min.getBlockY());
updateCuboidRegionStatement.setInt(3, min.getBlockX());
updateCuboidRegionStatement.setInt(4, max.getBlockZ());
updateCuboidRegionStatement.setInt(5, max.getBlockY());
updateCuboidRegionStatement.setInt(6, max.getBlockX());
updateCuboidRegionStatement.setString(7, region.getId().toLowerCase());
updateCuboidRegionStatement.execute();
}
private void updateRegionPoly2D(ProtectedPolygonalRegion region) throws SQLException {
updateRegion(region, "poly2d");
PreparedStatement updatePoly2dRegionStatement = this.conn.prepareStatement(
"UPDATE `region_poly2d` SET " +
"`max_y` = ?, " +
"`min_y` = ? " +
"WHERE `region_id` = ? "
);
updatePoly2dRegionStatement.setInt(1, region.getMaximumPoint().getBlockY());
updatePoly2dRegionStatement.setInt(2, region.getMinimumPoint().getBlockY());
updatePoly2dRegionStatement.setString(3, region.getId().toLowerCase());
updatePoly2dRegionStatement.execute();
updatePoly2dPoints(region);
}
private void updateRegionGlobal(GlobalProtectedRegion region) throws SQLException {
updateRegion(region, "global");
}
public Map<String, ProtectedRegion> getRegions() {
return regions;
}
public void setRegions(Map<String, ProtectedRegion> regions) {
this.regions = regions;
}
}
@@ -19,7 +19,6 @@
package com.sk89q.worldguard.protection.databases;
import java.io.IOException;
import java.util.Map;
import com.sk89q.worldguard.protection.managers.RegionManager;
@@ -35,29 +34,29 @@ public interface ProtectionDatabase {
* Load the list of regions. The method should not modify the list returned
* by getRegions() unless the load finishes successfully.
*
* @throws IOException
* @throws ProtectionDatabaseException
*/
public void load() throws IOException;
public void load() throws ProtectionDatabaseException;
/**
* Save the list of regions.
*
* @throws IOException
* @throws ProtectionDatabaseException
*/
public void save() throws IOException;
public void save() throws ProtectionDatabaseException;
/**
* Load the list of regions into a region manager.
*
* @param manager
* @throws IOException
* @throws ProtectionDatabaseException
*/
public void load(RegionManager manager) throws IOException;
public void load(RegionManager manager) throws ProtectionDatabaseException;
/**
* Save the list of regions from a region manager.
*
* @param manager
* @throws IOException
* @throws ProtectionDatabaseException
*/
public void save(RegionManager manager) throws IOException;
public void save(RegionManager manager) throws ProtectionDatabaseException;
/**
* Get a list of regions.
*
@@ -0,0 +1,42 @@
// $Id$
/*
* WorldGuard ProtectionDatabaseException
* Copyright (C) 2011 Nicholas Steicke <http://narthollis.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection.databases;
import java.lang.Exception;
public class ProtectionDatabaseException extends Exception {
private static final long serialVersionUID = 1L;
public ProtectionDatabaseException() {
super();
}
public ProtectionDatabaseException(String message) {
super(message);
}
public ProtectionDatabaseException(String message, Throwable cause) {
super(message, cause);
}
public ProtectionDatabaseException(Throwable cause) {
super(cause);
}
}
@@ -19,6 +19,8 @@
package com.sk89q.worldguard.protection.databases;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -98,4 +100,34 @@ public class RegionDBUtil {
return domain;
}
/**
* Creates a comma separated list of PreparedStatement place holders
*
* @param length
* @return
*/
public static String preparePlaceHolders(int length) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < length;) {
builder.append("?");
if (++i < length) {
builder.append(",");
}
}
return builder.toString();
}
/**
* Adds all of the parsed values to the PreparedStatement
*
* @param preparedStatement
* @param values
* @throws SQLException
*/
public static void setValues(PreparedStatement preparedStatement, String... values) throws SQLException {
for (int i = 0; i < values.length; i++) {
preparedStatement.setString(i + 1, values[i]);
}
}
}
@@ -21,6 +21,7 @@ package com.sk89q.worldguard.protection.databases;
import java.io.File;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
@@ -29,6 +30,9 @@ import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import com.sk89q.util.yaml.YAMLFormat;
import com.sk89q.util.yaml.YAMLNode;
import com.sk89q.util.yaml.YAMLProcessor;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.BlockVector2D;
import com.sk89q.worldedit.Vector;
@@ -40,24 +44,33 @@ import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion.CircularInheritanceException;
import com.sk89q.worldguard.util.yaml.Configuration;
import com.sk89q.worldguard.util.yaml.ConfigurationNode;
public class YAMLDatabase extends AbstractProtectionDatabase {
private static Logger logger = Logger.getLogger("Minecraft.WorldGuard");
private Configuration config;
private YAMLProcessor config;
private Map<String, ProtectedRegion> regions;
private final Logger logger;
public YAMLDatabase(File file) {
config = new Configuration(file);
public YAMLDatabase(File file, Logger logger) throws ProtectionDatabaseException, FileNotFoundException {
this.logger = logger;
if (!file.exists()) { // shouldn't be necessary, but check anyways
try {
file.createNewFile();
} catch (IOException e) {
throw new FileNotFoundException(file.getAbsolutePath());
}
}
config = new YAMLProcessor(file, false, YAMLFormat.COMPACT);
}
public void load() throws IOException {
config.load();
public void load() throws ProtectionDatabaseException {
try {
config.load();
} catch (IOException e) {
throw new ProtectionDatabaseException(e);
}
Map<String, ConfigurationNode> regionData = config.getNodes("regions");
Map<String, YAMLNode> regionData = config.getNodes("regions");
// No regions are even configured
if (regionData == null) {
@@ -70,9 +83,9 @@ public class YAMLDatabase extends AbstractProtectionDatabase {
Map<ProtectedRegion,String> parentSets =
new LinkedHashMap<ProtectedRegion, String>();
for (Map.Entry<String, ConfigurationNode> entry : regionData.entrySet()) {
for (Map.Entry<String, YAMLNode> entry : regionData.entrySet()) {
String id = entry.getKey().toLowerCase().replace(".", "");
ConfigurationNode node = entry.getValue();
YAMLNode node = entry.getValue();
String type = node.getString("type");
ProtectedRegion region;
@@ -141,7 +154,7 @@ public class YAMLDatabase extends AbstractProtectionDatabase {
return val;
}
private void setFlags(ProtectedRegion region, ConfigurationNode flagsData) {
private void setFlags(ProtectedRegion region, YAMLNode flagsData) {
if (flagsData == null) {
return;
}
@@ -165,7 +178,7 @@ public class YAMLDatabase extends AbstractProtectionDatabase {
region.setFlag(flag, val);
}
private DefaultDomain parseDomain(ConfigurationNode node) {
private DefaultDomain parseDomain(YAMLNode node) {
if (node == null) {
return new DefaultDomain();
}
@@ -183,12 +196,12 @@ public class YAMLDatabase extends AbstractProtectionDatabase {
return domain;
}
public void save() throws IOException {
public void save() throws ProtectionDatabaseException {
config.clear();
for (Map.Entry<String, ProtectedRegion> entry : regions.entrySet()) {
ProtectedRegion region = entry.getValue();
ConfigurationNode node = config.addNode("regions." + entry.getKey());
YAMLNode node = config.addNode("regions." + entry.getKey());
if (region instanceof ProtectedCuboidRegion) {
ProtectedCuboidRegion cuboid = (ProtectedCuboidRegion) region;
@@ -0,0 +1,62 @@
// $Id$
/*
* MySQL WordGuard Region Database
* Copyright (C) 2011 Nicholas Steicke <http://narthollis.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection.databases.migrators;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import com.sk89q.worldguard.protection.databases.ProtectionDatabase;
import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
public abstract class AbstractDatabaseMigrator implements DatabaseMigrator {
private static HashMap<MigratorKey, Class<? extends AbstractDatabaseMigrator>> migrators =
new HashMap<MigratorKey, Class<? extends AbstractDatabaseMigrator>>();
public static Map<MigratorKey, Class<? extends AbstractDatabaseMigrator>> getMigrators() {
if (!migrators.isEmpty()) return migrators;
AbstractDatabaseMigrator.migrators.put(new MigratorKey("mysql", "yaml"), MySQLToYAMLMigrator.class);
AbstractDatabaseMigrator.migrators.put(new MigratorKey("yaml", "mysql"), YAMLToMySQLMigrator.class);
return migrators;
}
protected abstract Set<String> getWorldsFromOld() throws MigrationException;
protected abstract Map<String, ProtectedRegion> getRegionsForWorldFromOld(String world) throws MigrationException;
protected abstract ProtectionDatabase getNewWorldStorage(String world) throws MigrationException;
public void migrate() throws MigrationException {
for (String world : this.getWorldsFromOld()) {
ProtectionDatabase database = this.getNewWorldStorage(world);
database.setRegions(this.getRegionsForWorldFromOld(world));
try {
database.save();
} catch (ProtectionDatabaseException e) {
throw new MigrationException(e);
}
}
}
}
@@ -1,7 +1,7 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
* MySQL WordGuard Region Database
* Copyright (C) 2011 Nicholas Steicke <http://narthollis.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -17,21 +17,15 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.util.yaml;
package com.sk89q.worldguard.protection.databases.migrators;
/**
* Configuration exception.
*
* @author sk89q
* Represents a method of converting from one database to another.
*
* @author Nicholas Steicke
*/
public class ConfigurationException extends Exception {
private static final long serialVersionUID = -2442886939908724203L;
public ConfigurationException() {
super();
}
public ConfigurationException(String msg) {
super(msg);
}
public interface DatabaseMigrator {
public void migrate() throws MigrationException;
}
@@ -0,0 +1,40 @@
// $Id$
/*
* MySQL WordGuard Region Database
* Copyright (C) 2011 Nicholas Steicke <http://narthollis.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection.databases.migrators;
public class MigrationException extends Exception {
private static final long serialVersionUID = 1L;
public MigrationException() {
super();
}
public MigrationException(String message) {
super(message);
}
public MigrationException(String message, Throwable cause) {
super(message, cause);
}
public MigrationException(Throwable cause) {
super(cause);
}
}
@@ -0,0 +1,43 @@
// $Id$
/*
* MySQL WordGuard Region Database
* Copyright (C) 2011 Nicholas Steicke <http://narthollis.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection.databases.migrators;
public class MigratorKey {
public final String from;
public final String to;
public MigratorKey(String from, String to) {
this.from = from;
this.to = to;
}
public boolean equals(Object o) {
MigratorKey other = (MigratorKey) o;
return other.from.equals(this.from) && other.to.equals(this.to);
}
public int hashCode() {
int hash = 17;
hash = hash * 31 + this.from.hashCode();
hash = hash * 31 + this.to.hashCode();
return hash;
}
}
@@ -0,0 +1,97 @@
// $Id$
/*
* MySQL WordGuard Region Database
* Copyright (C) 2011 Nicholas Steicke <http://narthollis.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection.databases.migrators;
import java.io.File;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.databases.MySQLDatabase;
import com.sk89q.worldguard.protection.databases.ProtectionDatabase;
import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
import com.sk89q.worldguard.protection.databases.YAMLDatabase;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
public class MySQLToYAMLMigrator extends AbstractDatabaseMigrator {
private WorldGuardPlugin plugin;
private Set<String> worlds;
public MySQLToYAMLMigrator(WorldGuardPlugin plugin) throws MigrationException {
this.plugin = plugin;
this.worlds = new HashSet<String>();
ConfigurationManager config = plugin.getGlobalStateManager();
try {
Connection conn = DriverManager.getConnection(config.sqlDsn, config.sqlUsername, config.sqlPassword);
ResultSet worlds = conn.prepareStatement("SELECT `name` FROM `world`;").executeQuery();
while(worlds.next()) {
this.worlds.add(worlds.getString(1));
}
conn.close();
} catch (SQLException e) {
throw new MigrationException((Exception) e);
}
}
@Override
protected Set<String> getWorldsFromOld() {
return this.worlds;
}
@Override
protected Map<String, ProtectedRegion> getRegionsForWorldFromOld(String world) throws MigrationException {
ProtectionDatabase oldDatabase;
try {
oldDatabase = new MySQLDatabase(plugin.getGlobalStateManager(), world, plugin.getLogger());
oldDatabase.load();
} catch (ProtectionDatabaseException e) {
throw new MigrationException((Exception) e);
}
return oldDatabase.getRegions();
}
@Override
protected ProtectionDatabase getNewWorldStorage(String world) throws MigrationException {
try {
File file = new File(plugin.getDataFolder(),
"worlds" + File.separator + world + File.separator + "regions.yml");
return new YAMLDatabase(file, plugin.getLogger());
} catch (FileNotFoundException e) {
throw new MigrationException((Exception) e);
} catch (ProtectionDatabaseException e) {
throw new MigrationException((Exception) e);
}
}
}
@@ -0,0 +1,86 @@
// $Id$
/*
* MySQL WordGuard Region Database
* Copyright (C) 2011 Nicholas Steicke <http://narthollis.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection.databases.migrators;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.databases.MySQLDatabase;
import com.sk89q.worldguard.protection.databases.ProtectionDatabase;
import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
import com.sk89q.worldguard.protection.databases.YAMLDatabase;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
public class YAMLToMySQLMigrator extends AbstractDatabaseMigrator {
private WorldGuardPlugin plugin;
private HashMap<String,File> regionYamlFiles;
public YAMLToMySQLMigrator(WorldGuardPlugin plugin) {
this.plugin = plugin;
this.regionYamlFiles = new HashMap<String,File>();
File files[] = new File(plugin.getDataFolder(), "worlds" + File.separator).listFiles();
for (File item : files) {
if (item.isDirectory()) {
for (File subItem : item.listFiles()) {
if (subItem.getName().equals("regions.yml")) {
this.regionYamlFiles.put(item.getName(), subItem);
}
}
}
}
}
@Override
protected Set<String> getWorldsFromOld() {
return this.regionYamlFiles.keySet();
}
@Override
protected Map<String, ProtectedRegion> getRegionsForWorldFromOld(String world) throws MigrationException {
ProtectionDatabase oldDatabase;
try {
oldDatabase = new YAMLDatabase(this.regionYamlFiles.get(world), plugin.getLogger());
oldDatabase.load();
} catch (FileNotFoundException e) {
throw new MigrationException((Exception) e);
} catch (ProtectionDatabaseException e) {
throw new MigrationException((Exception) e);
}
return oldDatabase.getRegions();
}
@Override
protected ProtectionDatabase getNewWorldStorage(String world) throws MigrationException {
try {
return new MySQLDatabase(plugin.getGlobalStateManager(), world, plugin.getLogger());
} catch (ProtectionDatabaseException e) {
throw new MigrationException((Exception) e);
}
}
}
@@ -33,6 +33,7 @@ public final class DefaultFlag {
public static final StateFlag MOB_DAMAGE = new StateFlag("mob-damage", 'm', true);
public static final StateFlag MOB_SPAWNING = new StateFlag("mob-spawning", true);
public static final StateFlag CREEPER_EXPLOSION = new StateFlag("creeper-explosion", 'c', true);
public static final StateFlag ENDERDRAGON_BLOCK_DAMAGE = new StateFlag("enderdragon-block-damage", true);
public static final StateFlag GHAST_FIREBALL = new StateFlag("ghast-fireball", true);
public static final StateFlag SLEEP = new StateFlag("sleep", true);
public static final StateFlag TNT = new StateFlag("tnt", 't', true);
@@ -56,6 +57,7 @@ public final class DefaultFlag {
public static final StateFlag GRASS_SPREAD = new StateFlag("grass-growth", true);
public static final StateFlag ENDER_BUILD = new StateFlag("enderman-grief", true);
public static final StateFlag INVINCIBILITY = new StateFlag("invincible", false);
public static final StateFlag EXP_DROPS = new StateFlag("exp-drops", true);
public static final StateFlag ENTRY = new StateFlag("entry", true);
public static final RegionGroupFlag ENTRY_PERM = new RegionGroupFlag("entry-group", RegionGroupFlag.RegionGroup.NON_MEMBERS);
public static final StateFlag EXIT = new StateFlag("exit", true);
@@ -85,10 +87,10 @@ public final class DefaultFlag {
public static final Flag<?>[] flagsList = new Flag<?>[] {
PASSTHROUGH, BUILD, PVP, CHEST_ACCESS, PISTONS,
TNT, LIGHTER, USE, PLACE_VEHICLE, DESTROY_VEHICLE, SLEEP,
MOB_DAMAGE, MOB_SPAWNING, DENY_SPAWN, INVINCIBILITY,
CREEPER_EXPLOSION, GHAST_FIREBALL, ENDER_BUILD,
MOB_DAMAGE, MOB_SPAWNING, DENY_SPAWN, INVINCIBILITY, EXP_DROPS,
CREEPER_EXPLOSION, ENDERDRAGON_BLOCK_DAMAGE, GHAST_FIREBALL, ENDER_BUILD,
GREET_MESSAGE, FAREWELL_MESSAGE, NOTIFY_ENTER, NOTIFY_LEAVE,
EXIT, EXIT_PERM, ENTRY, ENTRY_PERM,
EXIT, EXIT_PERM, ENTRY, ENTRY_PERM, LIGHTNING,
HEAL_AMOUNT, HEAL_DELAY, MIN_HEAL, MAX_HEAL,
FEED_DELAY, FEED_AMOUNT, MIN_FOOD, MAX_FOOD,
SNOW_FALL, SNOW_MELT, ICE_FORM, ICE_MELT,
@@ -70,7 +70,7 @@ public class RegionGroupFlag extends Flag<RegionGroupFlag.RegionGroup> {
} else if (input.equalsIgnoreCase("everyone") || input.equalsIgnoreCase("anyone")) {
return null;
} else {
throw new InvalidFlagFormat("Not none/allow/deny: " + input);
throw new InvalidFlagFormat("Expected [non]member/[non]owner/anyone but got '" + input + "'");
}
}
@@ -70,7 +70,7 @@ public class StateFlag extends Flag<StateFlag.State> {
} else if (input.equalsIgnoreCase("none")) {
return null;
} else {
throw new InvalidFlagFormat("Not none/allow/deny: " + input);
throw new InvalidFlagFormat("Expected none/allow/deny but got '" + input + "'");
}
}
@@ -150,7 +150,7 @@ public class FlatRegionManager extends RegionManager {
while (parent != null) {
if (!appRegions.contains(parent)) {
appRegions.add(region);
appRegions.add(parent);
}
parent = parent.getParent();
@@ -32,6 +32,7 @@ import org.khelekore.prtree.PRTree;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
import com.sk89q.worldguard.protection.databases.ProtectionDatabase;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegionMBRConverter;
@@ -58,7 +59,7 @@ public class PRTreeRegionManager extends RegionManager {
* @param regionloader
* @throws IOException
*/
public PRTreeRegionManager(ProtectionDatabase regionloader) throws IOException {
public PRTreeRegionManager(ProtectionDatabase regionloader) throws ProtectionDatabaseException {
super(regionloader);
regions = new TreeMap<String, ProtectedRegion>();
tree = new PRTree<ProtectedRegion>(converter, BRANCH_FACTOR);
@@ -26,6 +26,7 @@ import java.util.Map;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
import com.sk89q.worldguard.protection.databases.ProtectionDatabase;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
@@ -56,7 +57,7 @@ public abstract class RegionManager {
*
* @throws IOException thrown on load error
*/
public void load() throws IOException {
public void load() throws ProtectionDatabaseException {
loader.load(this);
}
@@ -65,7 +66,7 @@ public abstract class RegionManager {
*
* @throws IOException thrown on save eIf checking multiple flags for a single locationror
*/
public void save() throws IOException {
public void save() throws ProtectionDatabaseException {
loader.save(this);
}
@@ -140,11 +141,9 @@ public abstract class RegionManager {
* Get an object for a point for rules to be applied with. This gets
* a set for the given reason.
*
* @deprecated not yet fully supported
* @param region region
* @return regino set
*/
@Deprecated
public abstract ApplicableRegionSet getApplicableRegions(
ProtectedRegion region);
@@ -23,6 +23,7 @@ import java.util.ArrayList;
import java.util.List;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.BlockVector2D;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.protection.UnsupportedIntersectionException;
@@ -30,16 +31,14 @@ public class GlobalProtectedRegion extends ProtectedRegion {
public GlobalProtectedRegion(String id) {
super(id);
min = new BlockVector(0, 0, 0);
max = new BlockVector(0, 0, 0);
}
@Override
public BlockVector getMinimumPoint() {
return new BlockVector(0, 0, 0);
}
@Override
public BlockVector getMaximumPoint() {
return new BlockVector(0, 0, 0);
public List<BlockVector2D> getPoints() {
List<BlockVector2D> pts = new ArrayList<BlockVector2D>();
pts.add(new BlockVector2D(min.getBlockX(),min.getBlockZ()));
return pts;
}
@Override
@@ -33,36 +33,29 @@ import com.sk89q.worldguard.protection.UnsupportedIntersectionException;
*/
public class ProtectedCuboidRegion extends ProtectedRegion {
/**
* Store the first point.
*/
private BlockVector min;
/**
* Store the second point.
*/
private BlockVector max;
/**
* Construct a new instance of this cuboid region.
*
* @param id
* @param min
* @param max
* @param pt1
* @param pt2
*/
public ProtectedCuboidRegion(String id, BlockVector min, BlockVector max) {
public ProtectedCuboidRegion(String id, BlockVector pt1, BlockVector pt2) {
super(id);
this.min = min;
this.max = max;
setMinMaxPoints(pt1, pt2);
}
/**
* Get the lower point of the cuboid.
* Given any two points, sets the minimum and maximum points
*
* @return min point
* @param pt1
* @param pt2
*/
@Override
public BlockVector getMinimumPoint() {
return min;
private void setMinMaxPoints(BlockVector pt1, BlockVector pt2) {
List<Vector> points = new ArrayList<Vector>();
points.add(pt1);
points.add(pt2);
setMinMaxPoints(points);
}
/**
@@ -71,17 +64,7 @@ public class ProtectedCuboidRegion extends ProtectedRegion {
* @param pt
*/
public void setMinimumPoint(BlockVector pt) {
min = pt;
}
/**
* Get the upper point of the cuboid.
*
* @return max point
*/
@Override
public BlockVector getMaximumPoint() {
return max;
setMinMaxPoints(pt, max);
}
/**
@@ -90,7 +73,22 @@ public class ProtectedCuboidRegion extends ProtectedRegion {
* @param pt
*/
public void setMaximumPoint(BlockVector pt) {
max = pt;
setMinMaxPoints(min, pt);
}
public List<BlockVector2D> getPoints() {
List<BlockVector2D> pts = new ArrayList<BlockVector2D>();
int x1 = min.getBlockX();
int x2 = max.getBlockX();
int z1 = min.getBlockZ();
int z2 = max.getBlockZ();
pts.add(new BlockVector2D(x1, z1));
pts.add(new BlockVector2D(x2, z1));
pts.add(new BlockVector2D(x1, z2));
pts.add(new BlockVector2D(x2, z2));
return pts;
}
/**
@@ -134,124 +132,28 @@ public class ProtectedCuboidRegion extends ProtectedRegion {
@Override
public List<ProtectedRegion> getIntersectingRegions(List<ProtectedRegion> regions) throws UnsupportedIntersectionException {
int numRegions = regions.size();
List<ProtectedRegion> intersectingRegions = new ArrayList<ProtectedRegion>();
int i, i2, i3;
for (i = 0; i < numRegions; i++) {
ProtectedRegion region = regions.get(i);
BlockVector rMinPoint = region.getMinimumPoint();
BlockVector rMaxPoint = region.getMaximumPoint();
for (ProtectedRegion region : regions) {
if (!intersectsBoundingBox(region)) continue;
// Check whether the region is outside the min and max vector
if ((rMinPoint.getBlockX() < min.getBlockX() && rMaxPoint.getBlockX() < min.getBlockX())
|| (rMinPoint.getBlockX() > max.getBlockX() && rMaxPoint.getBlockX() > max.getBlockX())
&& ((rMinPoint.getBlockY() < min.getBlockY() && rMaxPoint.getBlockY() < min.getBlockY())
|| (rMinPoint.getBlockY() > max.getBlockY() && rMaxPoint.getBlockY() > max.getBlockY()))
&& ((rMinPoint.getBlockZ() < min.getBlockZ() && rMaxPoint.getBlockZ() < min.getBlockZ())
|| (rMinPoint.getBlockZ() > max.getBlockZ() && rMaxPoint.getBlockZ() > max.getBlockZ())) ) {
//intersectingRegions.add(regions.get(i));
// If both regions are Cuboids and their bounding boxes intersect, they intersect
if (region instanceof ProtectedCuboidRegion) {
intersectingRegions.add(region);
continue;
}
// Check whether the regions points are inside the other region
if (region.contains(new Vector(min.getBlockX(), min.getBlockY(), min.getBlockZ()))
|| region.contains(new Vector(min.getBlockX(), min.getBlockY(), max.getBlockZ()))
|| region.contains(new Vector(min.getBlockX(), max.getBlockY(), max.getBlockZ()))
|| region.contains(new Vector(min.getBlockX(), max.getBlockY(), min.getBlockZ()))
|| region.contains(new Vector(max.getBlockX(), max.getBlockY(), max.getBlockZ()))
|| region.contains(new Vector(max.getBlockX(), max.getBlockY(), min.getBlockZ()))
|| region.contains(new Vector(max.getBlockX(), min.getBlockY(), min.getBlockZ()))
|| region.contains(new Vector(max.getBlockX(), min.getBlockY(), max.getBlockZ())) ) {
intersectingRegions.add(regions.get(i));
continue;
}
// Check whether the other regions points are inside the current region
if (region instanceof ProtectedPolygonalRegion) {
for (i2 = 0; i2 < ((ProtectedPolygonalRegion)region).getPoints().size(); i2++) {
BlockVector2D pt2Dr = ((ProtectedPolygonalRegion)region).getPoints().get(i2);
int minYr = ((ProtectedPolygonalRegion)region).minY;
int maxYr = ((ProtectedPolygonalRegion)region).maxY;
Vector ptr = new Vector(pt2Dr.getBlockX(), minYr, pt2Dr.getBlockZ());
Vector ptr2 = new Vector(pt2Dr.getBlockX(), maxYr, pt2Dr.getBlockZ());
if (this.contains(ptr) || this.contains(ptr2)) {
intersectingRegions.add(regions.get(i));
continue;
}
}
} else if (region instanceof ProtectedCuboidRegion) {
BlockVector ptcMin = region.getMinimumPoint();
BlockVector ptcMax = region.getMaximumPoint();
if (this.contains(new Vector(ptcMin.getBlockX(), ptcMin.getBlockY(), ptcMin.getBlockZ()))
|| this.contains(new Vector(ptcMin.getBlockX(), ptcMin.getBlockY(), ptcMax.getBlockZ()))
|| this.contains(new Vector(ptcMin.getBlockX(), ptcMax.getBlockY(), ptcMax.getBlockZ()))
|| this.contains(new Vector(ptcMin.getBlockX(), ptcMax.getBlockY(), ptcMin.getBlockZ()))
|| this.contains(new Vector(ptcMax.getBlockX(), ptcMax.getBlockY(), ptcMax.getBlockZ()))
|| this.contains(new Vector(ptcMax.getBlockX(), ptcMax.getBlockY(), ptcMin.getBlockZ()))
|| this.contains(new Vector(ptcMax.getBlockX(), ptcMin.getBlockY(), ptcMin.getBlockZ()))
|| this.contains(new Vector(ptcMax.getBlockX(), ptcMin.getBlockY(), ptcMax.getBlockZ())) ) {
intersectingRegions.add(regions.get(i));
} else if (region instanceof ProtectedPolygonalRegion) {
// If either region contains the points of the other,
// or if any edges intersect, the regions intersect
if (containsAny(region.getPoints())
|| region.containsAny(getPoints())
|| intersectsEdges(region)) {
intersectingRegions.add(region);
continue;
}
} else {
throw new UnsupportedOperationException("Not supported yet.");
}
// Check whether the current regions edges collide with the regions edges
boolean regionIsIntersecting = false;
List<BlockVector2D> points = new ArrayList<BlockVector2D>();
points.add(new BlockVector2D(min.getBlockX(), min.getBlockZ()));
points.add(new BlockVector2D(min.getBlockX(), max.getBlockZ()));
points.add(new BlockVector2D(max.getBlockX(), max.getBlockZ()));
points.add(new BlockVector2D(max.getBlockX(), min.getBlockZ()));
for (i2 = 0; i2 < points.size(); i2++) {
boolean checkNextPoint = false;
BlockVector2D currPoint = points.get(i2);
BlockVector2D nextPoint;
if (i2 == (points.size() - 1)) {
nextPoint = points.get(0);
} else {
nextPoint = points.get(i2 + 1);
}
int currX = currPoint.getBlockX();
int currZ = currPoint.getBlockZ();
while (!checkNextPoint) {
for(i3 = min.getBlockY(); i3 <= max.getBlockY(); i3++) {
if (region.contains(new Vector(currX, i3, currZ))) {
intersectingRegions.add(regions.get(i));
regionIsIntersecting = true;
break;
}
}
if (currX == nextPoint.getBlockX() || currZ == nextPoint.getBlockZ() || regionIsIntersecting) {
checkNextPoint = true;
}
if (nextPoint.getBlockX() > currPoint.getBlockX()) {
currX++;
} else {
currX--;
}
if (nextPoint.getBlockZ() > currPoint.getBlockZ()) {
currZ++;
} else {
currZ--;
}
}
if (regionIsIntersecting) {
break;
}
}
}
return intersectingRegions;
}
@@ -280,6 +182,4 @@ public class ProtectedCuboidRegion extends ProtectedRegion {
int volume = xLength * yLength * zLength;
return volume;
}
}
}
@@ -21,7 +21,6 @@ package com.sk89q.worldguard.protection.regions;
import java.util.ArrayList;
import java.util.List;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.BlockVector2D;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.protection.UnsupportedIntersectionException;
@@ -31,55 +30,36 @@ public class ProtectedPolygonalRegion extends ProtectedRegion {
protected List<BlockVector2D> points;
protected int minY;
protected int maxY;
private BlockVector min;
private BlockVector max;
public ProtectedPolygonalRegion(String id, List<BlockVector2D> points, int minY, int maxY) {
super(id);
this.points = points;
this.minY = minY;
this.maxY = maxY;
setMinMaxPoints(points, minY, maxY);
this.minY = min.getBlockY();
this.maxY = max.getBlockY();
}
int minX = points.get(0).getBlockX();
int minZ = points.get(0).getBlockZ();
int maxX = points.get(0).getBlockX();
int maxZ = points.get(0).getBlockZ();
for (BlockVector2D v : points) {
int x = v.getBlockX();
int z = v.getBlockZ();
if (x < minX) {
minX = x;
}
if (z < minZ) {
minZ = z;
}
if (x > maxX) {
maxX = x;
}
if (z > maxZ) {
maxZ = z;
}
/**
* Sets the min and max points from all the 2d points and the min/max Y values
*
* @param points2D
* @param minY
* @param maxY
*/
private void setMinMaxPoints(List<BlockVector2D> points2D, int minY, int maxY) {
List<Vector> points = new ArrayList<Vector>();
int y = minY;
for (BlockVector2D point2D : points2D) {
points.add(new Vector(point2D.getBlockX(), y, point2D.getBlockZ()));
y = maxY;
}
min = new BlockVector(minX, minY, minZ);
max = new BlockVector(maxX, maxY, maxZ);
setMinMaxPoints(points);
}
public List<BlockVector2D> getPoints() {
return points;
}
@Override
public BlockVector getMinimumPoint() {
return min;
}
@Override
public BlockVector getMaximumPoint() {
return max;
}
/**
* Checks to see if a point is inside this region.
*/
@@ -144,117 +124,24 @@ public class ProtectedPolygonalRegion extends ProtectedRegion {
@Override
public List<ProtectedRegion> getIntersectingRegions(List<ProtectedRegion> regions) throws UnsupportedIntersectionException {
int numRegions = regions.size();
int numPoints = points.size();
List<ProtectedRegion> intersectingRegions = new ArrayList<ProtectedRegion>();
int i, i2, i3;
for (i = 0; i < numRegions; i++) {
ProtectedRegion region = regions.get(i);
BlockVector rMinPoint = region.getMinimumPoint();
BlockVector rMaxPoint = region.getMaximumPoint();
for (ProtectedRegion region : regions) {
if (!intersectsBoundingBox(region)) continue;
// Check whether the region is outside the min and max vector
if ((rMinPoint.getBlockX() < min.getBlockX() && rMaxPoint.getBlockX() < min.getBlockX())
|| (rMinPoint.getBlockX() > max.getBlockX() && rMaxPoint.getBlockX() > max.getBlockX())
&& ((rMinPoint.getBlockY() < min.getBlockY() && rMaxPoint.getBlockY() < min.getBlockY())
|| (rMinPoint.getBlockY() > max.getBlockY() && rMaxPoint.getBlockY() > max.getBlockY()))
&& ((rMinPoint.getBlockZ() < min.getBlockZ() && rMaxPoint.getBlockZ() < min.getBlockZ())
|| (rMinPoint.getBlockZ() > max.getBlockZ() && rMaxPoint.getBlockZ() > max.getBlockZ())) ) {
intersectingRegions.add(regions.get(i));
continue;
}
// Check whether the regions points are inside the other region
for (i2 = 0; i < numPoints; i++) {
Vector pt = new Vector(points.get(i2).getBlockX(), minY, points.get(i2).getBlockZ());
Vector pt2 = new Vector(points.get(i2).getBlockX(), maxY, points.get(i2).getBlockZ());
if (region.contains(pt) || region.contains(pt2)) {
intersectingRegions.add(regions.get(i));
continue;
}
}
// Check whether the other regions points are inside the current region
if (region instanceof ProtectedPolygonalRegion) {
for (i2 = 0; i < ((ProtectedPolygonalRegion)region).getPoints().size(); i++) {
BlockVector2D pt2Dr = ((ProtectedPolygonalRegion)region).getPoints().get(i2);
int minYr = ((ProtectedPolygonalRegion)region).minY;
int maxYr = ((ProtectedPolygonalRegion)region).maxY;
Vector ptr = new Vector(pt2Dr.getBlockX(), minYr, pt2Dr.getBlockZ());
Vector ptr2 = new Vector(pt2Dr.getBlockX(), maxYr, pt2Dr.getBlockZ());
if (this.contains(ptr) || this.contains(ptr2)) {
intersectingRegions.add(regions.get(i));
continue;
}
}
} else if (region instanceof ProtectedCuboidRegion) {
BlockVector ptcMin = region.getMinimumPoint();
BlockVector ptcMax = region.getMaximumPoint();
if (this.contains(new Vector(ptcMin.getBlockX(), ptcMin.getBlockY(), ptcMin.getBlockZ()))
|| this.contains(new Vector(ptcMin.getBlockX(), ptcMin.getBlockY(), ptcMax.getBlockZ()))
|| this.contains(new Vector(ptcMin.getBlockX(), ptcMax.getBlockY(), ptcMax.getBlockZ()))
|| this.contains(new Vector(ptcMin.getBlockX(), ptcMax.getBlockY(), ptcMin.getBlockZ()))
|| this.contains(new Vector(ptcMax.getBlockX(), ptcMax.getBlockY(), ptcMax.getBlockZ()))
|| this.contains(new Vector(ptcMax.getBlockX(), ptcMax.getBlockY(), ptcMin.getBlockZ()))
|| this.contains(new Vector(ptcMax.getBlockX(), ptcMin.getBlockY(), ptcMin.getBlockZ()))
|| this.contains(new Vector(ptcMax.getBlockX(), ptcMin.getBlockY(), ptcMax.getBlockZ())) ) {
intersectingRegions.add(regions.get(i));
if (region instanceof ProtectedPolygonalRegion || region instanceof ProtectedCuboidRegion) {
// If either region contains the points of the other,
// or if any edges intersect, the regions intersect
if (containsAny(region.getPoints())
|| region.containsAny(getPoints())
|| intersectsEdges(region)) {
intersectingRegions.add(region);
continue;
}
} else {
throw new UnsupportedOperationException("Not supported yet.");
}
// Check whether the current regions edges collide with the regions edges
boolean regionIsIntersecting = false;
for (i2 = 0; i2 < numPoints; i2++) {
boolean checkNextPoint = false;
BlockVector2D currPoint = points.get(i2);
BlockVector2D nextPoint;
if (i2 == (numPoints - 1)) {
nextPoint = points.get(0);
} else {
nextPoint = points.get(i2 + 1);
}
int currX = currPoint.getBlockX();
int currZ = currPoint.getBlockZ();
while (!checkNextPoint) {
for(i3 = this.minY; i3 <= this.maxY; i3++) {
if (region.contains(new Vector(currX, i3, currZ))) {
intersectingRegions.add(regions.get(i));
regionIsIntersecting = true;
break;
}
}
if (currX == nextPoint.getBlockX() || currZ == nextPoint.getBlockZ() || regionIsIntersecting) {
checkNextPoint = true;
}
if (nextPoint.getBlockX() > currPoint.getBlockX()) {
currX++;
} else {
currX--;
}
if (nextPoint.getBlockZ() > currPoint.getBlockZ()) {
currZ++;
} else {
currZ--;
}
}
if (regionIsIntersecting) {
break;
}
}
}
return intersectingRegions;
}
@@ -277,7 +164,8 @@ public class ProtectedPolygonalRegion extends ProtectedRegion {
@Override
public int volume() {
int volume = 0;
int numPoints = points.size();
// TODO: Fix this
/*int numPoints = points.size();
if (numPoints < 3) {
return 0;
}
@@ -285,7 +173,7 @@ public class ProtectedPolygonalRegion extends ProtectedRegion {
double area = 0;
int xa, z1, z2;
for (int i = 0; i <= numPoints - 1; i++) {
for (int i = 0; i < numPoints; i++) {
xa = points.get(i).getBlockX();
//za = points.get(i).getBlockZ();
@@ -308,7 +196,7 @@ public class ProtectedPolygonalRegion extends ProtectedRegion {
area = area + (xa * (points.get(1).getBlockZ() - points.get(numPoints - 1).getBlockZ()));
volume = (Math.abs(maxY - minY) + 1) * (int) Math.ceil((Math.abs(area) / 2));
volume = (Math.abs(maxY - minY) + 1) * (int) Math.ceil((Math.abs(area) / 2));*/
return volume;
}
@@ -19,12 +19,14 @@
package com.sk89q.worldguard.protection.regions;
import java.awt.geom.Line2D;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.BlockVector2D;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.domains.DefaultDomain;
@@ -38,6 +40,9 @@ import com.sk89q.worldguard.protection.flags.Flag;
*/
public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
protected BlockVector min;
protected BlockVector max;
private static final Pattern idPattern = Pattern.compile("^[A-Za-z0-9_,'\\-\\+/]{1,}$");
/**
@@ -79,6 +84,37 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
this.id = id;
}
/**
* Sets the minimum and maximum points of the bounding box for a region
*
* @param points
*/
protected void setMinMaxPoints(List<Vector> points) {
int minX = points.get(0).getBlockX();
int minY = points.get(0).getBlockY();
int minZ = points.get(0).getBlockZ();
int maxX = minX;
int maxY = minY;
int maxZ = minZ;
for (Vector v : points) {
int x = v.getBlockX();
int y = v.getBlockY();
int z = v.getBlockZ();
if (x < minX) minX = x;
if (y < minY) minY = y;
if (z < minZ) minZ = z;
if (x > maxX) maxX = x;
if (y > maxY) maxY = y;
if (z > maxZ) maxZ = z;
}
min = new BlockVector(minX, minY, minZ);
max = new BlockVector(maxX, maxY, maxZ);
}
/**
* @return the id
*/
@@ -91,14 +127,18 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
*
* @return min point
*/
public abstract BlockVector getMinimumPoint();
public BlockVector getMinimumPoint() {
return min;
}
/**
* Get the upper point of the cuboid.
*
* @return max point
*/
public abstract BlockVector getMaximumPoint();
public BlockVector getMaximumPoint() {
return max;
}
/**
* @return the priority
@@ -314,6 +354,13 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
this.flags = flags;
}
/**
* Gets the 2D points for this region
*
* @return
*/
public abstract List<BlockVector2D> getPoints();
/**
* Get the number of blocks in this region
*
@@ -330,21 +377,59 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
public abstract boolean contains(Vector pt);
/**
* Compares to another region.
* Check to see if a point is inside this region.
*
* @param pt
* @return
*/
public boolean contains(BlockVector2D pt) {
return contains(new Vector(pt.getBlockX(), min.getBlockY(), pt.getBlockZ()));
}
/**
* Check to see if a point is inside this region.
*
* @param x
* @param y
* @param z
* @return
*/
public boolean contains(int x, int y, int z) {
return contains(new Vector(x, y, z));
}
/**
* Check to see if any of the 2D points are inside this region.
*
* @param pts
* @return
*/
public boolean containsAny(List<BlockVector2D> pts) {
for (BlockVector2D pt : pts) {
if (contains(pt)) {
return true;
}
}
return false;
}
/**
* Compares to another region.<br>
*<br>
* Orders primarily by the priority, descending<br>
* Orders secondarily by the id, ascending
*
* @param other
* @return
*/
public int compareTo(ProtectedRegion other) {
if (id.equals(other.id)) {
return 0;
} else if (priority == other.priority) {
return 1;
} else if (priority > other.priority) {
if (priority > other.priority) {
return -1;
} else {
} else if (priority < other.priority) {
return 1;
}
return id.compareTo(other.id);
}
/**
@@ -365,6 +450,64 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
List<ProtectedRegion> regions)
throws UnsupportedIntersectionException;
/**
* Checks if the bounding box of a region intersects with with the bounding
* box of this region
*
* @param region
*/
protected boolean intersectsBoundingBox(ProtectedRegion region) {
BlockVector rMaxPoint = region.getMaximumPoint();
BlockVector min = getMinimumPoint();
if (rMaxPoint.getBlockX() < min.getBlockX()) return false;
if (rMaxPoint.getBlockY() < min.getBlockY()) return false;
if (rMaxPoint.getBlockZ() < min.getBlockZ()) return false;
BlockVector rMinPoint = region.getMinimumPoint();
BlockVector max = getMaximumPoint();
if (rMinPoint.getBlockX() > max.getBlockX()) return false;
if (rMinPoint.getBlockY() > max.getBlockY()) return false;
if (rMinPoint.getBlockZ() > max.getBlockZ()) return false;
return true;
}
/**
* Compares all edges of two regions to see if any of them intersect
*
* @param region
* @return
*/
protected boolean intersectsEdges(ProtectedRegion region) {
List<BlockVector2D> pts1 = getPoints();
List<BlockVector2D> pts2 = region.getPoints();
BlockVector2D lastPt1 = pts1.get(pts1.size() - 1);
BlockVector2D lastPt2 = pts2.get(pts2.size() - 1);
for (int i = 0; i < pts1.size(); i++ ) {
for (int j = 0; j < pts2.size(); j++) {
Line2D line1 = new Line2D.Double(
lastPt1.getBlockX(),
lastPt1.getBlockZ(),
pts1.get(i).getBlockX(),
pts1.get(i).getBlockZ());
if (line1.intersectsLine(
lastPt2.getBlockX(),
lastPt2.getBlockZ(),
pts2.get(j).getBlockX(),
pts2.get(j).getBlockZ())) {
return true;
}
lastPt2 = pts2.get(j);
}
lastPt1 = pts1.get(i);
}
return false;
}
/**
* Checks to see if the given ID is accurate.
*
@@ -0,0 +1,41 @@
/*
* WorldGuard
* Copyright (C) 2011 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.util;
import java.lang.reflect.Field;
/**
* @author zml2008
*/
public class ReflectionUtil {
@SuppressWarnings("unchecked")
public static <T> T getField(Object from, String name) {
Class<?> checkClass = from.getClass();
do {
try {
Field field = checkClass.getDeclaredField(name);
field.setAccessible(true);
return (T) field.get(from);
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
} while (checkClass.getSuperclass() != Object.class && ((checkClass = checkClass.getSuperclass()) != null));
return null;
}
}
@@ -1,204 +0,0 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.util.yaml;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.reader.UnicodeReader;
import org.yaml.snakeyaml.representer.Representer;
/**
* YAML configuration loader. To use this class, construct it with path to
* a file and call its load() method. For specifying node paths in the
* various get*() methods, they support SK's path notation, allowing you to
* select child nodes by delimiting node names with periods.
*
* <p>
* For example, given the following configuration file:</p>
*
* <pre>members:
* - Hollie
* - Jason
* - Bobo
* - Aya
* - Tetsu
* worldguard:
* fire:
* spread: false
* blocks: [cloth, rock, glass]
* sturmeh:
* cool: false
* eats:
* babies: true</pre>
*
* <p>Calling code could access sturmeh's baby eating state by using
* <code>getBoolean("sturmeh.eats.babies", false)</code>. For lists, there are
* methods such as <code>getStringList</code> that will return a type safe list.
*
* <p>This class is currently incomplete. It is not yet possible to get a node.
* </p>
*
* @author sk89q
*/
public class Configuration extends ConfigurationNode {
private Yaml yaml;
private File file;
private String header = null;
public Configuration(File file) {
super(new HashMap<String, Object>());
DumperOptions options = new DumperOptions();
options.setIndent(2);
options.setDefaultFlowStyle(DumperOptions.FlowStyle.AUTO);
yaml = new Yaml(new SafeConstructor(), new Representer(), options);
this.file = file;
}
/**
* Loads the configuration file.
*
* @throws IOException
*/
public void load() throws IOException {
FileInputStream stream = null;
try {
stream = new FileInputStream(file);
read(yaml.load(new UnicodeReader(stream)));
} catch (ConfigurationException e) {
root = new HashMap<String, Object>();
} finally {
try {
if (stream != null) {
stream.close();
}
} catch (IOException e) {
}
}
}
/**
* Set the header for the file as a series of lines that are terminated
* by a new line sequence.
*
* @param headerLines header lines to prepend
*/
public void setHeader(String... headerLines) {
StringBuilder header = new StringBuilder();
for (String line : headerLines) {
if (header.length() > 0) {
header.append("\r\n");
}
header.append(line);
}
setHeader(header.toString());
}
/**
* Set the header for the file. A header can be provided to prepend the
* YAML data output on configuration save. The header is
* printed raw and so must be manually commented if used. A new line will
* be appended after the header, however, if a header is provided.
*
* @param header header to prepend
*/
public void setHeader(String header) {
this.header = header;
}
/**
* Return the set header.
*
* @return
*/
public String getHeader() {
return header;
}
/**
* Saves the configuration to disk. All errors are clobbered.
*
* @return true if it was successful
*/
public boolean save() {
FileOutputStream stream = null;
File parent = file.getParentFile();
if (parent != null) {
parent.mkdirs();
}
try {
stream = new FileOutputStream(file);
OutputStreamWriter writer = new OutputStreamWriter(stream, "UTF-8");
if (header != null) {
writer.append(header);
writer.append("\r\n");
}
yaml.dump(root, writer);
return true;
} catch (IOException e) {} finally {
try {
if (stream != null) {
stream.close();
}
} catch (IOException e) {}
}
return false;
}
@SuppressWarnings("unchecked")
private void read(Object input) throws ConfigurationException {
try {
if ( null == input ) {
root = new HashMap<String, Object>();
} else {
root = (Map<String, Object>)input;
}
} catch (ClassCastException e) {
throw new ConfigurationException("Root document must be an key-value structure");
}
}
/**
* This method returns an empty ConfigurationNode for using as a
* default in methods that select a node from a node list.
* @return
*/
public static ConfigurationNode getEmptyNode() {
return new ConfigurationNode(new HashMap<String, Object>());
}
}
@@ -1,795 +0,0 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.util.yaml;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.sk89q.worldedit.BlockVector2D;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.Vector2D;
/**
* Represents a configuration node.
*
* @author sk89q
*/
public class ConfigurationNode {
protected Map<String, Object> root;
protected ConfigurationNode(Map<String, Object> root) {
this.root = root;
}
/**
* Clear all nodes.
*/
public void clear() {
root.clear();
}
/**
* Gets a property at a location. This will either return an Object
* or null, with null meaning that no configuration value exists at
* that location. This could potentially return a default value (not yet
* implemented) as defined by a plugin, if this is a plugin-tied
* configuration.
*
* @param path path to node (dot notation)
* @return object or null
*/
@SuppressWarnings("unchecked")
public Object getProperty(String path) {
if (!path.contains(".")) {
Object val = root.get(path);
if (val == null) {
return null;
}
return val;
}
String[] parts = path.split("\\.");
Map<String, Object> node = root;
for (int i = 0; i < parts.length; i++) {
Object o = node.get(parts[i]);
if (o == null) {
return null;
}
if (i == parts.length - 1) {
return o;
}
try {
node = (Map<String, Object>)o;
} catch (ClassCastException e) {
return null;
}
}
return null;
}
/**
* Prepare a value for serialization, in case it's not a native type
* (and we don't want to serialize objects as YAML objects).
*
* @param value
* @return
*/
private Object prepareSerialization(Object value) {
if (value instanceof Vector) {
Map<String, Double> out = new HashMap<String, Double>();
Vector vec = (Vector) value;
out.put("x", vec.getX());
out.put("y", vec.getY());
out.put("z", vec.getZ());
return out;
}
return value;
}
/**
* Set the property at a location. This will override existing
* configuration data to have it conform to key/value mappings.
*
* @param path
* @param value
*/
@SuppressWarnings("unchecked")
public void setProperty(String path, Object value) {
value = prepareSerialization(value);
if (!path.contains(".")) {
root.put(path, value);
return;
}
String[] parts = path.split("\\.");
Map<String, Object> node = root;
for (int i = 0; i < parts.length; i++) {
Object o = node.get(parts[i]);
// Found our target!
if (i == parts.length - 1) {
node.put(parts[i], value);
return;
}
if (o == null || !(o instanceof Map)) {
// This will override existing configuration data!
o = new HashMap<String, Object>();
node.put(parts[i], o);
}
node = (Map<String, Object>)o;
}
}
/**
* Adds a new node to the given path. The returned object is a reference
* to the new node. This method will replace an existing node at
* the same path. See <code>setProperty</code>.
*
* @param path
* @return
*/
public ConfigurationNode addNode(String path) {
Map<String, Object> map = new HashMap<String, Object>();
ConfigurationNode node = new ConfigurationNode(map);
setProperty(path, map);
return node;
}
/**
* Gets a string at a location. This will either return an String
* or null, with null meaning that no configuration value exists at
* that location. If the object at the particular location is not actually
* a string, it will be converted to its string representation.
*
* @param path path to node (dot notation)
* @return string or null
*/
public String getString(String path) {
Object o = getProperty(path);
if (o == null) {
return null;
}
return o.toString();
}
/**
* Gets a vector at a location. This will either return an Vector
* or a null. If the object at the particular location is not
* actually a string, it will be converted to its string representation.
*
* @param path path to node (dot notation)
* @return string or default
*/
public Vector getVector(String path) {
ConfigurationNode o = getNode(path);
if (o == null) {
return null;
}
Double x = o.getDouble("x");
Double y = o.getDouble("y");
Double z = o.getDouble("z");
if (x == null || y == null || z == null) {
return null;
}
return new Vector(x, y, z);
}
/**
* Gets a 2D vector at a location. This will either return an Vector
* or a null. If the object at the particular location is not
* actually a string, it will be converted to its string representation.
*
* @param path path to node (dot notation)
* @return string or default
*/
public Vector2D getVector2d(String path) {
ConfigurationNode o = getNode(path);
if (o == null) {
return null;
}
Double x = o.getDouble("x");
Double z = o.getDouble("z");
if (x == null || z == null) {
return null;
}
return new Vector2D(x, z);
}
/**
* Gets a string at a location. This will either return an Vector
* or the default value. If the object at the particular location is not
* actually a string, it will be converted to its string representation.
*
* @param path path to node (dot notation)
* @param def default value
* @return string or default
*/
public Vector getVector(String path, Vector def) {
Vector v = getVector(path);
if (v == null) {
setProperty(path, def);
return def;
}
return v;
}
/**
* Gets a string at a location. This will either return an String
* or the default value. If the object at the particular location is not
* actually a string, it will be converted to its string representation.
*
* @param path path to node (dot notation)
* @param def default value
* @return string or default
*/
public String getString(String path, String def) {
String o = getString(path);
if (o == null) {
setProperty(path, def);
return def;
}
return o;
}
/**
* Gets an integer at a location. This will either return an integer
* or null. If the object at the particular location is not
* actually a integer, the default value will be returned. However, other
* number types will be casted to an integer.
*
* @param path path to node (dot notation)
* @return integer or null
*/
public Integer getInt(String path) {
Integer o = castInt(getProperty(path));
if (o == null) {
return null;
} else {
return o;
}
}
/**
* Gets an integer at a location. This will either return an integer
* or the default value. If the object at the particular location is not
* actually a integer, the default value will be returned. However, other
* number types will be casted to an integer.
*
* @param path path to node (dot notation)
* @param def default value
* @return int or default
*/
public int getInt(String path, int def) {
Integer o = castInt(getProperty(path));
if (o == null) {
setProperty(path, def);
return def;
} else {
return o;
}
}
/**
* Gets a double at a location. This will either return an double
* or null. If the object at the particular location is not
* actually a double, the default value will be returned. However, other
* number types will be casted to an double.
*
* @param path path to node (dot notation)
* @return double or null
*/
public Double getDouble(String path) {
Double o = castDouble(getProperty(path));
if (o == null) {
return null;
} else {
return o;
}
}
/**
* Gets a double at a location. This will either return an double
* or the default value. If the object at the particular location is not
* actually a double, the default value will be returned. However, other
* number types will be casted to an double.
*
* @param path path to node (dot notation)
* @param def default value
* @return double or default
*/
public double getDouble(String path, double def) {
Double o = castDouble(getProperty(path));
if (o == null) {
setProperty(path, def);
return def;
} else {
return o;
}
}
/**
* Gets a boolean at a location. This will either return an boolean
* or null. If the object at the particular location is not
* actually a boolean, the default value will be returned.
*
* @param path path to node (dot notation)
* @return boolean or null
*/
public Boolean getBoolean(String path) {
Boolean o = castBoolean(getProperty(path));
if (o == null) {
return null;
} else {
return o;
}
}
/**
* Gets a boolean at a location. This will either return an boolean
* or the default value. If the object at the particular location is not
* actually a boolean, the default value will be returned.
*
* @param path path to node (dot notation)
* @param def default value
* @return boolean or default
*/
public boolean getBoolean(String path, boolean def) {
Boolean o = castBoolean(getProperty(path));
if (o == null) {
setProperty(path, def);
return def;
} else {
return o;
}
}
/**
* Get a list of keys at a location. If the map at the particular location
* does not exist or it is not a map, null will be returned.
*
* @param path path to node (dot notation)
* @return list of keys
*/
@SuppressWarnings("unchecked")
public List<String> getKeys(String path) {
if (path == null) return new ArrayList<String>(root.keySet());
Object o = getProperty(path);
if (o == null) {
return null;
} else if (o instanceof Map) {
return new ArrayList<String>(((Map<String,Object>)o).keySet());
} else {
return null;
}
}
/**
* Gets a list of objects at a location. If the list is not defined,
* null will be returned. The node must be an actual list.
*
* @param path path to node (dot notation)
* @return boolean or default
*/
@SuppressWarnings("unchecked")
public List<Object> getList(String path) {
Object o = getProperty(path);
if (o == null) {
return null;
} else if (o instanceof List) {
return (List<Object>)o;
} else {
return null;
}
}
/**
* Gets a list of strings. Non-valid entries will not be in the list.
* There will be no null slots. If the list is not defined, the
* default will be returned. 'null' can be passed for the default
* and an empty list will be returned instead. If an item in the list
* is not a string, it will be converted to a string. The node must be
* an actual list and not just a string.
*
* @param path path to node (dot notation)
* @param def default value or null for an empty list as default
* @return list of strings
*/
public List<String> getStringList(String path, List<String> def) {
List<Object> raw = getList(path);
if (raw == null) {
return def != null ? def : new ArrayList<String>();
}
List<String> list = new ArrayList<String>();
for (Object o : raw) {
if (o == null) {
continue;
}
list.add(o.toString());
}
return list;
}
/**
* Gets a list of integers. Non-valid entries will not be in the list.
* There will be no null slots. If the list is not defined, the
* default will be returned. 'null' can be passed for the default
* and an empty list will be returned instead. The node must be
* an actual list and not just an integer.
*
* @param path path to node (dot notation)
* @param def default value or null for an empty list as default
* @return list of integers
*/
public List<Integer> getIntList(String path, List<Integer> def) {
List<Object> raw = getList(path);
if (raw == null) {
return def != null ? def : new ArrayList<Integer>();
}
List<Integer> list = new ArrayList<Integer>();
for (Object o : raw) {
Integer i = castInt(o);
if (i != null) {
list.add(i);
}
}
return list;
}
/**
* Gets a list of doubles. Non-valid entries will not be in the list.
* There will be no null slots. If the list is not defined, the
* default will be returned. 'null' can be passed for the default
* and an empty list will be returned instead. The node must be
* an actual list and cannot be just a double.
*
* @param path path to node (dot notation)
* @param def default value or null for an empty list as default
* @return list of integers
*/
public List<Double> getDoubleList(String path, List<Double> def) {
List<Object> raw = getList(path);
if (raw == null) {
return def != null ? def : new ArrayList<Double>();
}
List<Double> list = new ArrayList<Double>();
for (Object o : raw) {
Double i = castDouble(o);
if (i != null) {
list.add(i);
}
}
return list;
}
/**
* Gets a list of booleans. Non-valid entries will not be in the list.
* There will be no null slots. If the list is not defined, the
* default will be returned. 'null' can be passed for the default
* and an empty list will be returned instead. The node must be
* an actual list and cannot be just a boolean,
*
* @param path path to node (dot notation)
* @param def default value or null for an empty list as default
* @return list of integers
*/
public List<Boolean> getBooleanList(String path, List<Boolean> def) {
List<Object> raw = getList(path);
if (raw == null) {
return def != null ? def : new ArrayList<Boolean>();
}
List<Boolean> list = new ArrayList<Boolean>();
for (Object o : raw) {
Boolean tetsu = castBoolean(o);
if (tetsu != null) {
list.add(tetsu);
}
}
return list;
}
/**
* Gets a list of vectors. Non-valid entries will not be in the list.
* There will be no null slots. If the list is not defined, the
* default will be returned. 'null' can be passed for the default
* and an empty list will be returned instead. The node must be
* an actual node and cannot be just a vector,
*
* @param path path to node (dot notation)
* @param def default value or null for an empty list as default
* @return list of integers
*/
public List<Vector> getVectorList(
String path, List<Vector> def) {
List<ConfigurationNode> raw = getNodeList(path, null);
List<Vector> list = new ArrayList<Vector>();
for (ConfigurationNode o : raw) {
Double x = o.getDouble("x");
Double y = o.getDouble("y");
Double z = o.getDouble("z");
if (x == null || y == null || z == null) {
continue;
}
list.add(new Vector(x, y, z));
}
return list;
}
/**
* Gets a list of 2D vectors. Non-valid entries will not be in the list.
* There will be no null slots. If the list is not defined, the
* default will be returned. 'null' can be passed for the default
* and an empty list will be returned instead. The node must be
* an actual node and cannot be just a vector,
*
* @param path path to node (dot notation)
* @param def default value or null for an empty list as default
* @return list of integers
*/
public List<Vector2D> getVector2dList(
String path, List<Vector2D> def) {
List<ConfigurationNode> raw = getNodeList(path, null);
List<Vector2D> list = new ArrayList<Vector2D>();
for (ConfigurationNode o : raw) {
Double x = o.getDouble("x");
Double z = o.getDouble("z");
if (x == null || z == null) {
continue;
}
list.add(new Vector2D(x, z));
}
return list;
}
/**
* Gets a list of 2D vectors. Non-valid entries will not be in the list.
* There will be no null slots. If the list is not defined, the
* default will be returned. 'null' can be passed for the default
* and an empty list will be returned instead. The node must be
* an actual node and cannot be just a vector,
*
* @param path path to node (dot notation)
* @param def default value or null for an empty list as default
* @return list of integers
*/
public List<BlockVector2D> getBlockVector2dList(
String path, List<BlockVector2D> def) {
List<ConfigurationNode> raw = getNodeList(path, null);
List<BlockVector2D> list = new ArrayList<BlockVector2D>();
for (ConfigurationNode o : raw) {
Double x = o.getDouble("x");
Double z = o.getDouble("z");
if (x == null || z == null) {
continue;
}
list.add(new BlockVector2D(x, z));
}
return list;
}
/**
* Gets a list of nodes. Non-valid entries will not be in the list.
* There will be no null slots. If the list is not defined, the
* default will be returned. 'null' can be passed for the default
* and an empty list will be returned instead. The node must be
* an actual node and cannot be just a boolean,
*
* @param path path to node (dot notation)
* @param def default value or null for an empty list as default
* @return list of integers
*/
@SuppressWarnings("unchecked")
public List<ConfigurationNode> getNodeList(String path, List<ConfigurationNode> def) {
List<Object> raw = getList(path);
if (raw == null) {
return def != null ? def : new ArrayList<ConfigurationNode>();
}
List<ConfigurationNode> list = new ArrayList<ConfigurationNode>();
for (Object o : raw) {
if (o instanceof Map) {
list.add(new ConfigurationNode((Map<String, Object>)o));
}
}
return list;
}
/**
* Get a configuration node at a path. If the node doesn't exist or the
* path does not lead to a node, null will be returned. A node has
* key/value mappings.
*
* @param path
* @return node or null
*/
@SuppressWarnings("unchecked")
public ConfigurationNode getNode(String path) {
Object raw = getProperty(path);
if (raw instanceof Map) {
return new ConfigurationNode((Map<String, Object>)raw);
}
return null;
}
/**
* Get a list of nodes at a location. If the map at the particular location
* does not exist or it is not a map, null will be returned.
*
* @param path path to node (dot notation)
* @return map of nodes
*/
@SuppressWarnings("unchecked")
public Map<String, ConfigurationNode> getNodes(String path) {
Object o = getProperty(path);
if (o == null) {
return null;
} else if (o instanceof Map) {
Map<String, ConfigurationNode> nodes =
new HashMap<String, ConfigurationNode>();
for (Map.Entry<String, Object> entry : ((Map<String, Object>)o).entrySet()) {
if (entry.getValue() instanceof Map) {
nodes.put(entry.getKey(),
new ConfigurationNode((Map<String, Object>) entry.getValue()));
}
}
return nodes;
} else {
return null;
}
}
/**
* Casts a value to an integer. May return null.
*
* @param o
* @return
*/
private static Integer castInt(Object o) {
if (o == null) {
return null;
} else if (o instanceof Byte) {
return (int)(Byte)o;
} else if (o instanceof Integer) {
return (Integer)o;
} else if (o instanceof Double) {
return (int)(double)(Double)o;
} else if (o instanceof Float) {
return (int)(float)(Float)o;
} else if (o instanceof Long) {
return (int)(long)(Long)o;
} else {
return null;
}
}
/**
* Casts a value to a double. May return null.
*
* @param o
* @return
*/
private static Double castDouble(Object o) {
if (o == null) {
return null;
} else if (o instanceof Float) {
return (double)(Float)o;
} else if (o instanceof Double) {
return (Double)o;
} else if (o instanceof Byte) {
return (double)(Byte)o;
} else if (o instanceof Integer) {
return (double)(Integer)o;
} else if (o instanceof Long) {
return (double)(Long)o;
} else {
return null;
}
}
/**
* Casts a value to a boolean. May return null.
*
* @param o
* @return
*/
private static Boolean castBoolean(Object o) {
if (o == null) {
return null;
} else if (o instanceof Boolean) {
return (Boolean)o;
} else {
return null;
}
}
/**
* Remove the property at a location. This will override existing
* configuration data to have it conform to key/value mappings.
*
* @param path
*/
@SuppressWarnings("unchecked")
public void removeProperty(String path) {
if (!path.contains(".")) {
root.remove(path);
return;
}
String[] parts = path.split("\\.");
Map<String, Object> node = root;
for (int i = 0; i < parts.length; i++) {
Object o = node.get(parts[i]);
// Found our target!
if (i == parts.length - 1) {
node.remove(parts[i]);
return;
}
node = (Map<String, Object>)o;
}
}
}
+1 -42
View File
@@ -1,45 +1,4 @@
name: WorldGuard
main: com.sk89q.worldguard.bukkit.WorldGuardPlugin
version: "${project.version}"
commands:
stopfire:
description: Halts all fire spread until it is disabled or the server is restarted
usage: /<command>
allowfire:
description: Re-enables fire spread if he has been disabled with /stopfire
usage: /<command>
halt-activity:
aliases: [stoplag, haltactivity]
description: Attempts to stop all intensive operations (toggle)
usage: /<command> [-c]
god:
description: Enable god mode
usage: /<command> [player]
ungod:
description: Disable god mode
usage: /<command> [player]
heal:
description: Heal yourself or another
usage: /<command> [player]
slay:
description: Slay yourself or another
usage: /<command> [player]
stack:
description: Stacks items in the player's inventory
usage: /<command>
aliases: ;
region:
description: Adjust protected regions
usage: /<command> <action> ...
aliases: [rg, regions]
flushstates:
descripton: Clear state manager.
usage: /<command> [player]
aliases: clearstates
locate:
description: Set your compass towards a person
usage: /<command> <target>
worldguard:
description: WorldGuard commands
aliases: wg
usage: /<command>
softdepend: [WorldEdit, CommandBook]
@@ -0,0 +1,82 @@
package com.sk89q.worldguard.protection;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.BlockVector2D;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import org.junit.Test;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
public class RegionIntersectTest {
@Test
public void testCuboidGetIntersectingRegions() {
ProtectedRegion region = new ProtectedCuboidRegion("square",
new BlockVector(100, 40, 0), new BlockVector(140, 128, 40));
assertIntersection(region, new ProtectedCuboidRegion("normal",
new BlockVector(80, 40, -20), new BlockVector(120, 128, 20)),
true);
assertIntersection(region, new ProtectedCuboidRegion("small",
new BlockVector(98, 45, 20), new BlockVector(103, 50, 25)),
true);
assertIntersection(region, new ProtectedCuboidRegion("large",
new BlockVector(-500, 0, -600), new BlockVector(1000, 128, 1000)),
true);
assertIntersection(region, new ProtectedCuboidRegion("short",
new BlockVector(50, 40, -1), new BlockVector(150, 128, 2)),
true);
assertIntersection(region, new ProtectedCuboidRegion("long",
new BlockVector(0, 40, 5), new BlockVector(1000, 128, 8)),
true);
List<BlockVector2D> triangle_overlap = new ArrayList<BlockVector2D>();
triangle_overlap.add(new BlockVector2D(90, -10));
triangle_overlap.add(new BlockVector2D(120, -10));
triangle_overlap.add(new BlockVector2D(90, 20));
assertIntersection(region, new ProtectedPolygonalRegion("triangle_overlap",
triangle_overlap, 0, 128),
true);
List<BlockVector2D> triangle_no_overlap = new ArrayList<BlockVector2D>();
triangle_no_overlap.add(new BlockVector2D(90, -10));
triangle_no_overlap.add(new BlockVector2D(105, -10));
triangle_no_overlap.add(new BlockVector2D(90, 5));
assertIntersection(region, new ProtectedPolygonalRegion("triangle_no_overlap",
triangle_no_overlap, 0, 128),
false);
List<BlockVector2D> triangle_overlap_no_points = new ArrayList<BlockVector2D>();
triangle_overlap_no_points.add(new BlockVector2D(100, -10));
triangle_overlap_no_points.add(new BlockVector2D(120, 50));
triangle_overlap_no_points.add(new BlockVector2D(140, -20));
assertIntersection(region, new ProtectedPolygonalRegion("triangle_overlap_no_points",
triangle_overlap_no_points, 60, 80),
true);
}
private void assertIntersection(ProtectedRegion region1, ProtectedRegion region2, boolean expected) {
boolean actual = false;
List<ProtectedRegion> regions = new ArrayList<ProtectedRegion>();
regions.add(region2);
try {
actual = (region1.getIntersectingRegions(regions).size() == 1);
} catch (Exception e) {
e.printStackTrace();
}
assertEquals("Check for '" + region2.getId() + "' region failed.", expected, actual);
}
}