Compare commits

...
36 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
52 changed files with 2457 additions and 1849 deletions

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
*.java diff=java
+25
View File
@@ -1,3 +1,28 @@
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
+19 -6
View File
@@ -7,7 +7,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.sk89q</groupId>
<artifactId>worldguard</artifactId>
<version>5.4</version>
<version>5.5</version>
<name>WorldGuard</name>
<description>WorldGuard protects your Minecraft servers</description>
@@ -18,6 +18,11 @@
</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>
@@ -26,7 +31,7 @@
<!-- Repository for Bukkit -->
<repository>
<id>bukkit-repo</id>
<url>http://repo.bukkit.org/artifactory/repo</url>
<url>http://repo.bukkit.org/content/groups/public</url>
</repository>
</repositories>
@@ -35,14 +40,21 @@
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldedit</artifactId>
<version>4.7</version>
<version>5.2</version>
</dependency>
<!-- Bukkit -->
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.0.0-R1-SNAPSHOT</version>
<version>1.1-R3</version>
</dependency>
<!-- CommandBook -->
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>commandbook</artifactId>
<version>2.0</version>
</dependency>
<!-- Additional libraries -->
@@ -115,7 +127,7 @@
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
</manifest>
<manifestEntries>
<Class-Path>WorldEdit.jar WorldGuard/WorldEdit.jar lib/WorldEdit.jar ../lib/WorldEdit.jar ../WorldEdit.jar</Class-Path>
<Class-Path>WorldGuard/WorldEdit.jar lib/WorldEdit.jar ../lib/WorldEdit.jar ../WorldEdit.jar</Class-Path>
</manifestEntries>
</archive>
</configuration>
@@ -167,10 +179,11 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.1</version>
<version>2.2.2</version>
<configuration>
<preparationGoals>assembly:assembly</preparationGoals>
<goals>assembly:assembly</goals>
<tagNameFormat>@{project.version}</tagNameFormat>
</configuration>
</plugin>
</plugins>
+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;
@@ -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;
}
}
@@ -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;
}
@@ -31,10 +31,11 @@ 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;
@@ -63,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;
@@ -80,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;
@@ -101,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;
@@ -163,25 +155,26 @@ public class WorldConfiguration {
/**
* 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) {
@@ -280,17 +273,20 @@ public class WorldConfiguration {
* 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);
@@ -314,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);
@@ -380,7 +371,7 @@ public class WorldConfiguration {
}
}
}
// useiConomy = getBoolean("iconomy.enable", false);
// buyOnClaim = getBoolean("iconomy.buy-on-claim", false);
// buyOnClaimPrice = getDouble("iconomy.buy-on-claim-price", 1.0);
@@ -390,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);
}
@@ -430,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.");
}
}
@@ -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;
@@ -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,7 +56,6 @@ 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;
@@ -65,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;
@@ -79,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;
@@ -100,45 +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);
registerEvent("FOOD_LEVEL_CHANGE", 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();
@@ -146,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);
}
@@ -156,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("");
@@ -198,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;
}
@@ -322,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;
}
}
}
}
@@ -420,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;
@@ -461,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;
@@ -501,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;
@@ -525,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;
@@ -543,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;
}
@@ -555,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;
}
@@ -572,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;
}
@@ -588,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;
}
}
@@ -598,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;
}
}
@@ -609,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;
@@ -629,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;
@@ -675,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;
@@ -692,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;
@@ -709,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;
@@ -752,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;
@@ -786,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;
@@ -806,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;
@@ -834,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;
@@ -859,7 +870,7 @@ public class WorldGuardEntityListener extends EntityListener {
}
}
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onFoodLevelChange(FoodLevelChangeEvent event) {
if (event.getEntity() instanceof Player) {
Player player = (Player) event.getEntity();
@@ -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;
@@ -72,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;
@@ -94,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.Highest);
registerEvent("PLAYER_ITEM_HELD", Priority.High);
registerEvent("PLAYER_BED_ENTER", Priority.High);
registerEvent("PLAYER_COMMAND_PREPROCESS", Priority.Lowest);
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();
@@ -177,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());
}
}
@@ -187,7 +257,7 @@ public class WorldGuardPlayerListener extends PlayerListener {
+ "Fire spread is currently globally disabled for this world.");
}
if (cfg.autoGodMode && (plugin.inGroup(player, "wg-invincible")
if (!cfg.hasCommandBookGodMode() && cfg.autoGodMode && (plugin.inGroup(player, "wg-invincible")
|| plugin.hasPermission(player, "worldguard.auto-invincible"))) {
cfg.enableGodMode(player);
}
@@ -209,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();
@@ -254,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();
@@ -284,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.
@@ -419,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();
@@ -431,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)) {
@@ -446,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);
@@ -457,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),
@@ -513,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();
@@ -521,14 +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
|| type == Material.BREWING_STAND
|| type == Material.ENCHANTMENT_TABLE
|| type == Material.CAULDRON)
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++) {
@@ -546,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"));
@@ -568,7 +524,7 @@ public class WorldGuardPlayerListener extends PlayerListener {
return;
}
if (item.getType() == Material.TNT) {
if (item.getTypeId() == BlockID.TNT) {
Block placedOn = block.getRelative(event.getBlockFace());
if (!plugin.getGlobalRegionManager().hasBypass(player, world)
&& !plugin.getGlobalRegionManager().allows(
@@ -578,10 +534,10 @@ public class WorldGuardPlayerListener extends PlayerListener {
}
}
if (item.getType() == Material.INK_SACK
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);
@@ -589,7 +545,7 @@ public class WorldGuardPlayerListener extends PlayerListener {
}
}
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.");
@@ -599,12 +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
|| type == Material.BREWING_STAND) {
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)) {
@@ -615,23 +571,23 @@ public class WorldGuardPlayerListener extends PlayerListener {
}
}
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.JUKEBOX //stores the (arguably) most valuable item
|| type == Material.DISPENSER
|| type == Material.FURNACE
|| type == Material.BURNING_FURNACE
|| type == Material.WORKBENCH
|| type == Material.BREWING_STAND
|| type == Material.ENCHANTMENT_TABLE
|| type == Material.CAULDRON
|| type == Material.DRAGON_EGG) {
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)) {
@@ -642,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!");
@@ -652,7 +608,7 @@ public class WorldGuardPlayerListener extends PlayerListener {
}
}
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)) {
@@ -663,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)) {
@@ -676,13 +632,13 @@ public class WorldGuardPlayerListener extends PlayerListener {
}
if (wcfg.getBlacklist() != null) {
if(type != Material.CHEST
&& type != Material.DISPENSER
&& type != Material.FURNACE
&& type != Material.BURNING_FURNACE
&& type != Material.BREWING_STAND
&& type != Material.ENCHANTMENT_TABLE
&& type != Material.CAULDRON) {
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)) {
@@ -701,7 +657,7 @@ public class WorldGuardPlayerListener extends PlayerListener {
}
// Workaround for http://leaky.bukkit.org/issues/1034
if (item.getType() == Material.TNT) {
if (item.getTypeId() == BlockID.TNT) {
Block placedOn = block.getRelative(event.getBlockFace());
if (!wcfg.getBlacklist().check(
new BlockPlaceBlacklistEvent(plugin.wrapPlayer(player), toVector(placedOn),
@@ -713,12 +669,12 @@ public class WorldGuardPlayerListener extends PlayerListener {
}
}
if ((type == Material.CHEST
|| type == Material.DISPENSER
|| type == Material.FURNACE
|| type == Material.BURNING_FURNACE
|| type == Material.ENCHANTMENT_TABLE
|| type == Material.BREWING_STAND)) {
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.");
@@ -729,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]")
@@ -784,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;
}
@@ -805,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)) {
@@ -851,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);
}
@@ -887,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;
@@ -911,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;
@@ -935,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();
@@ -943,7 +899,7 @@ public class WorldGuardPlayerListener extends PlayerListener {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (event.getItemStack().getType() == Material.MILK_BUCKET) {
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);
@@ -970,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();
@@ -998,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();
@@ -1033,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();
@@ -1054,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;
@@ -1083,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();
@@ -24,7 +24,6 @@ import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
@@ -34,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;
@@ -45,14 +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.minecraft.util.commands.Injector;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.TickSyncDelayLoggerFilter;
@@ -68,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,
@@ -90,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.
*/
@@ -110,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
@@ -118,35 +100,37 @@ public class WorldGuardPlugin extends JavaPlugin {
return plugin.hasPermission(player, perm);
}
};
commands.setInjector(new Injector() {
public Object getInstance(Class<?> cls) throws InvocationTargetException, IllegalAccessException, InstantiationException {
try {
return cls.getConstructor(WorldGuardPlugin.class).newInstance(plugin);
} catch (NoSuchMethodException e) {
e.printStackTrace();
return null;
}
}
});
// 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
@@ -179,6 +163,7 @@ 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));
@@ -187,15 +172,15 @@ public class WorldGuardPlugin extends JavaPlugin {
}
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.");
}
/**
@@ -205,8 +190,6 @@ public class WorldGuardPlugin extends JavaPlugin {
globalRegionManager.unload();
configuration.unload();
this.getServer().getScheduler().cancelTasks(this);
logger.info("WorldGuard " + getDescription().getVersion() + " disabled.");
}
/**
@@ -285,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;
@@ -300,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];
@@ -358,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;
@@ -702,7 +685,7 @@ public class WorldGuardPlugin extends JavaPlugin {
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) {
@@ -716,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();
}
}
@@ -14,12 +14,10 @@ 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;
@@ -28,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;
@@ -50,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();
@@ -104,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());
}
@@ -39,6 +39,7 @@ public class GeneralCommands {
this.plugin = plugin;
}
@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 {
@@ -84,6 +85,7 @@ public class GeneralCommands {
}
}
@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 {
@@ -34,11 +34,11 @@ public class ProtectionCommands {
this.plugin = plugin;
}
@Command(aliases = {"region"}, desc = "Region management 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"}, desc = "WorldGuard commands")
@Command(aliases = {"worldguard", "wg"}, desc = "WorldGuard commands")
@NestedCommand({WorldGuardCommands.class})
public void worldGuard(CommandContext args, CommandSender sender) {}
}
+81 -23
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,11 +54,18 @@ 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;
public RegionCommands(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@@ -118,8 +126,8 @@ 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());
}
}
@@ -192,8 +200,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());
}
}
@@ -323,8 +331,8 @@ 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());
}
}
@@ -681,8 +689,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());
}
}
@@ -730,8 +738,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());
}
}
@@ -801,8 +809,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());
}
}
@@ -839,8 +847,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());
}
}
@@ -862,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 {
@@ -872,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());
}
}
@@ -900,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 {
@@ -910,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());
}
}
@@ -920,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;
@@ -35,6 +33,7 @@ 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.
@@ -78,8 +77,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());
}
}
@@ -129,8 +128,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());
}
}
@@ -167,8 +166,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());
}
}
@@ -206,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());
}
}
@@ -97,7 +97,7 @@ public class ToggleCommands {
wcfg.fireSpreadDisableToggle = false;
}
@Command(aliases = {"halt-activity"},
@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 void stopLag(CommandContext args, CommandSender sender) throws CommandException {
@@ -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,30 +133,44 @@ 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) { // this should no longer happen hopefully
logger.info("WorldGuard: Region file for world \""
+ name + "\" missing or inaccessible.");
} catch (IOException e) {
logger.info("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.info("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!!one!!1!!eleven!!1!!!
@@ -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,30 +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) {
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) {}
// if this is thrown, we can't do anything (caught elsewhere anyway)
} catch (IOException e) {
throw new FileNotFoundException(file.getAbsolutePath());
}
}
config = new Configuration(file);
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) {
@@ -76,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;
@@ -147,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;
}
@@ -171,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();
}
@@ -189,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,
@@ -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);
}
@@ -414,21 +414,22 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
}
/**
* Compares to another region.
* 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);
}
/**
@@ -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 -43
View File
@@ -1,46 +1,4 @@
name: WorldGuard
main: com.sk89q.worldguard.bukkit.WorldGuardPlugin
version: "${project.version}"
softdepend: [WorldEdit]
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]