Major work towards 1.13 compat

This commit is contained in:
Matthew Miller 2018-07-20 00:06:02 +10:00
parent 8eeab682db
commit 6c5319f355
336 changed files with 3694 additions and 2936 deletions

View File

@ -26,9 +26,9 @@ buildscript {
}
dependencies {
classpath 'com.github.jengelman.gradle.plugins:shadow:1.2.1'
classpath 'org.jfrog.buildinfo:build-info-extractor-gradle:3.0.1'
classpath 'org.ajoberstar:gradle-git:0.12.0'
classpath 'com.github.jengelman.gradle.plugins:shadow:1.2.3'
classpath 'org.jfrog.buildinfo:build-info-extractor-gradle:4.7.5'
classpath 'org.ajoberstar:gradle-git:1.7.2'
}
}
@ -50,7 +50,7 @@ subprojects {
apply plugin: 'maven'
apply plugin: 'checkstyle'
apply plugin: 'com.github.johnrengelman.shadow'
apply plugin: 'com.jfrog.artifactory-upload'
apply plugin: 'com.jfrog.artifactory'
group = 'com.sk89q.worldguard'
version = '7.0.0-SNAPSHOT'
@ -62,6 +62,7 @@ subprojects {
checkstyle.configFile = new File(rootProject.projectDir, "config/checkstyle/checkstyle.xml")
repositories {
mavenLocal()
mavenCentral()
maven { url "http://repo.spongepowered.org/maven/" }
maven { url "https://hub.spigotmc.org/nexus/content/groups/public" }
@ -101,6 +102,10 @@ subprojects {
classifier 'dist'
dependencies {
include(dependency('org.khelekore:prtree:1.5.0'))
include(dependency('com.sk89q:squirrelid:0.1.0'))
include(dependency('org.flywaydb:flyway-core:3.0'))
include(dependency('com.googlecode.json-simple:json-simple:1.1.1'))
include(dependency('net.sf.opencsv:opencsv:2.0'))
}
exclude 'GradleStart**'
exclude '.cache'

View File

@ -27,7 +27,6 @@
<property name="max" value="2"/>
</module>
<module name="SuperFinalize"/> <!-- We don't actually use this -->
<module name="JUnitTestCase"/> <!-- Checks tearDown(), setUp() etc. -->
<!-- Style -->
<module name="LeftCurly"> <!-- Left brace never goes on another line -->

View File

@ -14,6 +14,8 @@
<subpackage name="worldguard">
<allow pkg="org.khelekore"/>
<allow pkg="org.flywaydb"/>
<allow pkg="org.yaml"/>
<allow pkg="org.json"/>
<subpackage name="bukkit">
<allow pkg="org.bukkit"/>

Binary file not shown.

View File

@ -1,6 +1,5 @@
#Fri Nov 13 12:12:21 EST 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.8-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.0-bin.zip

110
gradlew vendored
View File

@ -1,4 +1,4 @@
#!/usr/bin/env bash
#!/usr/bin/env sh
##############################################################################
##
@ -6,47 +6,6 @@
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# For Cygwin, ensure paths are in UNIX format before anything is touched.
if $cygwin ; then
[ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
fi
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
@ -61,9 +20,49 @@ while [ -h "$PRG" ] ; do
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >&-
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >&-
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
@ -90,7 +89,7 @@ location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
@ -114,6 +113,7 @@ fi
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
@ -154,11 +154,19 @@ if $cygwin ; then
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
APP_ARGS=$(save "$@")
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

14
gradlew.bat vendored
View File

@ -8,14 +8,14 @@
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
@ -46,10 +46,9 @@ echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
@ -60,11 +59,6 @@ set _SKIP=2
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line

View File

@ -2,11 +2,14 @@ apply plugin: 'eclipse'
apply plugin: 'idea'
dependencies {
compile 'com.sk89q.worldedit:worldedit-core:6.1.1-SNAPSHOT'
compile 'com.sk89q.worldedit:worldedit-core:7.0.0-SNAPSHOT'
compile 'com.sk89q.intake:intake:4.2-SNAPSHOT'
compile 'com.sk89q:squirrelid:0.1.0'
compile 'org.flywaydb:flyway-core:3.0'
compile 'org.khelekore:prtree:1.5.0'
compile 'net.sf.opencsv:opencsv:2.0'
compile 'com.googlecode.json-simple:json-simple:1.1.1'
compile 'com.google.code.findbugs:jsr305:1.3.9'
}
sourceSets {

View File

@ -0,0 +1,63 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC
"-//Puppy Crawl//DTD Check Configuration 1.3//EN"
"http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<module name="Checker">
<!-- Tabs are strictly banned -->
<module name="FileTabCharacter"/>
<module name="TreeWalker">
<!-- Important basics -->
<!-- <module name="PackageDeclaration"/> Unlikely that we would miss this in a PR -->
<module name="OuterTypeFilename"/> <!-- TypeName -> TypeName.java -->
<!--
Control package usage, so people don't insert Bukkit into WE where it shouldn't belong, etc.
It is a bit draconian, so update as necessary!
-->
<module name="ImportControl">
<property name="file" value="worldguard-core/config/checkstyle/import-control.xml"/>
</module>
<!-- Code -->
<module name="HideUtilityClassConstructor"/> <!-- Utility classes should not have a constructor -->
<module name="CovariantEquals"/>
<module name="EqualsHashCode"/> <!-- equals() and hashCode() go together -->
<module name="NestedTryDepth"> <!-- SHOULD not need to adjust this -->
<property name="max" value="2"/>
</module>
<module name="SuperFinalize"/> <!-- We don't actually use this -->
<!-- Style -->
<module name="LeftCurly"> <!-- Left brace never goes on another line -->
<property name="option" value="eol"/>
</module> <!-- We don't check right brace -->
<module name="DefaultComesLast"/> <!-- default case in switch should be last -->
<module name="GenericWhitespace"/>
<!-- Naming -->
<module name="ClassTypeParameterName">
<property name="format" value="^[A-Z][a-zA-Z0-9]*$"/>
</module>
<module name="LocalFinalVariableName"/>
<module name="LocalVariableName">
<property name="format" value="^[a-z_][a-zA-Z0-9]*$"/>
</module>
<module name="MemberName">
<property name="format" value="^[a-z_][a-zA-Z0-9]*$"/>
</module>
<module name="MethodName">
<property name="format" value="^[a-z][a-zA-Z0-9]*$"/>
</module>
<!-- <module name="PackageName"/> Unlikely that we would miss this in a PR -->
<module name="ParameterName"/>
<!-- <module name="TypeName"/> Unlikely that we would miss this in a PR -->
</module>
<!-- Require the header, something that many people forget and we hate to fix -->
<!-- You should configure the header in your IDE -->
<module name="Header">
<property name="headerFile" value="config/checkstyle/header.txt"/>
<property name="fileExtensions" value="java"/>
</module>
</module>

View File

@ -0,0 +1,40 @@
<!--
~ WorldGuard, a suite of tools for Minecraft
~ Copyright (C) sk89q <http://www.sk89q.com>
~ Copyright (C) WorldGuard team and contributors
~
~ This program is free software: you can redistribute it and/or modify it
~ under the terms of the GNU Lesser 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 Lesser General Public License
~ for more details.
~
~ You should have received a copy of the GNU Lesser General Public License
~ along with this program. If not, see <http://www.gnu.org/licenses/>.
-->
<!DOCTYPE import-control PUBLIC
"-//Puppy Crawl//DTD Import Control 1.1//EN"
"http://www.puppycrawl.com/dtds/import_control_1_1.dtd">
<import-control pkg="com.sk89q">
<allow pkg="java"/>
<allow pkg="javax"/>
<allow pkg="org.junit"/>
<allow pkg="junit"/>
<allow pkg="org.mockito"/>
<allow pkg="org.hamcrest"/>
<allow pkg="com.sk89q"/>
<allow pkg="org.enginehub"/>
<allow pkg="org.yaml.snakeyaml"/>
<allow pkg="au.com.bytecode.opencsv"/>
<allow pkg="org.khelekore.prtree"/>
<allow pkg="com.google.common"/>
<allow pkg="com.jolbox.bonecp"/>
<allow pkg="org.flywaydb.core"/>
<allow pkg="org.json.simple"/>
</import-control>

View File

@ -0,0 +1,163 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser 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 Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard;
import com.sk89q.worldedit.extension.platform.AbstractPlayerActor;
import com.sk89q.worldedit.world.weather.WeatherType;
import com.sk89q.worldguard.domains.Association;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import java.util.List;
public abstract class LocalPlayer extends AbstractPlayerActor implements RegionAssociable {
/**
* Returns true if this player is inside a group.
*
* @param group The group to check
* @return Whether this player is in {@code group}
*/
public abstract boolean hasGroup(String group);
/**
* Kick this player.
*
* @param msg The message to kick the player with
*/
public abstract void kick(String msg);
/**
* Ban this player.
*
* @param msg The message to ban the player with
*/
public abstract void ban(String msg);
@Override
public Association getAssociation(List<ProtectedRegion> regions) {
boolean member = false;
for (ProtectedRegion region : regions) {
if (region.isOwner(this)) {
return Association.OWNER;
} else if (!member && region.isMember(this)) {
member = true;
}
}
return member ? Association.MEMBER : Association.NON_MEMBER;
}
/**
* Gets the health of this player.
*
* @return The health
*/
public abstract double getHealth();
/**
* Sets the health of this player.
*
* @param health The health
*/
public abstract void setHealth(double health);
/**
* Gets the max health of this player.
*
* @return The max health
*/
public abstract double getMaxHealth();
/**
* Gets the food level of this player.
*
* @return The food level
*/
public abstract double getFoodLevel();
/**
* Sets the food level of this player.
*
* @param foodLevel The food level
*/
public abstract void setFoodLevel(double foodLevel);
/**
* Gets the saturation of this player.
*
* @return The saturation
*/
public abstract double getSaturation();
/**
* Sets the saturation of this player.
*
* @param saturation The saturation
*/
public abstract void setSaturation(double saturation);
/**
* Gets the players weather
*
* @return The players weather
*/
public abstract WeatherType getPlayerWeather();
/**
* Sets the players WeatherType
*
* @param weather The weather type
*/
public abstract void setPlayerWeather(WeatherType weather);
/**
* Resets the players weather to normal.
*/
public abstract void resetPlayerWeather();
/**
* Gets if the players time is relative.
*
* @return If the time is relative
*/
public abstract boolean isPlayerTimeRelative();
/**
* Gets the time offset of the player.
*
* @return The players time offset
*/
public abstract long getPlayerTimeOffset();
/**
* Sets the players time.
*
* @param time The players time
* @param relative If it's relative
*/
public abstract void setPlayerTime(long time, boolean relative);
/**
* Resets the players time to normal.
*/
public abstract void resetPlayerTime();
}

View File

@ -0,0 +1,69 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser 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 Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard;
import static com.google.common.base.Preconditions.checkNotNull;
import com.sk89q.worldguard.internal.platform.WorldGuardPlatform;
import com.sk89q.worldguard.protection.flags.registry.FlagRegistry;
import com.sk89q.worldguard.protection.flags.registry.SimpleFlagRegistry;
import java.util.logging.Logger;
public class WorldGuard {
public static final Logger logger = Logger.getLogger(WorldGuard.class.getCanonicalName());
private static final WorldGuard instance = new WorldGuard();
private WorldGuardPlatform platform;
private final SimpleFlagRegistry flagRegistry = new SimpleFlagRegistry();
public static WorldGuard getInstance() {
return instance;
}
public WorldGuard() {
flagRegistry.setInitialized(true);
}
/**
* The WorldGuard Platform.
*
* @return The platform
*/
public WorldGuardPlatform getPlatform() {
checkNotNull(platform);
return platform;
}
public void setPlatform(WorldGuardPlatform platform) {
checkNotNull(platform);
this.platform = platform;
}
/**
* Get the flag registry.
*
* @return the flag registry
*/
public FlagRegistry getFlagRegistry() {
return this.flagRegistry;
}
}

View File

@ -19,6 +19,10 @@
package com.sk89q.worldguard.blacklist;
import com.sk89q.worldedit.util.formatting.ColorCodeBuilder;
import com.sk89q.worldedit.util.formatting.Style;
import com.sk89q.worldedit.util.formatting.StyledFragment;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.blacklist.action.Action;
import com.sk89q.worldguard.blacklist.action.ActionType;
import com.sk89q.worldguard.blacklist.event.BlacklistEvent;
@ -29,8 +33,6 @@ import com.sk89q.worldguard.blacklist.target.TargetMatcherParser;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.sk89q.worldguard.bukkit.commands.CommandUtils;
import org.bukkit.ChatColor;
import java.io.BufferedReader;
import java.io.File;
@ -42,7 +44,7 @@ import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
public abstract class Blacklist {
public class Blacklist {
private static final Logger log = Logger.getLogger(Blacklist.class.getCanonicalName());
@ -133,12 +135,10 @@ public abstract class Blacklist {
* @throws IOException if an error occurred reading from the file
*/
public void load(File file) throws IOException {
FileReader input = null;
MatcherIndex.Builder builder = new MatcherIndex.Builder();
TargetMatcherParser targetMatcherParser = new TargetMatcherParser();
try {
input = new FileReader(file);
try (FileReader input = new FileReader(file)) {
BufferedReader buff = new BufferedReader(input);
String line;
@ -155,7 +155,7 @@ public abstract class Blacklist {
if (line.matches("^\\[.*\\]$")) {
String[] items = line.substring(1, line.length() - 1).split(",");
currentEntries = new ArrayList<BlacklistEntry>();
currentEntries = new ArrayList<>();
for (String item : items) {
try {
@ -185,10 +185,10 @@ public abstract class Blacklist {
entry.setIgnorePermissions(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("message")) {
entry.setMessage(CommandUtils.replaceColorMacros(parts[1].trim()));
entry.setMessage(WorldGuard.getInstance().getPlatform().replaceColorMacros(parts[1].trim()));
} else if (parts[0].equalsIgnoreCase("comment")) {
entry.setComment(CommandUtils.replaceColorMacros(parts[1].trim()));
entry.setComment(WorldGuard.getInstance().getPlatform().replaceColorMacros(parts[1].trim()));
} else {
boolean found = false;
@ -217,19 +217,12 @@ public abstract class Blacklist {
}
this.index = builder.build();
} finally {
try {
if (input != null) {
input.close();
}
} catch (IOException ignore) {
}
}
}
private List<Action> parseActions(BlacklistEntry entry, String raw) {
String[] split = raw.split(",");
List<Action> actions = new ArrayList<Action>();
List<Action> actions = new ArrayList<>();
for (String name : split) {
name = name.trim();
@ -270,12 +263,11 @@ public abstract class Blacklist {
public void notify(BlacklistEvent event, String comment) {
lastEvent = event;
broadcastNotification(ChatColor.GRAY + "WG: "
+ ChatColor.LIGHT_PURPLE + event.getCauseName()
+ ChatColor.GOLD + " (" + event.getDescription() + ") "
+ ChatColor.WHITE
+ event.getTarget().getFriendlyName()
+ (comment != null ? " (" + comment + ")" : "") + ".");
StyledFragment fragment = new StyledFragment().append(new StyledFragment(Style.GRAY).append("WG: "))
.append(new StyledFragment(Style.PURPLE).append(event.getCauseName()))
.append(new StyledFragment(Style.YELLOW_DARK).append(" (" + event.getDescription() + ") "))
.append(new StyledFragment(Style.WHITE).append(event.getTarget().getFriendlyName() + (comment != null ? " (" + comment + ")" : "") + "."));
broadcastNotification(ColorCodeBuilder.asColorCodes(fragment));
}
/**
@ -283,7 +275,9 @@ public abstract class Blacklist {
*
* @param msg The message to broadcast
*/
public abstract void broadcastNotification(String msg);
public void broadcastNotification(String msg) {
WorldGuard.getInstance().getPlatform().broadcastNotification(msg);
}
public LoadingCache<String, TrackedEvent> getRepeatingEventCache() {
return repeatingEventCache;

View File

@ -33,7 +33,7 @@ public class BlacklistEntry {
private Blacklist blacklist;
private Set<String> ignoreGroups;
private Set<String> ignorePermissions;
private Map<Class<? extends BlacklistEvent>, List<Action>> actions = new HashMap<Class<? extends BlacklistEvent>, List<Action>>();
private Map<Class<? extends BlacklistEvent>, List<Action>> actions = new HashMap<>();
private String message;
private String comment;
@ -146,12 +146,7 @@ public class BlacklistEntry {
* @return The actions for the given event
*/
public List<Action> getActions(Class<? extends BlacklistEvent> eventCls) {
List<Action> ret = actions.get(eventCls);
if (ret == null) {
ret = new ArrayList<Action>();
actions.put(eventCls, ret);
}
return ret;
return actions.computeIfAbsent(eventCls, k -> new ArrayList<>());
}
/**

View File

@ -31,7 +31,7 @@ public class BlacklistLoggerHandler implements LoggerHandler {
* List of logger handlers.
*/
private Set<LoggerHandler> handlers
= new HashSet<LoggerHandler>();
= new HashSet<>();
/**
* Add a handler.

View File

@ -32,16 +32,16 @@ import static com.google.common.base.Preconditions.checkNotNull;
class MatcherIndex {
private static final MatcherIndex EMPTY_INSTANCE = new MatcherIndex(HashBasedTable.<Integer, TargetMatcher, BlacklistEntry>create());
private final Table<Integer, TargetMatcher, BlacklistEntry> entries;
private static final MatcherIndex EMPTY_INSTANCE = new MatcherIndex(HashBasedTable.create());
private final Table<String, TargetMatcher, BlacklistEntry> entries;
private MatcherIndex(Table<Integer, TargetMatcher, BlacklistEntry> entries) {
private MatcherIndex(Table<String, TargetMatcher, BlacklistEntry> entries) {
checkNotNull(entries);
this.entries = entries;
}
public List<BlacklistEntry> getEntries(Target target) {
List<BlacklistEntry> found = new ArrayList<BlacklistEntry>();
List<BlacklistEntry> found = new ArrayList<>();
for (Entry<TargetMatcher, BlacklistEntry> entry : entries.row(target.getTypeId()).entrySet()) {
if (entry.getKey().test(target)) {
found.add(entry.getValue());
@ -63,7 +63,7 @@ class MatcherIndex {
}
public static class Builder {
private final Table<Integer, TargetMatcher, BlacklistEntry> entries = HashBasedTable.create();
private final Table<String, TargetMatcher, BlacklistEntry> entries = HashBasedTable.create();
public Builder add(TargetMatcher matcher, BlacklistEntry entry) {
checkNotNull(matcher);

View File

@ -21,7 +21,6 @@ package com.sk89q.worldguard.blacklist.action;
import com.sk89q.worldguard.blacklist.BlacklistEntry;
import com.sk89q.worldguard.blacklist.event.BlacklistEvent;
import org.bukkit.ChatColor;
import static com.google.common.base.Preconditions.checkNotNull;
@ -44,10 +43,9 @@ public class TellAction extends RepeatGuardedAction {
if (event.getPlayer() != null) {
if (message != null) {
event.getPlayer().printRaw(ChatColor.YELLOW + String.format(message, event.getTarget().getFriendlyName()));
event.getPlayer().print(String.format(message, event.getTarget().getFriendlyName()));
} else {
event.getPlayer().printRaw(ChatColor.YELLOW + "You're not allowed to " + event.getDescription() + " " +
event.getTarget().getFriendlyName() + ".");
event.getPlayer().printError("You're not allowed to " + event.getDescription() + " " + event.getTarget().getFriendlyName() + ".");
}
}

View File

@ -45,7 +45,7 @@ abstract class ItemBlacklistEvent extends AbstractBlacklistEvent {
@Override
public Vector getLoggedPosition() {
return getPlayer() != null ? getPlayer().getPosition() : getPosition();
return getPlayer() != null ? getPlayer().getLocation().toVector() : getPosition();
}
}

View File

@ -19,7 +19,6 @@
package com.sk89q.worldguard.blacklist.logger;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldguard.blacklist.event.BlacklistEvent;
import java.util.logging.Level;
@ -41,21 +40,6 @@ public class ConsoleHandler implements LoggerHandler {
(comment != null ? " (" + comment + ")" : ""));
}
/**
* Get an item's friendly name with its ID.
*
* @param id The item id
* @return The friendly name of the item
*/
private static String getFriendlyItemName(int id) {
ItemType type = ItemType.fromID(id);
if (type != null) {
return type.getName() + " (#" + id + ")";
} else {
return "#" + id;
}
}
@Override
public void close() {
}

View File

@ -84,7 +84,7 @@ public class DatabaseHandler implements LoggerHandler {
* @param item The item used
* @param comment The comment associated with the event
*/
private void logEvent(EventType eventType, @Nullable LocalPlayer player, Vector pos, int item, String comment) {
private void logEvent(EventType eventType, @Nullable LocalPlayer player, Vector pos, String item, String comment) {
try {
Connection conn = getConnection();
PreparedStatement stmt = conn.prepareStatement(
@ -97,7 +97,7 @@ public class DatabaseHandler implements LoggerHandler {
stmt.setInt(4, pos.getBlockX());
stmt.setInt(5, pos.getBlockY());
stmt.setInt(6, pos.getBlockZ());
stmt.setInt(7, item);
stmt.setString(7, item);
stmt.setInt(8, (int)(System.currentTimeMillis() / 1000));
stmt.setString(9, comment);
stmt.executeUpdate();

View File

@ -20,7 +20,6 @@
package com.sk89q.worldguard.blacklist.logger;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.event.BlacklistEvent;
import com.sk89q.worldguard.blacklist.target.Target;
@ -231,21 +230,6 @@ public class FileHandler implements LoggerHandler {
logEvent(event, event.getDescription(), event.getTarget(), event.getPosition(), comment);
}
/**
* Get an item's friendly name with its ID.
*
* @param id The id to get a friendly name for
* @return The friendly name
*/
private static String getFriendlyItemName(int id) {
ItemType type = ItemType.fromID(id);
if (type != null) {
return type.getName() + " (#" + id + ")";
} else {
return "#" + id + "";
}
}
@Override
public void close() {
for (Map.Entry<String,LogFileWriter> entry : writers.entrySet()) {

View File

@ -17,23 +17,26 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit.internal;
package com.sk89q.worldguard.blacklist.target;
import com.sk89q.worldguard.blacklist.Blacklist;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldedit.world.item.ItemType;
public class BukkitBlacklist extends Blacklist {
public class ItemMatcher implements TargetMatcher {
private WorldGuardPlugin plugin;
public BukkitBlacklist(Boolean useAsWhitelist, WorldGuardPlugin plugin) {
super(useAsWhitelist);
this.plugin = plugin;
private final ItemType type;
public ItemMatcher(ItemType type) {
this.type = type;
}
@Override
public void broadcastNotification(String msg) {
plugin.broadcastNotification(msg);
public String getMatchedTypeId() {
return this.type.getId();
}
@Override
public boolean test(Target target) {
return target.getTypeId().equals(getMatchedTypeId());
}
}

View File

@ -19,22 +19,24 @@
package com.sk89q.worldguard.blacklist.target;
public class WildcardDataMatcher implements TargetMatcher {
import com.sk89q.worldedit.world.item.ItemType;
private final int typeId;
public class ItemTarget implements Target {
public WildcardDataMatcher(int typeId) {
this.typeId = typeId;
private ItemType type;
public ItemTarget(ItemType type) {
this.type = type;
}
@Override
public int getMatchedTypeId() {
return typeId;
public String getTypeId() {
return type.getId();
}
@Override
public boolean test(Target target) {
return target.getTypeId() == typeId;
public String getFriendlyName() {
return type.getName();
}
}

View File

@ -29,14 +29,7 @@ public interface Target {
*
* @return the type ID
*/
int getTypeId();
/**
* Get the data value.
*
* @return the data value
*/
short getData();
String getTypeId();
/**
* Get a friendly name to be printed.

View File

@ -29,7 +29,7 @@ public interface TargetMatcher {
*
* @return the type ID
*/
int getMatchedTypeId();
String getMatchedTypeId();
/**
* Return whether the given target is matched by this matcher.

View File

@ -19,36 +19,22 @@
package com.sk89q.worldguard.blacklist.target;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldedit.world.item.ItemType;
import com.sk89q.worldedit.world.item.ItemTypes;
public class MaterialTarget implements Target {
public class TargetMatcherParser {
private int id;
private short data;
public MaterialTarget(int id, short data) {
this.id = id;
this.data = data;
public TargetMatcher fromInput(String input) throws TargetMatcherParseException {
return new ItemMatcher(parseType(input));
}
@Override
public int getTypeId() {
return id;
}
private ItemType parseType(String input) throws TargetMatcherParseException {
input = input.trim();
@Override
public short getData() {
return data;
}
@Override
public String getFriendlyName() {
ItemType type = ItemType.fromID(id);
if (type != null) {
return type.getName() + " (#" + id + ":" + data + ")";
} else {
return "#" + id + ":" + data;
ItemType itemType = ItemTypes.get(input);
if (itemType == null) {
throw new TargetMatcherParseException("Unknown block or item name: " + input);
}
return itemType;
}
}

View File

@ -0,0 +1,171 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser 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 Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.config;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.protection.managers.storage.DriverType;
import com.sk89q.worldguard.protection.managers.storage.RegionDriver;
import com.sk89q.worldguard.session.handler.WaterBreathing;
import com.sk89q.worldguard.util.report.Unreported;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
/**
* Represents the global configuration and also delegates configuration
* for individual worlds.
*
* @author sk89q
* @author Michael
*/
public abstract class ConfigurationManager {
protected static final Logger log = Logger.getLogger(ConfigurationManager.class.getCanonicalName());
static final String CONFIG_HEADER = "#\r\n" +
"# WorldGuard's main configuration file\r\n" +
"#\r\n" +
"# This is the global configuration file. Anything placed into here will\r\n" +
"# be applied to all worlds. However, each world has its own configuration\r\n" +
"# file to allow you to replace most settings in here for that world only.\r\n" +
"#\r\n" +
"# About editing this file:\r\n" +
"# - DO NOT USE TABS. You MUST use spaces or Bukkit will complain. If\r\n" +
"# you use an editor like Notepad++ (recommended for Windows users), you\r\n" +
"# must configure it to \"replace tabs with spaces.\" In Notepad++, this can\r\n" +
"# be changed in Settings > Preferences > Language Menu.\r\n" +
"# - Don't get rid of the indents. They are indented so some entries are\r\n" +
"# in categories (like \"enforce-single-session\" is in the \"protection\"\r\n" +
"# category.\r\n" +
"# - If you want to check the format of this file before putting it\r\n" +
"# into WorldGuard, paste it into http://yaml-online-parser.appspot.com/\r\n" +
"# and see if it gives \"ERROR:\".\r\n" +
"# - Lines starting with # are comments and so they are ignored.\r\n" +
"#\r\n";
private boolean hasCommandBookGodMode = false;
public boolean useRegionsCreatureSpawnEvent;
public boolean activityHaltToggle = false;
public boolean useGodPermission;
public boolean useGodGroup;
public boolean useAmphibiousGroup;
public boolean usePlayerMove;
public boolean usePlayerTeleports;
public boolean deopOnJoin;
public boolean blockInGameOp;
public boolean migrateRegionsToUuid;
public boolean keepUnresolvedNames;
@Unreported public Map<String, String> hostKeys = new HashMap<>();
public boolean hostKeysAllowFMLClients;
/**
* Region Storage Configuration method, and config values
*/
@Unreported public RegionDriver selectedRegionStoreDriver;
@Unreported public Map<DriverType, RegionDriver> regionStoreDriverMap;
/**
* Get the folder for storing data files and configuration.
*
* @return the data folder
*/
public abstract File getDataFolder();
/**
* Get the folder for storing data files and configuration for each
* world.
*
* @return the data folder
*/
public File getWorldsDataFolder() {
return new File(getDataFolder(), "worlds");
}
/**
* Load the configuration.
*/
public abstract void load();
/**
* Unload the configuration.
*/
public abstract void unload();
/**
* Get the configuration for a world.
*
* @param world The world to get the configuration for
* @return {@code world}'s configuration
*/
public abstract WorldConfiguration get(World world);
public abstract void disableUuidMigration();
/**
* Check to see if god mode is enabled for a player.
*
* @param player The player to check
* @return Whether the player has godmode through WorldGuard or CommandBook
*/
public boolean hasGodMode(LocalPlayer player) {
return WorldGuard.getInstance().getPlatform().getSessionManager().get(player).isInvincible(player);
}
/**
* Enable amphibious mode for a player.
*
* @param player The player to enable amphibious mode for
*/
public void enableAmphibiousMode(LocalPlayer player) {
WaterBreathing handler = WorldGuard.getInstance().getPlatform().getSessionManager().get(player).getHandler(WaterBreathing.class);
if (handler != null) {
handler.setWaterBreathing(true);
}
}
/**
* Disable amphibious mode for a player.
*
* @param player The player to disable amphibious mode for
*/
public void disableAmphibiousMode(LocalPlayer player) {
WaterBreathing handler = WorldGuard.getInstance().getPlatform().getSessionManager().get(player).getHandler(WaterBreathing.class);
if (handler != null) {
handler.setWaterBreathing(false);
}
}
/**
* Check to see if amphibious mode is enabled for a player.
*
* @param player The player to check
* @return Whether {@code player} has amphibious mode
*/
public boolean hasAmphibiousMode(LocalPlayer player) {
WaterBreathing handler = WorldGuard.getInstance().getPlatform().getSessionManager().get(player).getHandler(WaterBreathing.class);
return handler != null && handler.hasWaterBreathing();
}
}

View File

@ -0,0 +1,69 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser 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 Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.config;
import com.sk89q.worldguard.blacklist.Blacklist;
import com.sk89q.worldguard.util.report.Unreported;
import java.io.File;
import java.util.logging.Logger;
/**
* Holds the configuration for individual worlds.
*
* @author sk89q
* @author Michael
*/
public abstract class WorldConfiguration {
public static final Logger log = Logger.getLogger(WorldConfiguration.class.getCanonicalName());
public static final String CONFIG_HEADER = "#\r\n" +
"# WorldGuard's world configuration file\r\n" +
"#\r\n" +
"# This is a world configuration file. Anything placed into here will only\r\n" +
"# affect this world. If you don't put anything in this file, then the\r\n" +
"# settings will be inherited from the main configuration file.\r\n" +
"#\r\n" +
"# If you see {} below, that means that there are NO entries in this file.\r\n" +
"# Remove the {} and add your own entries.\r\n" +
"#\r\n";
@Unreported private String worldName;
protected File blacklistFile;
@Unreported protected Blacklist blacklist;
public boolean boundedLocationFlags;
public boolean useRegions;
/**
* Load the configuration.
*/
public abstract void loadConfiguration();
public Blacklist getBlacklist() {
return this.blacklist;
}
public String getWorldName() {
return this.worldName;
}
}

View File

@ -0,0 +1,120 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser 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 Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.config;
import com.google.common.collect.ImmutableMap;
import com.sk89q.util.yaml.YAMLFormat;
import com.sk89q.util.yaml.YAMLProcessor;
import com.sk89q.worldguard.protection.managers.storage.DriverType;
import com.sk89q.worldguard.protection.managers.storage.RegionDriver;
import com.sk89q.worldguard.protection.managers.storage.file.DirectoryYamlDriver;
import com.sk89q.worldguard.protection.managers.storage.sql.SQLDriver;
import com.sk89q.worldguard.util.report.Unreported;
import com.sk89q.worldguard.util.sql.DataSourceConfig;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public abstract class YamlConfigurationManager extends ConfigurationManager {
@Unreported private YAMLProcessor config;
public abstract void copyDefaults();
@Override
public void load() {
copyDefaults();
config = new YAMLProcessor(new File(getDataFolder(), "config.yml"), true, YAMLFormat.EXTENDED);
try {
config.load();
} catch (IOException e) {
log.severe("Error reading configuration for global config: ");
e.printStackTrace();
}
config.removeProperty("suppress-tick-sync-warnings");
migrateRegionsToUuid = config.getBoolean("regions.uuid-migration.perform-on-next-start", true);
keepUnresolvedNames = config.getBoolean("regions.uuid-migration.keep-names-that-lack-uuids", true);
useRegionsCreatureSpawnEvent = config.getBoolean("regions.use-creature-spawn-event", true);
useGodPermission = config.getBoolean("auto-invincible", config.getBoolean("auto-invincible-permission", false));
useGodGroup = config.getBoolean("auto-invincible-group", false);
useAmphibiousGroup = config.getBoolean("auto-no-drowning-group", false);
config.removeProperty("auto-invincible-permission");
usePlayerMove = config.getBoolean("use-player-move-event", true);
usePlayerTeleports = config.getBoolean("use-player-teleports", true);
deopOnJoin = config.getBoolean("security.deop-everyone-on-join", false);
blockInGameOp = config.getBoolean("security.block-in-game-op-command", false);
hostKeys = new HashMap<>();
Object hostKeysRaw = config.getProperty("host-keys");
if (!(hostKeysRaw instanceof Map)) {
config.setProperty("host-keys", new HashMap<String, String>());
} else {
for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) hostKeysRaw).entrySet()) {
String key = String.valueOf(entry.getKey());
String value = String.valueOf(entry.getValue());
hostKeys.put(key.toLowerCase(), value);
}
}
hostKeysAllowFMLClients = config.getBoolean("security.host-keys-allow-forge-clients", false);
// ====================================================================
// Region store drivers
// ====================================================================
boolean useSqlDatabase = config.getBoolean("regions.sql.use", false);
String sqlDsn = config.getString("regions.sql.dsn", "jdbc:mysql://localhost/worldguard");
String sqlUsername = config.getString("regions.sql.username", "worldguard");
String sqlPassword = config.getString("regions.sql.password", "worldguard");
String sqlTablePrefix = config.getString("regions.sql.table-prefix", "");
DataSourceConfig dataSourceConfig = new DataSourceConfig(sqlDsn, sqlUsername, sqlPassword, sqlTablePrefix);
SQLDriver sqlDriver = new SQLDriver(dataSourceConfig);
DirectoryYamlDriver yamlDriver = new DirectoryYamlDriver(getWorldsDataFolder(), "regions.yml");
this.regionStoreDriverMap = ImmutableMap.<DriverType, RegionDriver>builder()
.put(DriverType.MYSQL, sqlDriver)
.put(DriverType.YAML, yamlDriver)
.build();
this.selectedRegionStoreDriver = useSqlDatabase ? sqlDriver : yamlDriver;
postLoad();
config.setHeader(CONFIG_HEADER);
}
public void postLoad() {}
public YAMLProcessor getConfig() {
return config;
}
@Override
public void disableUuidMigration() {
config.setProperty("regions.uuid-migration.perform-on-next-start", false);
if (!config.save()) {
log.severe("Error saving configuration!");
}
}
}

View File

@ -0,0 +1,125 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser 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 Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.config;
import com.sk89q.util.yaml.YAMLProcessor;
import com.sk89q.worldguard.util.report.Unreported;
import java.util.ArrayList;
import java.util.List;
public abstract class YamlWorldConfiguration extends WorldConfiguration {
@Unreported private YAMLProcessor parentConfig;
@Unreported private YAMLProcessor config;
public boolean getBoolean(String node, boolean def) {
boolean val = parentConfig.getBoolean(node, def);
if (config.getProperty(node) != null) {
return config.getBoolean(node, def);
} else {
return val;
}
}
public String getString(String node, String def) {
String val = parentConfig.getString(node, def);
if (config.getProperty(node) != null) {
return config.getString(node, def);
} else {
return val;
}
}
public int getInt(String node, int def) {
int val = parentConfig.getInt(node, def);
if (config.getProperty(node) != null) {
return config.getInt(node, def);
} else {
return val;
}
}
@SuppressWarnings("unused")
private double getDouble(String node, double def) {
double val = parentConfig.getDouble(node, def);
if (config.getProperty(node) != null) {
return config.getDouble(node, def);
} else {
return val;
}
}
public List<Integer> getIntList(String node, List<Integer> def) {
List<Integer> res = parentConfig.getIntList(node, def);
if (res == null || res.size() == 0) {
parentConfig.setProperty(node, new ArrayList<Integer>());
}
if (config.getProperty(node) != null) {
res = config.getIntList(node, def);
}
return res;
}
public List<String> getStringList(String node, List<String> def) {
List<String> res = parentConfig.getStringList(node, def);
if (res == null || res.size() == 0) {
parentConfig.setProperty(node, new ArrayList<String>());
}
if (config.getProperty(node) != null) {
res = config.getStringList(node, def);
}
return res;
}
public List<String> getKeys(String node) {
List<String> res = parentConfig.getKeys(node);
if (res == null || res.size() == 0) {
res = config.getKeys(node);
}
if (res == null) {
res = new ArrayList<String>();
}
return res;
}
public Object getProperty(String node) {
Object res = parentConfig.getProperty(node);
if (config.getProperty(node) != null) {
res = config.getProperty(node);
}
return res;
}
}

View File

@ -34,7 +34,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
*/
public class GroupDomain implements Domain, ChangeTracked {
private final Set<String> groups = new CopyOnWriteArraySet<String>();
private final Set<String> groups = new CopyOnWriteArraySet<>();
private boolean dirty = true;
/**

View File

@ -34,8 +34,8 @@ import static com.google.common.base.Preconditions.checkNotNull;
*/
public class PlayerDomain implements Domain, ChangeTracked {
private final Set<UUID> uniqueIds = new CopyOnWriteArraySet<UUID>();
private final Set<String> names = new CopyOnWriteArraySet<String>();
private final Set<UUID> uniqueIds = new CopyOnWriteArraySet<>();
private final Set<String> names = new CopyOnWriteArraySet<>();
private boolean dirty = true;
/**

View File

@ -17,32 +17,25 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit.permission;
package com.sk89q.worldguard.internal.permission;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import org.bukkit.command.CommandSender;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldguard.internal.PermissionModel;
abstract class AbstractPermissionModel implements PermissionModel {
public abstract class AbstractPermissionModel implements PermissionModel {
private final WorldGuardPlugin plugin;
private final CommandSender sender;
private final Actor sender;
public AbstractPermissionModel(WorldGuardPlugin plugin, CommandSender sender) {
this.plugin = plugin;
public AbstractPermissionModel(Actor sender) {
this.sender = sender;
}
protected WorldGuardPlugin getPlugin() {
return plugin;
}
public CommandSender getSender() {
public Actor getSender() {
return sender;
}
protected boolean hasPluginPermission(String permission) {
return plugin.hasPermission(getSender(), "worldguard." + permission);
return getSender().hasPermission("worldguard." + permission);
}
}

View File

@ -17,15 +17,14 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit.permission;
package com.sk89q.worldguard.internal.permission;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.internal.permission.AbstractPermissionModel;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import javax.annotation.Nullable;
@ -34,8 +33,8 @@ import javax.annotation.Nullable;
*/
public class RegionPermissionModel extends AbstractPermissionModel {
public RegionPermissionModel(WorldGuardPlugin plugin, CommandSender sender) {
super(plugin, sender);
public RegionPermissionModel(Actor sender) {
super(sender);
}
public boolean mayIgnoreRegionProtection(World world) {
@ -171,18 +170,17 @@ public class RegionPermissionModel extends AbstractPermissionModel {
* @param region the region
*/
private boolean hasPatternPermission(String perm, ProtectedRegion region) {
if (!(getSender() instanceof Player)) {
if (!(getSender() instanceof LocalPlayer)) {
return true; // Non-players (i.e. console, command blocks, etc.) have full power
}
LocalPlayer localPlayer = getPlugin().wrapPlayer((Player) getSender());
String idLower = region.getId().toLowerCase();
String effectivePerm;
if (region.isOwner(localPlayer)) {
if (region.isOwner((LocalPlayer) getSender())) {
return hasPluginPermission("region." + perm + ".own." + idLower) ||
hasPluginPermission("region." + perm + ".member." + idLower);
} else if (region.isMember(localPlayer)) {
} else if (region.isMember((LocalPlayer) getSender())) {
return hasPluginPermission("region." + perm + ".member." + idLower);
} else {
effectivePerm = "region." + perm + "." + idLower;

View File

@ -0,0 +1,117 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser 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 Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.internal.platform;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.gamemode.GameMode;
import com.sk89q.worldguard.config.ConfigurationManager;
import com.sk89q.worldguard.protection.flags.FlagContext;
import com.sk89q.worldguard.protection.regions.RegionContainer;
import com.sk89q.worldguard.session.SessionManager;
/**
* A platform for implementing.
*/
public interface WorldGuardPlatform {
/**
* Notifies the platform when a flag context is created.
*
* @param flagContextBuilder The flag context
*/
void notifyFlagContextCreate(FlagContext.FlagContextBuilder flagContextBuilder);
/**
* Get the global ConfigurationManager.
* Use this to access global configuration values and per-world configuration values.
*
* @return The global ConfigurationManager
*/
ConfigurationManager getGlobalStateManager();
/**
* Gets a world by name, if possible.
*
* @param worldName The name
* @return The world
*/
World getWorldByName(String worldName);
/**
* Replaces colour macros.
*
* @param string The string
* @return The replaced string
*/
String replaceColorMacros(String string);
/**
* Replace macros in the text.
*
* The macros replaced are as follows:
* %name%: The name of {@code sender}.
* %id%: The unique name of the sender.
* %online%: The number of players currently online on the server
* If {@code sender} is a Player:
* %world%: The name of the world {@code sender} is located in
* %health%: The health of {@code sender}.
*
* @param sender The sender to check
* @param message The message to replace macros in
* @return The message with macros replaced
*/
String replaceMacros(Actor sender, String message);
/**
* Gets the session manager.
*
* @return The session manager
*/
SessionManager getSessionManager();
/**
* Notifies all with the worldguard.notify permission.
* This will check both superperms and WEPIF,
* but makes sure WEPIF checks don't result in duplicate notifications
*
* @param message The notification to broadcast
*/
void broadcastNotification(String message);
/**
* Unload the platform
*/
void unload();
/**
* Gets a RegionContainer.
*
* @return The region container
*/
RegionContainer getRegionContainer();
/**
* Gets the servers default game mode.
*
* @return The default game mode
*/
GameMode getDefaultGameMode();
}

View File

@ -21,7 +21,7 @@ package com.sk89q.worldguard.protection;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.flags.StateFlag.State;
@ -37,7 +37,7 @@ public abstract class AbstractRegionSet implements ApplicableRegionSet {
@Deprecated
public boolean canBuild(LocalPlayer player) {
checkNotNull(player);
return test(queryState(player, DefaultFlag.BUILD));
return test(queryState(player, Flags.BUILD));
}
@Override
@ -65,7 +65,7 @@ public abstract class AbstractRegionSet implements ApplicableRegionSet {
public boolean allows(StateFlag flag) {
checkNotNull(flag);
if (flag == DefaultFlag.BUILD) {
if (flag == Flags.BUILD) {
throw new IllegalArgumentException("Can't use build flag with allows()");
}
@ -77,7 +77,7 @@ public abstract class AbstractRegionSet implements ApplicableRegionSet {
public boolean allows(StateFlag flag, @Nullable LocalPlayer player) {
checkNotNull(flag);
if (flag == DefaultFlag.BUILD) {
if (flag == Flags.BUILD) {
throw new IllegalArgumentException("Can't use build flag with allows()");
}

View File

@ -20,9 +20,8 @@
package com.sk89q.worldguard.protection;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.RegionQuery;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.RegionGroup;
import com.sk89q.worldguard.protection.flags.StateFlag;
@ -52,7 +51,7 @@ public interface ApplicableRegionSet extends Iterable<ProtectedRegion> {
* </p>
*
* <p>Be sure to check the value of this flag if an instance of this
* interface is being retrieved from {@link RegionQuery} as it may
* interface is being retrieved from RegionQuery as it may
* return an instance of {@link PermissiveRegionSet} or
* {@link FailedLoadRegionSet}, among other possibilities.</p>
*
@ -62,7 +61,7 @@ public interface ApplicableRegionSet extends Iterable<ProtectedRegion> {
boolean isVirtual();
/**
* Tests whether the {@link DefaultFlag#BUILD} flag or membership
* Tests whether the {@link Flags#BUILD} flag or membership
* requirements permit the given player.
*
* @param player the player to check
@ -78,9 +77,9 @@ public interface ApplicableRegionSet extends Iterable<ProtectedRegion> {
*
* <p>{@code subject} can be non-null to satisfy region group requirements,
* otherwise it will be assumed that the caller that is not a member of any
* regions. (Flags on a region can be changed so that they only apply
* regions. (FlagUtil on a region can be changed so that they only apply
* to certain users.) The subject argument is required if the
* {@link DefaultFlag#BUILD} flag is in the list of flags.</p>
* {@link Flags#BUILD} flag is in the list of flags.</p>
*
* @param subject an optional subject, which would be used to determine the region groups that apply
* @param flags a list of flags to check
@ -96,9 +95,9 @@ public interface ApplicableRegionSet extends Iterable<ProtectedRegion> {
*
* <p>{@code subject} can be non-null to satisfy region group requirements,
* otherwise it will be assumed that the caller that is not a member of any
* regions. (Flags on a region can be changed so that they only apply
* regions. (FlagUtil on a region can be changed so that they only apply
* to certain users.) The subject argument is required if the
* {@link DefaultFlag#BUILD} flag is in the list of flags.</p>
* {@link Flags#BUILD} flag is in the list of flags.</p>
*
* @param subject an optional subject, which would be used to determine the region groups that apply
* @param flags a list of flags to check
@ -121,9 +120,9 @@ public interface ApplicableRegionSet extends Iterable<ProtectedRegion> {
*
* <p>{@code subject} can be non-null to satisfy region group requirements,
* otherwise it will be assumed that the caller that is not a member of any
* regions. (Flags on a region can be changed so that they only apply
* regions. (FlagUtil on a region can be changed so that they only apply
* to certain users.) The subject argument is required if the
* {@link DefaultFlag#BUILD} flag is the flag being queried.</p>
* {@link Flags#BUILD} flag is the flag being queried.</p>
*
* @param subject an optional subject, which would be used to determine the region group to apply
* @param flag the flag
@ -139,9 +138,9 @@ public interface ApplicableRegionSet extends Iterable<ProtectedRegion> {
*
* <p>{@code subject} can be non-null to satisfy region group requirements,
* otherwise it will be assumed that the caller that is not a member of any
* regions. (Flags on a region can be changed so that they only apply
* regions. (FlagUtil on a region can be changed so that they only apply
* to certain users.) The subject argument is required if the
* {@link DefaultFlag#BUILD} flag is the flag being queried.</p>
* {@link Flags#BUILD} flag is the flag being queried.</p>
*
* @param subject an optional subject, which would be used to determine the region group to apply
* @param flag the flag

View File

@ -22,11 +22,10 @@ package com.sk89q.worldguard.protection;
import com.google.common.collect.ImmutableList;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.StateFlag.State;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import org.bukkit.ChatColor;
import javax.annotation.Nullable;
import java.util.Collection;
@ -42,7 +41,7 @@ public class FailedLoadRegionSet extends AbstractRegionSet {
private static final FailedLoadRegionSet INSTANCE = new FailedLoadRegionSet();
private final String denyMessage = ChatColor.RED + "Region data for WorldGuard failed to load for this world, so " +
private final String denyMessage = "Region data for WorldGuard failed to load for this world, so " +
"everything has been protected as a precaution. Please inform a server administrator.";
private final Collection<String> denyMessageCollection = ImmutableList.of(denyMessage);
@ -58,9 +57,9 @@ public class FailedLoadRegionSet extends AbstractRegionSet {
@Nullable
@Override
public <V> V queryValue(@Nullable RegionAssociable subject, Flag<V> flag) {
if (flag == DefaultFlag.BUILD) {
if (flag == Flags.BUILD) {
return (V) State.DENY;
} else if (flag == DefaultFlag.DENY_MESSAGE) {
} else if (flag == Flags.DENY_MESSAGE) {
return (V) denyMessage;
}
return flag.getDefault();
@ -69,9 +68,9 @@ public class FailedLoadRegionSet extends AbstractRegionSet {
@SuppressWarnings("unchecked")
@Override
public <V> Collection<V> queryAllValues(@Nullable RegionAssociable subject, Flag<V> flag) {
if (flag == DefaultFlag.BUILD) {
if (flag == Flags.BUILD) {
return (Collection<V>) ImmutableList.of(State.DENY);
} else if (flag == DefaultFlag.DENY_MESSAGE) {
} else if (flag == Flags.DENY_MESSAGE) {
return (Collection<V>) denyMessageCollection;
}
V fallback = flag.getDefault();

View File

@ -24,7 +24,7 @@ import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.sk89q.worldguard.domains.Association;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.RegionGroup;
import com.sk89q.worldguard.protection.flags.StateFlag;
@ -90,7 +90,7 @@ public class FlagValueCalculator {
* the region is not a member of all regions.
*
* <p>A region is "counted" if it doesn't have the
* {@link DefaultFlag#PASSTHROUGH} flag set to {@code ALLOW}. (The
* {@link Flags#PASSTHROUGH} flag set to {@code ALLOW}. (The
* explicit purpose of the PASSTHROUGH flag is to have the region
* be skipped over in this check.)</p>
*
@ -118,7 +118,7 @@ public class FlagValueCalculator {
}
// If PASSTHROUGH is set, ignore this region
if (getEffectiveFlag(region, DefaultFlag.PASSTHROUGH, subject) == State.ALLOW) {
if (getEffectiveFlag(region, Flags.PASSTHROUGH, subject) == State.ALLOW) {
continue;
}
@ -306,7 +306,7 @@ public class FlagValueCalculator {
// The BUILD flag is implicitly set on every region where
// PASSTHROUGH is not set to ALLOW
if (priority != minimumPriority && flag.implicitlySetWithMembership()
&& getEffectiveFlag(region, DefaultFlag.PASSTHROUGH, subject) != State.ALLOW) {
&& getEffectiveFlag(region, Flags.PASSTHROUGH, subject) != State.ALLOW) {
minimumPriority = getPriority(region);
}
}
@ -355,10 +355,10 @@ public class FlagValueCalculator {
@SuppressWarnings("unchecked")
public <V> V getEffectiveFlag(final ProtectedRegion region, Flag<V> flag, @Nullable RegionAssociable subject) {
if (region == globalRegion) {
if (flag == DefaultFlag.PASSTHROUGH) {
if (flag == Flags.PASSTHROUGH) {
// Has members/owners -> the global region acts like
// a regular region without PASSTHROUGH
if (region.hasMembersOrOwners() || region.getFlag(DefaultFlag.PASSTHROUGH) == State.DENY) {
if (region.hasMembersOrOwners() || region.getFlag(Flags.PASSTHROUGH) == State.DENY) {
return null;
} else {
return (V) State.ALLOW;
@ -432,7 +432,7 @@ public class FlagValueCalculator {
public static enum Result {
/**
* Indicates that there are no regions or the only regions are
* ones with {@link DefaultFlag#PASSTHROUGH} enabled.
* ones with {@link Flags#PASSTHROUGH} enabled.
*/
NO_REGIONS,

View File

@ -22,7 +22,7 @@ package com.sk89q.worldguard.protection;
import com.google.common.collect.ImmutableList;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.StateFlag.State;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
@ -53,7 +53,7 @@ public class PermissiveRegionSet extends AbstractRegionSet {
@Nullable
@Override
public <V> V queryValue(@Nullable RegionAssociable subject, Flag<V> flag) {
if (flag == DefaultFlag.BUILD) {
if (flag == Flags.BUILD) {
return (V) State.DENY;
}
return flag.getDefault();
@ -62,7 +62,7 @@ public class PermissiveRegionSet extends AbstractRegionSet {
@SuppressWarnings("unchecked")
@Override
public <V> Collection<V> queryAllValues(@Nullable RegionAssociable subject, Flag<V> flag) {
if (flag == DefaultFlag.BUILD) {
if (flag == Flags.BUILD) {
return (Collection<V>) ImmutableList.of(State.DENY);
}
V fallback = flag.getDefault();

View File

@ -19,10 +19,6 @@
package com.sk89q.worldguard.protection.flags;
import org.bukkit.command.CommandSender;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
/**
* A boolean flag.
*/

View File

@ -21,7 +21,7 @@ package com.sk89q.worldguard.protection.flags;
/**
* A special implementation of the {@link StateFlag} for
* {@link DefaultFlag#BUILD}.
* {@link Flags#BUILD}.
*/
class BuildFlag extends StateFlag {

View File

@ -19,10 +19,6 @@
package com.sk89q.worldguard.protection.flags;
import org.bukkit.command.CommandSender;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
/**
* Stores a command/
*/

View File

@ -0,0 +1,63 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser 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 Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection.flags;
import com.sk89q.worldedit.world.entity.EntityType;
import com.sk89q.worldedit.world.entity.EntityTypes;
import javax.annotation.Nullable;
/**
* Stores an entity type.
*/
public class EntityTypeFlag extends Flag<EntityType> {
protected EntityTypeFlag(String name, @Nullable RegionGroup defaultGroup) {
super(name, defaultGroup);
}
protected EntityTypeFlag(String name) {
super(name);
}
@Override
public EntityType parseInput(FlagContext context) throws InvalidFlagFormat {
String input = context.getUserInput();
input = input.trim();
if (!input.startsWith("/")) {
input = "/" + input;
}
EntityType entityType = unmarshal(input);
if (entityType == null) {
throw new InvalidFlagFormat("Unknown entity type: " + input);
}
return entityType;
}
@Override
public EntityType unmarshal(@Nullable Object o) {
return EntityTypes.get(String.valueOf(o));
}
@Override
public Object marshal(EntityType o) {
return o.getId();
}
}

View File

@ -19,15 +19,16 @@
package com.sk89q.worldguard.protection.flags;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.Iterators;
import com.sk89q.worldguard.protection.FlagValueCalculator;
import com.sk89q.worldguard.protection.flags.registry.FlagRegistry;
import javax.annotation.Nullable;
import java.util.Collection;
import java.util.regex.Pattern;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.annotation.Nullable;
/**
* A flag carries extra data on a region.
@ -126,10 +127,10 @@ public abstract class Flag<T> {
/**
* Whether the flag implicitly has a value set as long as
* {@link DefaultFlag#PASSTHROUGH} is not set.
* {@link Flags#PASSTHROUGH} is not set.
*
* <p>This value is only changed, at least in WorldGuard, for the
* {@link DefaultFlag#BUILD} flag.</p>
* {@link Flags#BUILD} flag.</p>
*
* @return Whether the flag is ignored
*/
@ -142,7 +143,7 @@ public abstract class Flag<T> {
* from membership.
*
* <p>This value is only changed, at least in WorldGuard, for the
* {@link DefaultFlag#BUILD} flag.</p>
* {@link Flags#BUILD} flag.</p>
*
* @return Whether membership is used
*/
@ -155,7 +156,7 @@ public abstract class Flag<T> {
* {@link FlagValueCalculator}.
*
* <p>This value is only changed, at least in WorldGuard, for the
* {@link DefaultFlag#BUILD} flag.</p>
* {@link Flags#BUILD} flag.</p>
*
* @return Whether a subject is required
*/

View File

@ -20,23 +20,22 @@
package com.sk89q.worldguard.protection.flags;
import com.google.common.collect.Maps;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import java.util.Map;
import javax.annotation.Nullable;
import java.util.Map;
public final class FlagContext {
private final CommandSender sender;
private final Actor sender;
private final String input;
private Map<String, Object> context;
private FlagContext(CommandSender sender, String input, Map<String, Object> values) {
private FlagContext(Actor sender, String input, Map<String, Object> values) {
this.sender = sender;
this.input = input;
this.context = values;
@ -50,7 +49,7 @@ public final class FlagContext {
context.put(name, value);
}
public CommandSender getSender() {
public Actor getSender() {
return sender;
}
@ -64,11 +63,11 @@ public final class FlagContext {
* @return Player
* @throws InvalidFlagFormat if the sender is not a player
*/
public Player getPlayerSender() throws InvalidFlagFormat {
try {
return WorldGuardPlugin.inst().checkPlayer(sender);
} catch (CommandException e) {
throw new InvalidFlagFormat(e.getMessage());
public LocalPlayer getPlayerSender() throws InvalidFlagFormat {
if (sender.isPlayer() && sender instanceof LocalPlayer) {
return (LocalPlayer) sender;
} else {
throw new InvalidFlagFormat("Not a player");
}
}
@ -128,7 +127,7 @@ public final class FlagContext {
* @param values map of values to override from the current FlagContext
* @return a copy of this FlagContext
*/
public FlagContext copyWith(@Nullable CommandSender commandSender, @Nullable String s, @Nullable Map<String, Object> values) {
public FlagContext copyWith(@Nullable Actor commandSender, @Nullable String s, @Nullable Map<String, Object> values) {
Map<String, Object> map = Maps.newHashMap();
map.putAll(context);
if (values != null) {
@ -138,11 +137,11 @@ public final class FlagContext {
}
public static class FlagContextBuilder {
private CommandSender sender;
private Actor sender;
private String input;
private Map<String, Object> map = Maps.newHashMap();
public FlagContextBuilder setSender(CommandSender sender) {
public FlagContextBuilder setSender(Actor sender) {
this.sender = sender;
return this;
}
@ -164,7 +163,7 @@ public final class FlagContext {
}
public FlagContext build() {
Bukkit.getServer().getPluginManager().callEvent(new FlagContextCreateEvent(this));
WorldGuard.getInstance().getPlatform().notifyFlagContextCreate(this);
return new FlagContext(sender, input, map);
}

View File

@ -28,11 +28,11 @@ import java.util.logging.Logger;
import static com.google.common.base.Preconditions.checkNotNull;
public final class Flags {
public final class FlagUtil {
private static final Logger log = Logger.getLogger(Flags.class.getCanonicalName());
private static final Logger log = Logger.getLogger(FlagUtil.class.getCanonicalName());
private Flags() {
private FlagUtil() {
}
/**

View File

@ -19,22 +19,25 @@
package com.sk89q.worldguard.protection.flags;
import com.sk89q.worldedit.util.formatting.ColorCodeBuilder;
import com.sk89q.worldedit.util.formatting.Style;
import com.sk89q.worldedit.util.formatting.StyledFragment;
import com.sk89q.worldedit.world.entity.EntityType;
import com.sk89q.worldedit.world.gamemode.GameMode;
import com.sk89q.worldedit.world.weather.WeatherType;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.protection.flags.registry.FlagConflictException;
import com.sk89q.worldguard.protection.flags.registry.FlagRegistry;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.WeatherType;
import org.bukkit.entity.EntityType;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Nullable;
/**
* The flags that are used in WorldGuard.
*/
public final class DefaultFlag {
public final class Flags {
// Overrides membership check
public static final StateFlag PASSTHROUGH = new StateFlag("passthrough", false);
public static final StateFlag PASSTHROUGH = register(new StateFlag("passthrough", false));
// This flag is unlike the others. It forces the checking of region membership
public static final StateFlag BUILD = new BuildFlag("build", true);
@ -104,23 +107,26 @@ public final class DefaultFlag {
public static final StateFlag ENTITY_ITEM_FRAME_DESTROY = new StateFlag("entity-item-frame-destroy", true);
public static final StateFlag FALL_DAMAGE = new StateFlag("fall-damage", true);
// Flags that adjust behaviors that aren't state flags
// FlagUtil that adjust behaviors that aren't state flags
public static final StringFlag DENY_MESSAGE = new StringFlag("deny-message",
"" + ChatColor.RED + ChatColor.BOLD + "Hey!" + ChatColor.GRAY + " Sorry, but you can't %what% here.");
ColorCodeBuilder.asColorCodes(new StyledFragment().append(new StyledFragment(Style.RED, Style.BOLD).append("Hey!"))
.append(new StyledFragment(Style.GRAY).append(" Sorry, but you can't %what% here."))));
public static final StringFlag ENTRY_DENY_MESSAGE = new StringFlag("entry-deny-message",
"" + ChatColor.RED + ChatColor.BOLD + "Hey!" + ChatColor.GRAY + " You are not permitted to enter this area.");
ColorCodeBuilder.asColorCodes(new StyledFragment().append(new StyledFragment(Style.RED, Style.BOLD).append("Hey!"))
.append(new StyledFragment(Style.GRAY).append(" You are not permitted to enter this area."))));
public static final StringFlag EXIT_DENY_MESSAGE = new StringFlag("exit-deny-message",
"" + ChatColor.RED + ChatColor.BOLD + "Hey!" + ChatColor.GRAY + " You are not permitted to leave this area.");
ColorCodeBuilder.asColorCodes(new StyledFragment().append(new StyledFragment(Style.RED, Style.BOLD).append("Hey!"))
.append(new StyledFragment(Style.GRAY).append(" You are not permitted to leave this area."))));
public static final BooleanFlag EXIT_OVERRIDE = new BooleanFlag("exit-override");
public static final StateFlag EXIT_VIA_TELEPORT = new StateFlag("exit-via-teleport", true);
public static final StringFlag GREET_MESSAGE = new StringFlag("greeting");
public static final StringFlag FAREWELL_MESSAGE = new StringFlag("farewell");
public static final BooleanFlag NOTIFY_ENTER = new BooleanFlag("notify-enter");
public static final BooleanFlag NOTIFY_LEAVE = new BooleanFlag("notify-leave");
public static final SetFlag<EntityType> DENY_SPAWN = new SetFlag<EntityType>("deny-spawn", new EntityTypeFlag(null));
public static final EnumFlag<GameMode> GAME_MODE = new EnumFlag<GameMode>("game-mode", GameMode.class);
public static final SetFlag<EntityType> DENY_SPAWN = new SetFlag<>("deny-spawn", new EntityTypeFlag(null));
public static final Flag<GameMode> GAME_MODE = new GameModeTypeFlag("game-mode");
public static final StringFlag TIME_LOCK = new StringFlag("time-lock");
public static final EnumFlag<WeatherType> WEATHER_LOCK = new EnumFlag<WeatherType>("weather-lock", WeatherType.class);
public static final Flag<WeatherType> WEATHER_LOCK = new WeatherTypeFlag("weather-lock");
public static final IntegerFlag HEAL_DELAY = new IntegerFlag("heal-delay");
public static final IntegerFlag HEAL_AMOUNT = new IntegerFlag("heal-amount");
public static final DoubleFlag MIN_HEAL = new DoubleFlag("heal-min-health");
@ -133,8 +139,8 @@ public final class DefaultFlag {
// public static final StringFlag MAX_PLAYERS_MESSAGE = new StringFlag("max-players-reject-message");
public static final LocationFlag TELE_LOC = new LocationFlag("teleport", RegionGroup.MEMBERS);
public static final LocationFlag SPAWN_LOC = new LocationFlag("spawn", RegionGroup.MEMBERS);
public static final SetFlag<String> BLOCKED_CMDS = new SetFlag<String>("blocked-cmds", new CommandStringFlag(null));
public static final SetFlag<String> ALLOWED_CMDS = new SetFlag<String>("allowed-cmds", new CommandStringFlag(null));
public static final SetFlag<String> BLOCKED_CMDS = register(new SetFlag<>("blocked-cmds", new CommandStringFlag(null)));
public static final SetFlag<String> ALLOWED_CMDS = register(new SetFlag<>("allowed-cmds", new CommandStringFlag(null)));
// these 3 are not used by worldguard and should be re-implemented in plugins that may use them using custom flag api
@Deprecated
@ -144,45 +150,16 @@ public final class DefaultFlag {
@Deprecated
public static final DoubleFlag PRICE = new DoubleFlag("price");
public static final Flag<?>[] flagsList = new Flag<?>[] {
PASSTHROUGH, BUILD, BLOCK_BREAK, BLOCK_PLACE, PVP, CHEST_ACCESS, PISTONS,
TNT, LIGHTER, RIDE, USE, INTERACT, PLACE_VEHICLE, DESTROY_VEHICLE, DAMAGE_ANIMALS, SLEEP,
MOB_DAMAGE, MOB_SPAWNING, DENY_SPAWN, INVINCIBILITY, EXP_DROPS, FIREWORK_DAMAGE, WITHER_DAMAGE,
CREEPER_EXPLOSION, OTHER_EXPLOSION, ENDERDRAGON_BLOCK_DAMAGE, GHAST_FIREBALL, ENDER_BUILD,
DENY_MESSAGE, ENTRY_DENY_MESSAGE, EXIT_DENY_MESSAGE, EXIT_OVERRIDE, EXIT_VIA_TELEPORT,
GREET_MESSAGE, FAREWELL_MESSAGE, NOTIFY_ENTER, NOTIFY_LEAVE,
EXIT, ENTRY, LIGHTNING, ENTITY_PAINTING_DESTROY, ENDERPEARL, CHORUS_TELEPORT,
ENTITY_ITEM_FRAME_DESTROY, FALL_DAMAGE, ITEM_PICKUP, ITEM_DROP, /*MAX_PLAYERS, MAX_PLAYERS_MESSAGE,*/
HEAL_AMOUNT, HEAL_DELAY, MIN_HEAL, MAX_HEAL,
FEED_DELAY, FEED_AMOUNT, MIN_FOOD, MAX_FOOD,
SNOW_FALL, SNOW_MELT, ICE_FORM, ICE_MELT, SOIL_DRY, GAME_MODE,
MUSHROOMS, LEAF_DECAY, GRASS_SPREAD, MYCELIUM_SPREAD, VINE_GROWTH,
SEND_CHAT, RECEIVE_CHAT, FIRE_SPREAD, LAVA_FIRE, LAVA_FLOW, WATER_FLOW,
TELE_LOC, SPAWN_LOC, POTION_SPLASH, TIME_LOCK, WEATHER_LOCK,
BLOCKED_CMDS, ALLOWED_CMDS, PRICE, BUYABLE, ENABLE_SHOP
};
private DefaultFlag() {
private Flags() {
}
/**
* Get a list of default flags.
*
* @deprecated Use {@link FlagRegistry}
* @return An array of flags
*/
@Deprecated
public static Flag<?>[] getFlags() {
return flagsList;
public static <T extends Flag> T register(final T flag) throws FlagConflictException {
WorldGuard.getInstance().getFlagRegistry().register(flag);
return flag;
}
/**
* Get a list of default flags.
*
* @return An array of flags
*/
public static List<Flag<?>> getDefaultFlags() {
return Arrays.asList(flagsList);
public static @Nullable Flag get(final String id) {
return WorldGuard.getInstance().getFlagRegistry().get(id);
}
/**

View File

@ -0,0 +1,60 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser 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 Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection.flags;
import com.sk89q.worldedit.world.gamemode.GameMode;
import com.sk89q.worldedit.world.gamemode.GameModes;
import javax.annotation.Nullable;
public class GameModeTypeFlag extends Flag<GameMode> {
protected GameModeTypeFlag(String name, @Nullable RegionGroup defaultGroup) {
super(name, defaultGroup);
}
protected GameModeTypeFlag(String name) {
super(name);
}
@Override
public GameMode parseInput(FlagContext context) throws InvalidFlagFormat {
String input = context.getUserInput();
input = input.trim();
if (!input.startsWith("/")) {
input = "/" + input;
}
GameMode gamemode = unmarshal(input);
if (gamemode == null) {
throw new InvalidFlagFormat("Unknown game mode: " + input);
}
return gamemode;
}
@Override
public GameMode unmarshal(@Nullable Object o) {
return GameModes.get(String.valueOf(o));
}
@Override
public Object marshal(GameMode o) {
return o.getId();
}
}

View File

@ -19,11 +19,10 @@
package com.sk89q.worldguard.protection.flags;
import com.sk89q.worldedit.LocalWorld;
import com.sk89q.worldedit.Location;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.bukkit.BukkitUtil;
import org.bukkit.Bukkit;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldguard.WorldGuard;
import javax.annotation.Nullable;
@ -35,8 +34,8 @@ class LazyLocation extends Location {
private final String worldName;
@Nullable
private static LocalWorld findWorld(String worldName) {
return BukkitUtil.getLocalWorld(Bukkit.getServer().getWorld(worldName));
private static World findWorld(String worldName) {
return WorldGuard.getInstance().getPlatform().getWorldByName(worldName);
}
public LazyLocation(String worldName, Vector position, float yaw, float pitch) {
@ -54,7 +53,7 @@ class LazyLocation extends Location {
}
public LazyLocation setAngles(float yaw, float pitch) {
return new LazyLocation(worldName, getPosition(), yaw, pitch);
return new LazyLocation(worldName, toVector(), yaw, pitch);
}
public LazyLocation setPosition(Vector position) {
@ -62,11 +61,11 @@ class LazyLocation extends Location {
}
public LazyLocation add(Vector other) {
return this.setPosition(getPosition().add(other));
return this.setPosition(toVector().add(other));
}
public LazyLocation add(double x, double y, double z) {
return this.setPosition(getPosition().add(x, y, z));
return this.setPosition(toVector().add(x, y, z));
}
}

View File

@ -19,15 +19,13 @@
package com.sk89q.worldguard.protection.flags;
import com.sk89q.worldedit.Location;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.bukkit.BukkitUtil;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.permission.RegionPermissionModel;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.internal.permission.RegionPermissionModel;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.entity.Player;
import java.util.HashMap;
import java.util.Map;
@ -49,7 +47,7 @@ public class LocationFlag extends Flag<Location> {
Location loc = null;
if ("here".equalsIgnoreCase(input)) {
loc = toLazyLocation(player.getLocation());
loc = player.getLocation();
} else if ("none".equalsIgnoreCase(input)) {
return null;
} else {
@ -72,17 +70,17 @@ public class LocationFlag extends Flag<Location> {
Object obj = context.get("region");
if (obj instanceof ProtectedRegion) {
ProtectedRegion rg = (ProtectedRegion) obj;
if (WorldGuardPlugin.inst().getGlobalStateManager().get(player.getWorld()).boundedLocationFlags) {
if (!rg.contains(loc.getPosition())) {
if (new RegionPermissionModel(WorldGuardPlugin.inst(), player).mayOverrideLocationFlagBounds(rg)) {
player.sendMessage(ChatColor.GRAY + "WARNING: Flag location is outside of region.");
if (WorldGuard.getInstance().getPlatform().getGlobalStateManager().get(player.getWorld()).boundedLocationFlags) {
if (!rg.contains(loc.toVector())) {
if (new RegionPermissionModel(player).mayOverrideLocationFlagBounds(rg)) {
player.printDebug("WARNING: Flag location is outside of region.");
} else {
// no permission
throw new InvalidFlagFormat("You can't set that flag outside of the region boundaries.");
}
}
// clamp height to world limits
loc.setPosition(loc.getPosition().clampY(0, player.getWorld().getMaxHeight()));
loc.setPosition(loc.toVector().clampY(0, player.getWorld().getMaxY()));
return loc;
}
}
@ -91,10 +89,6 @@ public class LocationFlag extends Flag<Location> {
throw new InvalidFlagFormat("Expected 'here' or x,y,z.");
}
private Location toLazyLocation(org.bukkit.Location location) {
return new LazyLocation(location.getWorld().getName(), BukkitUtil.toVector(location), location.getYaw(), location.getPitch());
}
@Override
public Location unmarshal(Object o) {
if (o instanceof Map<?, ?>) {
@ -130,13 +124,15 @@ public class LocationFlag extends Flag<Location> {
@Override
public Object marshal(Location o) {
Vector position = o.getPosition();
Map<String, Object> vec = new HashMap<String, Object>();
Vector position = o.toVector();
Map<String, Object> vec = new HashMap<>();
if (o instanceof LazyLocation) {
vec.put("world", ((LazyLocation) o).getWorldName());
} else {
try {
vec.put("world", o.getWorld().getName());
if (o.getExtent() instanceof World) {
vec.put("world", ((World) o.getExtent()).getName());
}
} catch (NullPointerException e) {
return null;
}

View File

@ -19,9 +19,6 @@
package com.sk89q.worldguard.protection.flags;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import org.bukkit.command.CommandSender;
import javax.annotation.Nullable;
import java.util.Collection;
@ -72,7 +69,7 @@ public class StateFlag extends Flag<StateFlag.State> {
* the global region.
*
* <p>This value is only changed, at least in WorldGuard, for the
* {@link DefaultFlag#BUILD} flag.</p>
* {@link Flags#BUILD} flag.</p>
*
* @return Whether {@code ALLOW} is prevented
*/

View File

@ -19,10 +19,6 @@
package com.sk89q.worldguard.protection.flags;
import org.bukkit.command.CommandSender;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import javax.annotation.Nullable;
/**

View File

@ -20,7 +20,6 @@
package com.sk89q.worldguard.protection.flags;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.bukkit.BukkitUtil;
import java.util.HashMap;
import java.util.Map;
@ -43,7 +42,7 @@ public class VectorFlag extends Flag<Vector> {
String input = context.getUserInput();
if ("here".equalsIgnoreCase(input)) {
return BukkitUtil.toVector(context.getPlayerSender().getLocation());
return context.getPlayerSender().getLocation().toVector();
} else {
String[] split = input.split(",");
if (split.length == 3) {
@ -82,7 +81,7 @@ public class VectorFlag extends Flag<Vector> {
@Override
public Object marshal(Vector o) {
Map<String, Object> vec = new HashMap<String, Object>();
Map<String, Object> vec = new HashMap<>();
vec.put("x", o.getX());
vec.put("y", o.getY());
vec.put("z", o.getZ());

View File

@ -0,0 +1,60 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser 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 Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection.flags;
import com.sk89q.worldedit.world.weather.WeatherType;
import com.sk89q.worldedit.world.weather.WeatherTypes;
import javax.annotation.Nullable;
public class WeatherTypeFlag extends Flag<WeatherType> {
protected WeatherTypeFlag(String name, @Nullable RegionGroup defaultGroup) {
super(name, defaultGroup);
}
protected WeatherTypeFlag(String name) {
super(name);
}
@Override
public WeatherType parseInput(FlagContext context) throws InvalidFlagFormat {
String input = context.getUserInput();
input = input.trim();
if (!input.startsWith("/")) {
input = "/" + input;
}
WeatherType weatherType = unmarshal(input);
if (weatherType == null) {
throw new InvalidFlagFormat("Unknown game mode: " + input);
}
return weatherType;
}
@Override
public WeatherType unmarshal(@Nullable Object o) {
return WeatherTypes.get(String.valueOf(o));
}
@Override
public Object marshal(WeatherType o) {
return o.getId();
}
}

Some files were not shown because too many files have changed in this diff Show More