Merge branch 'master' of github.com:Multiverse/Multiverse-Core into new-tests

Conflicts:
	src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java
This commit is contained in:
main() 2012-01-07 16:10:18 +01:00
commit 814725a2ba
121 changed files with 2954 additions and 648 deletions

View File

@ -5,7 +5,9 @@
~ with this project. ~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-->
<!DOCTYPE module SYSTEM "http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<!DOCTYPE module PUBLIC
"-//Puppy Crawl//DTD Check Configuration 1.3//EN"
"http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<!-- Future reference: valid severity values are 'ignore', 'info', 'warning', 'error' -->
<module name="Checker">
<module name="JavadocPackage">
@ -23,7 +25,19 @@
<property name="message" value="Line has trailing spaces."/>
<property name="format" value="\s+$"/>
</module>
<module name="SuppressWithNearbyCommentFilter"/>
<module name="SuppressWithNearbyCommentFilter">
<property name="commentFormat" value="SUPPRESS CHECKSTYLE: (\w+)"/>
<property name="checkFormat" value="$1"/>
</module>
<module name="SuppressionCommentFilter">
<property name="offCommentFormat" value="BEGIN CHECKSTYLE-SUPPRESSION\: (\w+)"/>
<property name="onCommentFormat" value="END CHECKSTYLE-SUPPRESSION\: (\w+)"/>
<property name="checkFormat" value="$1"/>
</module>
<module name="SuppressionCommentFilter">
<property name="offCommentFormat" value="BEGIN CHECKSTYLE-SUPPRESSION\: ALL"/>
<property name="onCommentFormat" value="END CHECKSTYLE-SUPPRESSION\: ALL"/>
</module>
<module name="TreeWalker">
<!-- Make suppression possible -->
<module name="FileContentsHolder"/>
@ -61,12 +75,16 @@
</module>
<module name="IllegalImport"/>
<module name="RedundantImport"/>
<module name="UnusedImports"/>
<module name="UnusedImports">
<property name="processJavadoc" value="true"/>
</module>
<module name="MethodLength"/>
<module name="ParameterNumber"/>
<module name="EmptyForIteratorPad"/>
<module name="MethodParamPad"/>
<module name="NoWhitespaceAfter"/>
<module name="NoWhitespaceAfter">
<property name="tokens" value="BNOT, DEC, DOT, INC, LNOT, UNARY_MINUS, UNARY_PLUS"/>
</module>
<module name="NoWhitespaceBefore"/>
<module name="OperatorWrap"/>
<module name="ParenPad"/>
@ -93,7 +111,9 @@
</module>
<module name="IllegalInstantiation"/>
<module name="InnerAssignment"/>
<module name="MagicNumber"/>
<module name="MagicNumber">
<property name="ignoreNumbers" value="-1, 0, 0.5, 1, 2, 3"/>
</module>
<module name="MissingSwitchDefault"/>
<module name="RedundantThrows"/>
<module name="SimplifyBooleanExpression"/>
@ -115,5 +135,8 @@
<property name="severity" value="info"/>
</module>
<module name="UpperEll"/>
<module name="Indentation"/>
<module name="MissingDeprecated"/>
<module name="MissingOverride"/>
</module>
</module>

View File

@ -8,14 +8,15 @@
package com.onarandombox.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.configuration.*;
import com.onarandombox.MultiverseCore.configuration.ConfigPropertyFactory;
import com.onarandombox.MultiverseCore.configuration.MVActiveConfigProperty;
import com.onarandombox.MultiverseCore.configuration.MVConfigProperty;
import com.onarandombox.MultiverseCore.enums.EnglishChatColor;
import com.onarandombox.MultiverseCore.event.MVWorldPropertyChangeEvent;
import com.onarandombox.MultiverseCore.exceptions.PropertyDoesNotExistException;
import com.onarandombox.MultiverseCore.utils.BlockSafety;
import com.onarandombox.MultiverseCore.utils.LocationManipulation;
import com.onarandombox.MultiverseCore.utils.SafeTTeleporter;
import org.bukkit.ChatColor;
import org.bukkit.Difficulty;
import org.bukkit.GameMode;
@ -31,11 +32,16 @@ import org.bukkit.permissions.PermissionDefault;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The implementation of a Multiverse handled world.
@ -53,7 +59,6 @@ public class MVWorld implements MultiverseWorld {
private Map<String, List<String>> masterList;
private Map<String, MVConfigProperty<?>> propertyList;
private String generator;
private Permission permission;
private Permission exempt;
@ -62,6 +67,20 @@ public class MVWorld implements MultiverseWorld {
private Map<String, String> propertyAliases;
private Permission ignoreperm;
private static final Map<String, String> TIME_ALIASES;
static {
Map<String, String> staticTimes = new HashMap<String, String>();
staticTimes.put("morning", "8:00");
staticTimes.put("day", "12:00");
staticTimes.put("noon", "12:00");
staticTimes.put("midnight", "0:00");
staticTimes.put("night", "20:00");
// now set TIME_ALIASES to a "frozen" map
TIME_ALIASES = Collections.unmodifiableMap(staticTimes);
}
public MVWorld(World world, FileConfiguration config, MultiverseCore instance, Long seed, String generatorString, boolean fixSpawn) {
this.config = config;
this.plugin = instance;
@ -97,29 +116,57 @@ public class MVWorld implements MultiverseWorld {
// getNewProperty(name, defaultValue, yamlConfigNode, helpText)
//
// If the first type is used, name is used as the yamlConfigNode
this.propertyList.put("hidden", fac.getNewProperty("hidden", false, "Sorry, 'hidden' must either be:" + ChatColor.GREEN + " true " + ChatColor.WHITE + "or" + ChatColor.RED + " false" + ChatColor.WHITE + "."));
this.propertyList.put("alias", fac.getNewProperty("alias", "", "alias.name", "Alias must be a valid string."));
this.propertyList.put("color", fac.getNewProperty("color", EnglishChatColor.WHITE, "alias.color", "Sorry, 'color' must either one of: " + EnglishChatColor.getAllColors()));
this.propertyList.put("pvp", fac.getNewProperty("pvp", true, "Sorry, 'pvp' must either be:" + ChatColor.GREEN + " true " + ChatColor.WHITE + "or" + ChatColor.RED + " false" + ChatColor.WHITE + "."));
this.propertyList.put("scale", fac.getNewProperty("scale", this.getDefaultScale(this.environment), "Scale must be a positive double value. ex: " + ChatColor.GOLD + "2.3"));
this.propertyList.put("respawn", fac.getNewProperty("respawn", "", "respawnworld", "You must set this to the " + ChatColor.GOLD + " NAME" + ChatColor.RED + " not alias of a world."));
this.propertyList.put("weather", fac.getNewProperty("weather", true, "allowweather", "Sorry, 'weather' must either be:" + ChatColor.GREEN + " true " + ChatColor.WHITE + "or" + ChatColor.RED + " false" + ChatColor.WHITE + "."));
this.propertyList.put("difficulty", fac.getNewProperty("difficulty", Difficulty.EASY, "Difficulty must be set as one of the following: " + ChatColor.GREEN + "peaceful " + ChatColor.AQUA + "easy " + ChatColor.GOLD + "normal " + ChatColor.RED + "hard"));
this.propertyList.put("animals", fac.getNewProperty("animals", true, "animals.spawn", "Sorry, 'animals' must either be:" + ChatColor.GREEN + " true " + ChatColor.WHITE + "or" + ChatColor.RED + " false" + ChatColor.WHITE + "."));
this.propertyList.put("monsters", fac.getNewProperty("monsters", true, "monsters.spawn", "Sorry, 'monsters' must either be:" + ChatColor.GREEN + " true " + ChatColor.WHITE + "or" + ChatColor.RED + " false" + ChatColor.WHITE + "."));
this.propertyList.put("currency", fac.getNewProperty("currency", -1, "entryfee.currency", "Currency must be an integer between -1 and the highest Minecraft item ID."));
this.propertyList.put("price", fac.getNewProperty("price", 0.0, "entryfee.price", "Price must be a double value. ex: " + ChatColor.GOLD + "1.2" + ChatColor.WHITE + ". Set to a negative value to give players money for entering this world."));
this.propertyList.put("hunger", fac.getNewProperty("hunger", true, "Sorry, 'hunger' must either be:" + ChatColor.GREEN + " true " + ChatColor.WHITE + "or" + ChatColor.RED + " false" + ChatColor.WHITE + "."));
this.propertyList.put("autoheal", fac.getNewProperty("autoheal", true, "Sorry, 'autoheal' must either be:" + ChatColor.GREEN + " true " + ChatColor.WHITE + "or" + ChatColor.RED + " false" + ChatColor.WHITE + "."));
this.propertyList.put("adjustspawn", fac.getNewProperty("adjustspawn", true, "Sorry, 'adjustspawn' must either be:" + ChatColor.GREEN + " true " + ChatColor.WHITE + "or" + ChatColor.RED + " false" + ChatColor.WHITE + "."));
if(!fixSpawn) {
this.propertyList.put("hidden", fac.getNewProperty("hidden", false,
"Sorry, 'hidden' must either be:" + ChatColor.GREEN + " true " + ChatColor.WHITE + "or" + ChatColor.RED + " false" + ChatColor.WHITE + "."));
this.propertyList.put("alias", fac.getNewProperty("alias", "", "alias.name",
"Alias must be a valid string."));
this.propertyList.put("color", fac.getNewProperty("color", EnglishChatColor.WHITE, "alias.color",
"Sorry, 'color' must either one of: " + EnglishChatColor.getAllColors()));
this.propertyList.put("pvp", fac.getNewProperty("pvp", true, "pvp",
"Sorry, 'pvp' must either be:" + ChatColor.GREEN + " true " + ChatColor.WHITE
+ "or" + ChatColor.RED + " false" + ChatColor.WHITE + ".", "setActualPVP"));
this.propertyList.put("scale", fac.getNewProperty("scale", this.getDefaultScale(this.environment), "scale",
"Scale must be a positive double value. ex: " + ChatColor.GOLD + "2.3", "verifyScaleSetProperly"));
this.propertyList.put("respawn", fac.getNewProperty("respawn", "", "respawnworld",
"You must set this to the " + ChatColor.GOLD + " NAME" + ChatColor.RED + " not alias of a world."));
this.propertyList.put("weather", fac.getNewProperty("weather", true, "allowweather",
"Sorry, 'weather' must either be:" + ChatColor.GREEN + " true " + ChatColor.WHITE
+ "or" + ChatColor.RED + " false" + ChatColor.WHITE + ".", "setActualWeather"));
this.propertyList.put("difficulty", fac.getNewProperty("difficulty", Difficulty.EASY,
"Difficulty must be set as one of the following: " + ChatColor.GREEN + "peaceful "
+ ChatColor.AQUA + "easy " + ChatColor.GOLD + "normal " + ChatColor.RED + "hard"));
this.propertyList.put("animals", fac.getNewProperty("animals", true, "animals.spawn",
"Sorry, 'animals' must either be:" + ChatColor.GREEN + " true " + ChatColor.WHITE
+ "or" + ChatColor.RED + " false" + ChatColor.WHITE + ".", "syncMobs"));
this.propertyList.put("monsters", fac.getNewProperty("monsters", true, "monsters.spawn",
"Sorry, 'monsters' must either be:" + ChatColor.GREEN + " true " + ChatColor.WHITE
+ "or" + ChatColor.RED + " false" + ChatColor.WHITE + ".", "syncMobs"));
this.propertyList.put("currency", fac.getNewProperty("currency", -1, "entryfee.currency",
"Currency must be an integer between -1 and the highest Minecraft item ID."));
this.propertyList.put("price", fac.getNewProperty("price", 0.0, "entryfee.price",
"Price must be a double value. ex: " + ChatColor.GOLD + "1.2" + ChatColor.WHITE
+ ". Set to a negative value to give players money for entering this world."));
this.propertyList.put("hunger", fac.getNewProperty("hunger", true,
"Sorry, 'hunger' must either be:" + ChatColor.GREEN + " true " + ChatColor.WHITE + "or" + ChatColor.RED + " false" + ChatColor.WHITE + "."));
this.propertyList.put("autoheal", fac.getNewProperty("autoheal", true,
"Sorry, 'autoheal' must either be:" + ChatColor.GREEN + " true " + ChatColor.WHITE + "or" + ChatColor.RED + " false" + ChatColor.WHITE + "."));
this.propertyList.put("adjustspawn", fac.getNewProperty("adjustspawn", true,
"Sorry, 'adjustspawn' must either be:" + ChatColor.GREEN + " true " + ChatColor.WHITE
+ "or" + ChatColor.RED + " false" + ChatColor.WHITE + "."));
if (!fixSpawn) {
this.setAdjustSpawn(false);
}
this.propertyList.put("gamemode", fac.getNewProperty("gamemode", GameMode.SURVIVAL, "GameMode must be set as one of the following: " + ChatColor.RED + "survival " + ChatColor.GREEN + "creative "));
this.propertyList.put("memory", fac.getNewProperty("keepspawninmemory", true, "keepspawninmemory", "Sorry, 'memory' must either be:" + ChatColor.GREEN + " true " + ChatColor.WHITE + "or" + ChatColor.RED + " false" + ChatColor.WHITE + "."));
this.propertyList.put("spawn", fac.getNewProperty("spawn", this.world.getSpawnLocation(), "There is no help available for this variable. Go bug Rigby90 about it."));
this.propertyList.put("autoload", fac.getNewProperty("autoload", true, "Set this to false ONLY if you don't want this world to load itself on server restart."));
this.propertyList.put("gamemode", fac.getNewProperty("gamemode", GameMode.SURVIVAL,
"GameMode must be set as one of the following: " + ChatColor.RED + "survival " + ChatColor.GREEN + "creative "));
this.propertyList.put("memory", fac.getNewProperty("keepspawninmemory", true, "keepspawninmemory",
"Sorry, 'memory' must either be:" + ChatColor.GREEN + " true "
+ ChatColor.WHITE + "or" + ChatColor.RED + " false" + ChatColor.WHITE + ".", "setActualKeepSpawnInMemory"));
this.propertyList.put("spawn", fac.getNewProperty("spawn", this.world.getSpawnLocation(), "spawn",
"There is no help available for this variable. Go bug Rigby90 about it.", "setActualKeepSpawnInMemory"));
this.propertyList.put("autoload", fac.getNewProperty("autoload", true,
"Set this to false ONLY if you don't want this world to load itself on server restart."));
this.propertyList.put("bedrespawn", fac.getNewProperty("bedrespawn", true, "If a player dies in this world, shoudld they go to their bed?"));
this.propertyList.put("time", fac.getNewProperty("time", "", "Set the time to whatever you want! (Will NOT freeze time)", "setActualTime", true));
this.getKnownProperty("spawn", Location.class).setValue(this.readSpawnFromConfig(this.getCBWorld()));
@ -144,9 +191,11 @@ public class MVWorld implements MultiverseWorld {
this.permission = new Permission("multiverse.access." + this.getName(), "Allows access to " + this.getName(), PermissionDefault.OP);
// This guy is special. He shouldn't be added to any parent perms.
this.ignoreperm = new Permission("mv.bypass.gamemode." + this.getName(), "Allows players with this permission to ignore gamemode changes.", PermissionDefault.FALSE);
this.ignoreperm = new Permission("mv.bypass.gamemode." + this.getName(),
"Allows players with this permission to ignore gamemode changes.", PermissionDefault.FALSE);
this.exempt = new Permission("multiverse.exempt." + this.getName(), "A player who has this does not pay to enter this world, or use any MV portals in it " + this.getName(), PermissionDefault.OP);
this.exempt = new Permission("multiverse.exempt." + this.getName(),
"A player who has this does not pay to enter this world, or use any MV portals in it " + this.getName(), PermissionDefault.OP);
try {
this.plugin.getServer().getPluginManager().addPermission(this.permission);
this.plugin.getServer().getPluginManager().addPermission(this.exempt);
@ -158,51 +207,53 @@ public class MVWorld implements MultiverseWorld {
}
/**
* Applies all settings to the Bukkit-{@link World}.
* Used by the active PVP-property to set the "actual" PVP-property.
* @return True if the property was successfully set.
*/
public void changeActiveEffects() {
// Disable any current weather
if (!this.getKnownProperty("weather", Boolean.class).getValue()) {
this.getCBWorld().setStorm(false);
this.getCBWorld().setThundering(false);
}
// Set the spawn location
Location spawnLocation = this.getKnownProperty("spawn", Location.class).getValue();
this.getCBWorld().setSpawnLocation(spawnLocation.getBlockX(), spawnLocation.getBlockY(), spawnLocation.getBlockZ());
// Synchronize all Mob settings
this.syncMobs();
// Ensure the memory setting is correct
this.world.setKeepSpawnInMemory(this.getKnownProperty("memory", Boolean.class).getValue());
public boolean setActualPVP() {
// Set the PVP mode
this.world.setPVP(this.getKnownProperty("pvp", Boolean.class).getValue());
return true;
}
/**
* Used by the active scale-property to set the "actual" scale-property.
* @return True if the property was successfully set.
*/
public boolean verifyScaleSetProperly() {
// Ensure the scale is above 0
if (this.getKnownProperty("scale", Double.class).getValue() <= 0) {
// Disallow negative or 0 scalings.
this.getKnownProperty("scale", Double.class).setValue(1.0);
this.plugin.log(Level.WARNING, "Someone tried to set a scale <= 0, defaulting to 1.");
}
// Set the gamemode
// TODO: Move this to a per world gamemode
if (MultiverseCore.EnforceGameModes) {
for (Player p : this.plugin.getServer().getWorld(this.getName()).getPlayers()) {
this.plugin.log(Level.FINER, "Setting " + p.getName() + "'s GameMode to " + this.getKnownProperty("mode", GameMode.class).getValue().toString());
this.plugin.getPlayerListener().handleGameMode(p, this);
}
return true;
}
// Set the difficulty
this.getCBWorld().setDifficulty(this.getKnownProperty("diff", Difficulty.class).getValue());
/**
* Used by the active keepSpawnInMemory-property to set the "actual" property.
* @return True if the property was successfully set.
*/
public boolean setActualKeepSpawnInMemory() {
// Ensure the memory setting is correct
this.world.setKeepSpawnInMemory(this.getKnownProperty("memory", Boolean.class).getValue());
return true;
}
/**
* Used by the active spawn-property to set the "actual" property.
* @return True if the property was successfully set.
*/
public boolean setActualSpawn() {
// Set the spawn location
Location spawnLocation = this.getKnownProperty("spawn", Location.class).getValue();
this.getCBWorld().setSpawnLocation(spawnLocation.getBlockX(), spawnLocation.getBlockY(), spawnLocation.getBlockZ());
return true;
}
private double getDefaultScale(Environment environment) {
if (environment == Environment.NETHER) {
return 8.0;
return 8.0; // SUPPRESS CHECKSTYLE: MagicNumberCheck
}
return 1.0;
}
@ -342,7 +393,12 @@ public class MVWorld implements MultiverseWorld {
return false;
}
private void syncMobs() {
/**
* Ensure that the value of the animals and monsters config
* properties are set in accordance with the current animals
* and monsters in the world, respectively.
*/
public void syncMobs() {
if (this.getAnimalList().isEmpty()) {
this.world.setSpawnFlags(this.world.getAllowMonsters(), this.getKnownProperty("animals", Boolean.class).getValue());
@ -396,6 +452,8 @@ public class MVWorld implements MultiverseWorld {
/**
* {@inheritDoc}
*
* @deprecated Use {@link #getProperty(String, Class)} instead
*/
@Override
@Deprecated
@ -464,12 +522,40 @@ public class MVWorld implements MultiverseWorld {
value = propertyChangeEvent.getNewValue();
}
if (property.parseValue(value)) {
if (property instanceof MVActiveConfigProperty) {
return this.setActiveProperty((MVActiveConfigProperty<?>) property);
}
this.saveConfig();
return true;
}
return false;
}
private boolean setActiveProperty(MVActiveConfigProperty<?> property) {
try {
if (property.getMethod() == null) {
// This property did not have a method.
return true;
}
Method method = this.getClass().getMethod(property.getMethod());
Object returnVal = method.invoke(this);
if (returnVal instanceof Boolean) {
return (Boolean) returnVal;
} else {
return true;
}
} catch (NoSuchMethodException e) {
System.out.println(e);
return false;
} catch (IllegalAccessException e) {
System.out.println(e);
return false;
} catch (InvocationTargetException e) {
System.out.println(e);
return false;
}
}
/**
* {@inheritDoc}
*/
@ -681,6 +767,8 @@ public class MVWorld implements MultiverseWorld {
/**
* {@inheritDoc}
*
* @deprecated This is deprecated.
*/
@Override
@Deprecated
@ -756,7 +844,6 @@ public class MVWorld implements MultiverseWorld {
private void saveConfig() {
if (this.canSave) {
try {
this.changeActiveEffects();
this.config.save(new File(this.plugin.getDataFolder(), "worlds.yml"));
} catch (IOException e) {
this.plugin.log(Level.SEVERE, "Could not save worlds.yml. Please check your filesystem permissions.");
@ -769,7 +856,25 @@ public class MVWorld implements MultiverseWorld {
*/
@Override
public boolean setGameMode(String gameMode) {
return this.setKnownProperty("mode", gameMode + "", null);
return this.setKnownProperty("mode", gameMode, null);
}
/**
* Sets the actual gamemode by iterating through players.
*
* gameMode is not used, but it's in the reflection template.
*
* Needs a bit o' refactoring.
*
* @return True if the gamemodes of players were set successfully. (always)
*/
public boolean setActualGameMode() {
for (Player p : this.plugin.getServer().getWorld(this.getName()).getPlayers()) {
this.plugin.log(Level.FINER, String.format("Setting %s's GameMode to %s",
p.getName(), this.getKnownProperty("mode", GameMode.class).getValue().toString()));
this.plugin.getPlayerListener().handleGameMode(p, this);
}
return true;
}
/**
@ -788,6 +893,19 @@ public class MVWorld implements MultiverseWorld {
this.setKnownProperty("weather", weather + "", null);
}
/**
* Used by the active weather-property to set the "actual" property.
* @return True if the property was successfully set.
*/
public boolean setActualWeather() {
// Disable any current weather
if (!this.getKnownProperty("weather", Boolean.class).getValue()) {
this.getCBWorld().setStorm(false);
this.getCBWorld().setThundering(false);
}
return true;
}
/**
* {@inheritDoc}
*/
@ -830,6 +948,9 @@ public class MVWorld implements MultiverseWorld {
this.saveConfig();
}
private static final int SPAWN_LOCATION_SEARCH_TOLERANCE = 16;
private static final int SPAWN_LOCATION_SEARCH_RADIUS = 16;
private Location readSpawnFromConfig(World w) {
Location spawnLocation = w.getSpawnLocation();
Location configLocation = this.getSpawnLocation();
@ -850,7 +971,8 @@ public class MVWorld implements MultiverseWorld {
// If it's not, find a better one.
this.plugin.log(Level.WARNING, "Spawn location from world.dat file was unsafe. Adjusting...");
this.plugin.log(Level.WARNING, "Original Location: " + LocationManipulation.strCoordsRaw(spawnLocation));
Location newSpawn = teleporter.getSafeLocation(spawnLocation, 16, 16);
Location newSpawn = teleporter.getSafeLocation(spawnLocation,
SPAWN_LOCATION_SEARCH_TOLERANCE, SPAWN_LOCATION_SEARCH_RADIUS);
// I think we could also do this, as I think this is what Notch does.
// Not sure how it will work in the nether...
//Location newSpawn = this.spawnLocation.getWorld().getHighestBlockAt(this.spawnLocation).getLocation();
@ -865,7 +987,8 @@ public class MVWorld implements MultiverseWorld {
if (newerSpawn != null) {
this.setSpawnLocation(newerSpawn);
configLocation = this.getSpawnLocation();
this.plugin.log(Level.INFO, "New Spawn for '" + this.getName() + "' is Located at: " + LocationManipulation.locationToString(configLocation));
this.plugin.log(Level.INFO, "New Spawn for '" + this.getName()
+ "' is Located at: " + LocationManipulation.locationToString(configLocation));
} else {
this.plugin.log(Level.SEVERE, "New safe spawn NOT found!!!");
}
@ -897,7 +1020,12 @@ public class MVWorld implements MultiverseWorld {
*/
@Override
public boolean setDifficulty(String difficulty) {
return this.setKnownProperty("diff", difficulty, null);
if (this.setKnownProperty("diff", difficulty, null)) {
// Set the difficulty
this.getCBWorld().setDifficulty(this.getKnownProperty("diff", Difficulty.class).getValue());
return true;
}
return false;
}
/**
@ -978,6 +1106,87 @@ public class MVWorld implements MultiverseWorld {
return result;
}
/**
* {@inheritDoc}
*/
@Override
public String getTime() {
long time = this.getCBWorld().getTime();
// I'm tired, so they get time in 24 hour for now.
// Someone else can add 12 hr format if they want :P
// BEGIN CHECKSTYLE-SUPPRESSION: MagicNumberCheck
int hours = (int) ((time / 1000 + 8) % 24);
int minutes = (int) (60 * (time % 1000) / 1000);
// END CHECKSTYLE-SUPPRESSION: MagicNumberCheck
return String.format("%d:%02d", hours, minutes);
}
/**
* Used by the active time-property to set the "actual" property.
* @return True if the property was successfully set.
*/
public boolean setActualTime() {
return this.setTime(this.getKnownProperty("time", String.class).toString());
}
/**
* {@inheritDoc}
*/
@Override
// BEGIN CHECKSTYLE-SUPPRESSION: MagicNumberCheck
public boolean setTime(String timeAsString) {
if (TIME_ALIASES.containsKey(timeAsString.toLowerCase())) {
return this.setTime(TIME_ALIASES.get(timeAsString.toLowerCase()));
}
// Regex that extracts a time in the following formats:
// 11:11pm, 11:11, 23:11, 1111, 1111p, and the aliases at the top of this file.
String timeRegex = "(\\d\\d?):?(\\d\\d)(a|p)?m?";
Pattern pattern = Pattern.compile(timeRegex, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(timeAsString);
matcher.find();
int hour = 0;
double minute = 0;
int count = matcher.groupCount();
if (count >= 2) {
hour = Integer.parseInt(matcher.group(1));
minute = Integer.parseInt(matcher.group(2));
}
// If there were 4 matches (all, hour, min, ampm)
if (count == 4) {
// We want 24 hour time for calcs, but if they
// added a p[m], turn it into a 24 hr one.
if (matcher.group(3).equals("p")) {
hour += 12;
}
}
// Translate 24th hour to 0th hour.
if (hour == 24) { // SUPPRESS CHECKSTYLE MagicNumberCheck
hour = 0;
}
// Clamp the hour
if (hour > 23 || hour < 0) {
return false;
}
// Clamp the minute
if (minute > 59 || minute < 0) {
return false;
}
// 60 seconds in a minute, time needs to be in hrs * 1000, per
// the bukkit docs.
double totaltime = (hour + (minute / 60.0)) * 1000;
// Somehow there's an 8 hour offset...
totaltime -= 8000;
if (totaltime < 0) {
totaltime = 24000 + totaltime;
}
this.getCBWorld().setTime((long) totaltime);
return true;
}
// END CHECKSTYLE-SUPPRESSION: MagicNumberCheck
@Override
public String toString() {
StringBuilder toStringBuilder = new StringBuilder();

View File

@ -14,12 +14,27 @@ import com.onarandombox.MultiverseCore.api.MVPlugin;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.commands.*;
import com.onarandombox.MultiverseCore.destination.*;
import com.onarandombox.MultiverseCore.destination.AnchorDestination;
import com.onarandombox.MultiverseCore.destination.BedDestination;
import com.onarandombox.MultiverseCore.destination.CannonDestination;
import com.onarandombox.MultiverseCore.destination.DestinationFactory;
import com.onarandombox.MultiverseCore.destination.ExactDestination;
import com.onarandombox.MultiverseCore.destination.PlayerDestination;
import com.onarandombox.MultiverseCore.destination.WorldDestination;
import com.onarandombox.MultiverseCore.event.MVVersionEvent;
import com.onarandombox.MultiverseCore.listeners.MVEntityListener;
import com.onarandombox.MultiverseCore.listeners.MVPlayerListener;
import com.onarandombox.MultiverseCore.listeners.MVPluginListener;
import com.onarandombox.MultiverseCore.listeners.MVPortalAdjustListener;
import com.onarandombox.MultiverseCore.listeners.MVWeatherListener;
import com.onarandombox.MultiverseCore.utils.*;
import com.onarandombox.MultiverseCore.utils.AnchorManager;
import com.onarandombox.MultiverseCore.utils.DebugLog;
import com.onarandombox.MultiverseCore.utils.MVMessaging;
import com.onarandombox.MultiverseCore.utils.MVPermissions;
import com.onarandombox.MultiverseCore.utils.MVPlayerSession;
import com.onarandombox.MultiverseCore.utils.SafeTTeleporter;
import com.onarandombox.MultiverseCore.utils.SpoutInterface;
import com.onarandombox.MultiverseCore.utils.WorldManager;
import com.pneumaticraft.commandhandler.CommandHandler;
import org.bukkit.ChatColor;
import org.bukkit.Location;
@ -50,17 +65,20 @@ import java.util.logging.Logger;
* The implementation of the Multiverse-{@link Core}.
*/
public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
private final static int Protocol = 10;
private static final int PROTOCOL = 10;
// Global Multiverse config variable, states whether or not
// Multiverse should stop other plugins from teleporting players
// to worlds.
// TODO This is REALLY bad style! We have to change this!
// No, I'm NOT going to suppress these warnings because we HAVE TO CHANGE THIS!
public static boolean EnforceAccess;
public static boolean EnforceGameModes;
public static boolean PrefixChat;
public static boolean DisplayPermErrors;
public static boolean TeleportIntercept;
public static boolean FirstSpawnOverride;
public static Map<String, String> teleportQueue = new HashMap<String, String>();
public static int GlobalDebug = 0;
private AnchorManager anchorManager = new AnchorManager(this);
/**
@ -77,6 +95,12 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
return null;
}
/**
* This method is used to add a teleportation to the teleportQueue.
*
* @param teleporter The name of the player that initiated the teleportation.
* @param teleportee The name of the player that was teleported.
*/
public static void addPlayerToTeleportQueue(String teleporter, String teleportee) {
staticLog(Level.FINEST, "Adding mapping '" + teleporter + "' => '" + teleportee + "' to teleport queue");
teleportQueue.put(teleportee, teleporter);
@ -87,9 +111,14 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
return "The Multiverse-Core Plugin";
}
/**
* {@inheritDoc}
* @deprecated This is now deprecated, nobody needs it any longer.
* All version info-dumping is now done with {@link MVVersionEvent}.
*/
@Override
@Deprecated
public String dumpVersionInfo(String buffer) {
// I'm kinda cheating on this one, since we call the init event.
return buffer;
}
@ -106,18 +135,17 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
@Override
public int getProtocolVersion() {
return MultiverseCore.Protocol;
return MultiverseCore.PROTOCOL;
}
// Useless stuff to keep us going.
private static final Logger log = Logger.getLogger("Minecraft");
private static final Logger LOGGER = Logger.getLogger("Minecraft");
private static DebugLog debugLog;
public static boolean MobsDisabledInDefaultWorld = false;
// Setup our Map for our Commands using the CommandHandler.
private CommandHandler commandHandler;
private final static String tag = "[Multiverse-Core]";
private static final String LOG_TAG = "[Multiverse-Core]";
// Multiverse Permissions Handler
private MVPermissions ph;
@ -129,23 +157,22 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
// Setup the block/player/entity listener.
private MVPlayerListener playerListener = new MVPlayerListener(this);
private MVPortalAdjustListener portalAdjustListener = new MVPortalAdjustListener(this);
private MVEntityListener entityListener = new MVEntityListener(this);
private MVPluginListener pluginListener = new MVPluginListener(this);
private MVWeatherListener weatherListener = new MVWeatherListener(this);
public UpdateChecker updateCheck;
public static int GlobalDebug = 0;
//public UpdateChecker updateCheck;
// HashMap to contain information relating to the Players.
private HashMap<String, MVPlayerSession> playerSessions;
private GenericBank bank = null;
private AllPay banker;
protected int pluginCount;
private int pluginCount;
private DestinationFactory destFactory;
private SpoutInterface spoutInterface = null;
private double allpayversion = 3;
private double chversion = 4;
private static final double ALLPAY_VERSION = 3;
private static final double CH_VERSION = 4;
private MVMessaging messaging;
private File serverFolder = new File(System.getProperty("user.dir"));
@ -185,9 +212,10 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
this.getServer().getPluginManager().disablePlugin(this);
return;
}
this.banker = new AllPay(this, tag + " ");
this.messaging = new MVMessaging();
this.banker = new AllPay(this, LOG_TAG + " ");
// Output a little snippet to show it's enabled.
this.log(Level.INFO, "- Version " + this.getDescription().getVersion() + " (API v" + Protocol + ") Enabled - By " + getAuthors());
this.log(Level.INFO, "- Version " + this.getDescription().getVersion() + " (API v" + PROTOCOL + ") Enabled - By " + getAuthors());
// Load the defaultWorldGenerators
this.worldManager.getDefaultWorldGenerators();
@ -244,44 +272,34 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
private boolean validateAllpay() {
try {
this.banker = new AllPay(this, "Verify");
if (this.banker.getVersion() >= allpayversion) {
if (this.banker.getVersion() >= ALLPAY_VERSION) {
return true;
} else {
log.info(tag + " - Version " + this.getDescription().getVersion() + " was NOT ENABLED!!!");
log.info(tag + " A plugin that has loaded before " + this.getDescription().getName() + " has an incompatible version of AllPay!");
log.info(tag + " The Following Plugins MAY out of date!");
log.info(tag + " This plugin needs AllPay v" + allpayversion + " or higher and another plugin has loaded v" + this.banker.getVersion() + "!");
log.info(tag + AllPay.pluginsThatUseUs.toString());
return false;
}
} catch (Throwable t) {
}
log.info(tag + " - Version " + this.getDescription().getVersion() + " was NOT ENABLED!!!");
log.info(tag + " A plugin that has loaded before " + this.getDescription().getName() + " has an incompatible version of AllPay!");
log.info(tag + " Check the logs for [AllPay] - Version ... for PLUGIN NAME to find the culprit! Then Yell at that dev!");
log.info(tag + " Or update that plugin :P");
log.info(tag + " This plugin needs AllPay v" + allpayversion + " or higher!");
LOGGER.info(String.format("%s - Version %s was NOT ENABLED!!!", LOG_TAG, this.getDescription().getVersion()));
LOGGER.info(String.format("%s A plugin that has loaded before %s has an incompatible version of AllPay (an internal library)!",
LOG_TAG, this.getDescription().getName()));
LOGGER.info(String.format("%s The Following Plugins MAY out of date: %s", LOG_TAG, AllPay.pluginsThatUseUs.toString()));
LOGGER.info(String.format("%s This plugin needs AllPay v%f or higher and another plugin has loaded v%f!",
LOG_TAG, ALLPAY_VERSION, this.banker.getVersion()));
return false;
}
private boolean validateCH() {
try {
this.commandHandler = new CommandHandler(this, null);
if (this.commandHandler.getVersion() >= chversion) {
if (this.commandHandler.getVersion() >= CH_VERSION) {
return true;
} else {
log.info(tag + " - Version " + this.getDescription().getVersion() + " was NOT ENABLED!!!");
log.info(tag + " A plugin that has loaded before " + this.getDescription().getName() + " has an incompatible version of CommandHandler (an internal library)!");
log.info(tag + " Please contact this plugin author!!!!!!!");
log.info(tag + " This plugin needs CommandHandler v" + chversion + " or higher and another plugin has loaded v" + this.commandHandler.getVersion() + "!");
return false;
}
} catch (Throwable t) {
}
log.info(tag + " - Version " + this.getDescription().getVersion() + " was NOT ENABLED!!!");
log.info(tag + " A plugin that has loaded before " + this.getDescription().getName() + " has an incompatible version of CommandHandler (an internal library)!");
log.info(tag + " Please contact this plugin author!!!!!!!");
log.info(tag + " This plugin needs CommandHandler v" + chversion + " or higher!");
LOGGER.info(String.format("%s - Version %s was NOT ENABLED!!!", LOG_TAG, this.getDescription().getVersion()));
LOGGER.info(String.format("%s A plugin that has loaded before %s has an incompatible version of CommandHandler (an internal library)!",
LOG_TAG, this.getDescription().getName()));
LOGGER.info(String.format("%s Please contact this plugin author!!!", LOG_TAG));
LOGGER.info(String.format("%s This plugin needs CommandHandler v%f or higher and another plugin has loaded v%f!",
LOG_TAG, CH_VERSION, this.commandHandler.getVersion()));
return false;
}
@ -307,7 +325,10 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
pm.registerEvent(Event.Type.PLAYER_RESPAWN, this.playerListener, Priority.Low, this); // Let plugins which specialize in (re)spawning carry more weight.
pm.registerEvent(Event.Type.PLAYER_LOGIN, this.playerListener, Priority.Low, this); // Let plugins which specialize in (re)spawning carry more weight.
pm.registerEvent(Event.Type.PLAYER_CHAT, this.playerListener, Priority.Normal, this); // To prepend the world name
pm.registerEvent(Event.Type.PLAYER_PORTAL, this.playerListener, Priority.Lowest, this); // To switch gamemode
pm.registerEvent(Event.Type.PLAYER_PORTAL, this.playerListener, Priority.High, this);
// We want this high to have it go last, so it can cancel if needbe.
pm.registerEvent(Event.Type.PLAYER_PORTAL, this.portalAdjustListener, Priority.Lowest, this); // To handle portal correction
pm.registerEvent(Event.Type.PLAYER_CHANGED_WORLD, this.playerListener, Priority.Monitor, this); // To switch gamemode
pm.registerEvent(Event.Type.ENTITY_REGAIN_HEALTH, this.entityListener, Priority.Normal, this);
@ -340,7 +361,6 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
GlobalDebug = this.multiverseConfig.getInt("debug", 0);
// Lets cache these values due to the fact that they will be accessed many times.
EnforceAccess = this.multiverseConfig.getBoolean("enforceaccess", false);
EnforceGameModes = this.multiverseConfig.getBoolean("enforcegamemodes", true);
PrefixChat = this.multiverseConfig.getBoolean("worldnameprefix", true);
// Should MV Intercept teleports by other plugins?
TeleportIntercept = this.multiverseConfig.getBoolean("teleportintercept", true);
@ -348,13 +368,21 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
FirstSpawnOverride = this.multiverseConfig.getBoolean("firstspawnoverride", true);
// Should permissions errors display to users?
DisplayPermErrors = this.multiverseConfig.getBoolean("displaypermerrors", true);
this.messaging = new MVMessaging(this);
this.messaging.setCooldown(this.multiverseConfig.getInt("messagecooldown", 5000));
this.messaging.setCooldown(this.multiverseConfig.getInt("messagecooldown", 5000)); // SUPPRESS CHECKSTYLE: MagicNumberCheck
// Update the version of the config!
this.multiverseConfig.set("version", coreDefaults.get("version"));
// Remove old values.
this.multiverseConfig.set("enforcegamemodes", null);
this.multiverseConfig.set("bedrespawn", null);
this.multiverseConfig.set("opfallback", null);
this.saveMVConfigs();
}
/**
* Safely return a world name
* Safely return a world name.
* (The tests call this with no worlds loaded)
*
* @return The default world name.
@ -476,6 +504,12 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
staticLog(level, msg);
}
/**
* Logs a message at the specified level.
*
* @param level The Log-{@link Level}.
* @param msg The message to log.
*/
public static void staticLog(Level level, String msg) {
if (level == Level.FINE && GlobalDebug >= 1) {
staticDebugLog(Level.INFO, msg);
@ -487,8 +521,8 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
staticDebugLog(Level.INFO, msg);
return;
} else if (level != Level.FINE && level != Level.FINER && level != Level.FINEST) {
log.log(level, tag + " " + msg);
debugLog.log(level, tag + " " + msg);
LOGGER.log(level, String.format("%s %s", LOG_TAG, msg));
debugLog.log(level, String.format("%s %s", LOG_TAG, msg));
}
}
@ -500,7 +534,7 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
* @param msg The message
*/
public static void staticDebugLog(Level level, String msg) {
log.log(level, "[MVCore-Debug] " + msg);
LOGGER.log(level, "[MVCore-Debug] " + msg);
debugLog.log(level, "[MVCore-Debug] " + msg);
}
@ -544,7 +578,7 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
*/
// TODO this should be static!
public String getTag() {
return MultiverseCore.tag;
return MultiverseCore.LOG_TAG;
}
// TODO This code should get moved somewhere more appropriate, but for now, it's here.
@ -585,6 +619,11 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
sender.sendMessage("Type " + ChatColor.DARK_AQUA + "/mv import ?" + ChatColor.WHITE + " for help!");
}
/**
* Removes a player-session.
*
* @param player The {@link Player} that owned the session.
*/
public void removePlayerSession(Player player) {
if (this.playerSessions.containsKey(player.getName())) {
this.playerSessions.remove(player.getName());
@ -672,6 +711,9 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
this.serverFolder = newServerFolder;
}
/**
* Initializes Spout.
*/
public void setSpout() {
this.spoutInterface = new SpoutInterface();
this.commandHandler.registerCommand(new SpoutCommand(this));
@ -686,6 +728,11 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
}
}
/**
* Gets our {@link SpoutInterface}.
*
* @return The {@link SpoutInterface} we're using.
*/
public SpoutInterface getSpout() {
return this.spoutInterface;
}

View File

@ -7,11 +7,14 @@
package com.onarandombox.MultiverseCore.api;
/**
* A fancy text.
*/
public interface FancyText {
/**
* TODO: Write something useful here.
* Gets the {@link String}-representation of this {@link FancyText}.
*
* @return And Here.
* @return The {@link String}-representation of this {@link FancyText}.
*/
String getFancyText();
}

View File

@ -8,7 +8,11 @@
package com.onarandombox.MultiverseCore.api;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.event.MVVersionEvent;
/**
* This interface is implemented by every official Multiverse-plugin.
*/
public interface MVPlugin extends LoggablePlugin {
/**
* Adds This plugin's version information to the buffer and returns the new string.
@ -16,7 +20,11 @@ public interface MVPlugin extends LoggablePlugin {
* @param buffer The string that contains Core and all other MV plugins' versions.
*
* @return A modified buffer that contains this MVPlugin's version information.
*
* @deprecated This is now deprecated, nobody needs it any longer.
* All version info-dumping is now done with {@link MVVersionEvent}.
*/
@Deprecated
String dumpVersionInfo(String buffer);
/**

View File

@ -35,7 +35,7 @@ public interface MVWorldManager {
* @param generator The Custom generator plugin to use.
* @return True if the world is added, false if not.
*/
public boolean addWorld(String name, Environment env, String seedString, String generator);
boolean addWorld(String name, Environment env, String seedString, String generator);
/**
* Add a new World to the Multiverse Setup.
@ -49,7 +49,7 @@ public interface MVWorldManager {
* @param useSpawnAdjust If true, multiverse will search for a safe spawn. If not, It will not modify the level.dat.
* @return True if the world is added, false if not.
*/
public boolean addWorld(String name, Environment env, String seedString, String generator, boolean useSpawnAdjust);
boolean addWorld(String name, Environment env, String seedString, String generator, boolean useSpawnAdjust);
/**
* Remove the world from the Multiverse list, from the
@ -58,7 +58,7 @@ public interface MVWorldManager {
* @param name The name of the world to remove
* @return True if success, false if failure.
*/
public Boolean deleteWorld(String name);
boolean deleteWorld(String name);
/**
* Remove the world from the Multiverse list, from the
@ -69,7 +69,7 @@ public interface MVWorldManager {
* config. If false, they'll stay and the world may come back.
* @return True if success, false if failure.
*/
public Boolean deleteWorld(String name, boolean removeConfig);
boolean deleteWorld(String name, boolean removeConfig);
/**
* Unload a world from Multiverse.
@ -77,7 +77,7 @@ public interface MVWorldManager {
* @param name Name of the world to unload
* @return True if the world was unloaded, false if not.
*/
public boolean unloadWorld(String name);
boolean unloadWorld(String name);
/**
* Loads the world. Only use this if the world has been
@ -86,14 +86,14 @@ public interface MVWorldManager {
* @param name The name of the world to load
* @return True if success, false if failure.
*/
public boolean loadWorld(String name);
boolean loadWorld(String name);
/**
* Removes all players from the specified world.
*
* @param name World to remove players from.
*/
public void removePlayersFromWorld(String name);
void removePlayersFromWorld(String name);
/**
* Test if a given chunk generator is valid.
@ -103,14 +103,14 @@ public interface MVWorldManager {
* @param worldName The worldName to use as the default.
* @return A {@link ChunkGenerator} or null
*/
public ChunkGenerator getChunkGenerator(String generator, String generatorID, String worldName);
ChunkGenerator getChunkGenerator(String generator, String generatorID, String worldName);
/**
* Returns a list of all the worlds Multiverse knows about.
*
* @return A list of {@link MultiverseWorld}.
*/
public Collection<MultiverseWorld> getMVWorlds();
Collection<MultiverseWorld> getMVWorlds();
/**
@ -120,7 +120,7 @@ public interface MVWorldManager {
* @param name The name or alias of the world to get.
* @return A {@link MultiverseWorld} or null.
*/
public MultiverseWorld getMVWorld(String name);
MultiverseWorld getMVWorld(String name);
/**
* Returns a {@link MultiverseWorld} if it exists, and null if it does not.
@ -128,7 +128,7 @@ public interface MVWorldManager {
* @param world The Bukkit world to check.
* @return A {@link MultiverseWorld} or null.
*/
public MultiverseWorld getMVWorld(World world);
MultiverseWorld getMVWorld(World world);
/**
* Checks to see if the given name is a valid {@link MultiverseWorld}.
@ -136,7 +136,7 @@ public interface MVWorldManager {
* @param name The name or alias of the world to check.
* @return True if the world exists, false if not.
*/
public boolean isMVWorld(String name);
boolean isMVWorld(String name);
/**
* Checks to see if the given world is a valid {@link MultiverseWorld}.
@ -144,7 +144,7 @@ public interface MVWorldManager {
* @param world The Bukkit world to check.
* @return True if the world has been loaded into MV2, false if not.
*/
public boolean isMVWorld(World world);
boolean isMVWorld(World world);
/**
* Load the Worlds & Settings from the configuration file.
@ -152,21 +152,21 @@ public interface MVWorldManager {
* @param forceLoad If set to true, this will perform a total
* reset and not just load new worlds.
*/
public void loadWorlds(boolean forceLoad);
void loadWorlds(boolean forceLoad);
/**
* Loads the Worlds & Settings for any worlds that bukkit loaded before us.
* <p>
* This way people will _always_ have some worlds in the list.
*/
public void loadDefaultWorlds();
void loadDefaultWorlds();
/**
* Return the World Purger.
*
* @return A valid {@link PurgeWorlds}.
*/
public PurgeWorlds getWorldPurger();
PurgeWorlds getWorldPurger();
/**
* Gets the world players will spawn in on first join.
@ -174,19 +174,19 @@ public interface MVWorldManager {
*
* @return A Multiverse world that players will spawn in or null if no MV world has been set.
*/
public MultiverseWorld getSpawnWorld();
MultiverseWorld getSpawnWorld();
/**
* Gets the list of worlds in the config, but unloaded.
*
* @return A List of worlds as strings.
*/
public List<String> getUnloadedWorlds();
List<String> getUnloadedWorlds();
/**
* This method populates an internal list and needs to be called after multiverse initialization.
*/
public void getDefaultWorldGenerators();
void getDefaultWorldGenerators();
/**
* Load the config from a file.
@ -194,14 +194,14 @@ public interface MVWorldManager {
* @param file The file to load.
* @return A loaded configuration.
*/
public FileConfiguration loadWorldConfig(File file);
FileConfiguration loadWorldConfig(File file);
/**
* Saves the world config to disk.
*
* @return True if success, false if fail.
*/
public boolean saveWorldsConfig();
boolean saveWorldsConfig();
/**
* Remove the world from the Multiverse list and from the config.
@ -209,19 +209,19 @@ public interface MVWorldManager {
* @param name The name of the world to remove
* @return True if success, false if failure.
*/
public boolean removeWorldFromConfig(String name);
boolean removeWorldFromConfig(String name);
/**
* Sets the initial spawn world for new players.
*
* @param world The World new players should spawn in.
*/
public void setFirstSpawnWorld(String world);
void setFirstSpawnWorld(String world);
/**
* Gets the world players should spawn in first.
*
* @return The {@link MultiverseWorld} new players should spawn in.
*/
public MultiverseWorld getFirstSpawnWorld();
MultiverseWorld getFirstSpawnWorld();
}

View File

@ -217,6 +217,7 @@ public interface MultiverseWorld {
* Turn pvp on or off. This setting is used to set the world's PVP mode, and thus relies on fakePVP
*
* @return True if this world has fakepvp on
* @deprecated This is deprecated.
*/
@Deprecated
boolean getFakePVP();
@ -532,4 +533,23 @@ public interface MultiverseWorld {
* @return All property names, with alternating colors.
*/
String getAllPropertyNames();
/**
* Sets the current time in a world.
*
* This method will take the following formats:
* 11:37am
* 4:30p
* day(morning), night, noon, midnight
*
* @param timeAsString The formatted time to set the world to.
* @return True if the time was set, false if not.
*/
boolean setTime(String timeAsString);
/**
* Same as {@link #getTime()}, but returns a string.
* @return The time as a short string: 12:34pm
*/
String getTime();
}

View File

@ -0,0 +1,5 @@
/**
* The Multiverse-API, containing lots of interfaces that can be quite useful for other
* plugins when interacting with Multiverse.
*/
package com.onarandombox.MultiverseCore.api;

View File

@ -16,6 +16,9 @@ import org.bukkit.permissions.PermissionDefault;
import java.util.ArrayList;
import java.util.List;
/**
* Allows management of Anchor Destinations.
*/
public class AnchorCommand extends PaginatedCoreCommand<String> {
public AnchorCommand(MultiverseCore plugin) {
@ -32,7 +35,7 @@ public class AnchorCommand extends PaginatedCoreCommand<String> {
this.addCommandExample("/mv anchor " + ChatColor.GREEN + "awesomething " + ChatColor.RED + "-d");
this.addCommandExample("/mv anchors ");
this.setPermission("multiverse.core.anchor", "Allows management of Anchor Destinations.", PermissionDefault.OP);
this.setItemsPerPage(8);
this.setItemsPerPage(8); // SUPPRESS CHECKSTYLE: MagicNumberCheck
}
private List<String> getFancyAnchorList(Player p) {
@ -59,7 +62,8 @@ public class AnchorCommand extends PaginatedCoreCommand<String> {
if (filterObject.getFilter().length() > 0) {
availableAnchors = this.getFilteredItems(availableAnchors, filterObject.getFilter());
if (availableAnchors.size() == 0) {
sender.sendMessage(ChatColor.RED + "Sorry... " + ChatColor.WHITE + "No anchors matched your filter: " + ChatColor.AQUA + filterObject.getFilter());
sender.sendMessage(ChatColor.RED + "Sorry... " + ChatColor.WHITE
+ "No anchors matched your filter: " + ChatColor.AQUA + filterObject.getFilter());
return;
}
} else {

View File

@ -17,7 +17,9 @@ import org.bukkit.entity.Player;
import org.bukkit.permissions.PermissionDefault;
import java.util.List;
/**
* Checks to see if a player can go to a destination.
*/
public class CheckCommand extends MultiverseCommand {
public CheckCommand(MultiverseCore plugin) {

View File

@ -8,7 +8,6 @@
package com.onarandombox.MultiverseCore.commands;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.enums.ConfigProperty;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
@ -16,9 +15,10 @@ import org.bukkit.permissions.PermissionDefault;
import java.util.List;
/**
* Allows you to set Global MV Variables.
*/
public class ConfigCommand extends MultiverseCommand {
private MVWorldManager worldManager;
public ConfigCommand(MultiverseCore plugin) {
super(plugin);
this.setName("Configuration");
@ -33,7 +33,6 @@ public class ConfigCommand extends MultiverseCommand {
this.addCommandExample("/mv config " + ChatColor.GREEN + "debug" + ChatColor.AQUA + " 3");
this.addCommandExample("/mv config " + ChatColor.GREEN + "enforceaccess" + ChatColor.AQUA + " false");
this.setPermission("multiverse.core.config", "Allows you to set Global MV Variables.", PermissionDefault.OP);
this.worldManager = this.plugin.getMVWorldManager();
}
@Override
@ -58,7 +57,8 @@ public class ConfigCommand extends MultiverseCommand {
this.plugin.getMVConfiguration().set(args.get(0).toLowerCase(), args.get(1));
// Don't forget to set the world!
this.plugin.getMVWorldManager().setFirstSpawnWorld(args.get(1));
} else if (args.get(0).equalsIgnoreCase("messagecooldown") || args.get(0).equalsIgnoreCase("teleportcooldown") || args.get(0).equalsIgnoreCase("debug")) {
} else if (args.get(0).equalsIgnoreCase("messagecooldown") || args.get(0).equalsIgnoreCase("teleportcooldown")
|| args.get(0).equalsIgnoreCase("debug")) {
try {
this.plugin.getMVConfiguration().set(args.get(0).toLowerCase(), Integer.parseInt(args.get(1)));
} catch (NumberFormatException e) {
@ -70,7 +70,8 @@ public class ConfigCommand extends MultiverseCommand {
try {
property = ConfigProperty.valueOf(args.get(0).toLowerCase());
} catch (IllegalArgumentException e) {
sender.sendMessage(ChatColor.RED + "Sorry, " + ChatColor.AQUA + args.get(0) + ChatColor.WHITE + " you can't set " + ChatColor.AQUA + args.get(0));
sender.sendMessage(ChatColor.RED + "Sorry, " + ChatColor.AQUA
+ args.get(0) + ChatColor.WHITE + " you can't set " + ChatColor.AQUA + args.get(0));
sender.sendMessage(ChatColor.GREEN + "Valid values are:");
sender.sendMessage(ConfigProperty.getAllValues());
return;

View File

@ -13,6 +13,9 @@ import org.bukkit.permissions.PermissionDefault;
import java.util.List;
/**
* Confirms actions.
*/
public class ConfirmCommand extends MultiverseCommand {
public ConfirmCommand(MultiverseCore plugin) {

View File

@ -21,6 +21,9 @@ import org.bukkit.permissions.PermissionDefault;
import java.text.DecimalFormat;
import java.util.List;
/**
* Returns detailed information on the Players where abouts.
*/
public class CoordCommand extends MultiverseCommand {
private MVWorldManager worldManager;

View File

@ -19,6 +19,9 @@ import org.bukkit.permissions.PermissionDefault;
import java.io.File;
import java.util.List;
/**
* Creates a new world and loads it.
*/
public class CreateCommand extends MultiverseCommand {
private MVWorldManager worldManager;
@ -26,7 +29,7 @@ public class CreateCommand extends MultiverseCommand {
super(plugin);
this.setName("Create World");
this.setCommandUsage("/mv create" + ChatColor.GREEN + " {NAME} {ENV}" + ChatColor.GOLD + " -s [SEED] -g [GENERATOR[:ID]] [-n]");
this.setArgRange(2, 7);
this.setArgRange(2, 7); // SUPPRESS CHECKSTYLE: MagicNumberCheck
this.addKey("mvcreate");
this.addKey("mvc");
this.addKey("mv create");
@ -47,8 +50,8 @@ public class CreateCommand extends MultiverseCommand {
String seed = CommandHandler.getFlag("-s", args);
String generator = CommandHandler.getFlag("-g", args);
boolean useSpawnAdjust = true;
for(String s : args) {
if(s.equalsIgnoreCase("-n")) {
for (String s : args) {
if (s.equalsIgnoreCase("-n")) {
useSpawnAdjust = false;
}
}

View File

@ -15,6 +15,9 @@ import org.bukkit.permissions.PermissionDefault;
import java.util.List;
import java.util.logging.Level;
/**
* Enables debug-information.
*/
public class DebugCommand extends MultiverseCommand {
public DebugCommand(MultiverseCore plugin) {
@ -42,7 +45,8 @@ public class DebugCommand extends MultiverseCommand {
}
MultiverseCore.GlobalDebug = debugLevel;
} catch (NumberFormatException e) {
sender.sendMessage(ChatColor.RED + "Error" + ChatColor.WHITE + " setting debug level. Please use a number 0-3 " + ChatColor.AQUA + "(3 being many many messages!)");
sender.sendMessage(ChatColor.RED + "Error" + ChatColor.WHITE
+ " setting debug level. Please use a number 0-3 " + ChatColor.AQUA + "(3 being many many messages!)");
}
}

View File

@ -15,6 +15,9 @@ import org.bukkit.permissions.PermissionDefault;
import java.util.ArrayList;
import java.util.List;
/**
* Deletes worlds.
*/
public class DeleteCommand extends MultiverseCommand {
public DeleteCommand(MultiverseCore plugin) {
@ -30,8 +33,9 @@ public class DeleteCommand extends MultiverseCommand {
@Override
public void runCommand(CommandSender sender, List<String> args) {
Class<?> paramTypes[] = {String.class};
Class<?>[] paramTypes = {String.class};
List<Object> objectArgs = new ArrayList<Object>(args);
this.plugin.getCommandHandler().queueCommand(sender, "mvdelete", "deleteWorld", objectArgs, paramTypes, ChatColor.GREEN + "World Deleted!", ChatColor.RED + "World could NOT be deleted!");
this.plugin.getCommandHandler().queueCommand(sender, "mvdelete", "deleteWorld", objectArgs,
paramTypes, ChatColor.GREEN + "World Deleted!", ChatColor.RED + "World could NOT be deleted!");
}
}

View File

@ -14,6 +14,9 @@ import org.bukkit.permissions.PermissionDefault;
import java.util.List;
/**
* Lists valid known environments.
*/
public class EnvironmentCommand extends MultiverseCommand {
public EnvironmentCommand(MultiverseCore plugin) {
@ -29,6 +32,11 @@ public class EnvironmentCommand extends MultiverseCommand {
this.setPermission("multiverse.core.list.environments", "Lists valid known environments.", PermissionDefault.OP);
}
/**
* Shows all valid known environments to a {@link CommandSender}.
*
* @param sender The {@link CommandSender}.
*/
public static void showEnvironments(CommandSender sender) {
sender.sendMessage(ChatColor.YELLOW + "Valid Environments are:");
sender.sendMessage(ChatColor.GREEN + "NORMAL");

View File

@ -17,6 +17,9 @@ import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
/**
* Returns a list of loaded generator plugins.
*/
public class GeneratorCommand extends MultiverseCommand {
public GeneratorCommand(MultiverseCore plugin) {

View File

@ -5,6 +5,7 @@
* with this project. *
******************************************************************************/
// TODO maybe remove this comment...?
// This file is no longer licensed under that silly CC license. I have blanked it out and will start implementaiton of my own in a few days. For now there is no help.
package com.onarandombox.MultiverseCore.commands;
@ -18,6 +19,9 @@ import org.bukkit.permissions.PermissionDefault;
import java.util.ArrayList;
import java.util.List;
/**
* Displays a nice help menu.
*/
public class HelpCommand extends PaginatedCoreCommand<Command> {
public HelpCommand(MultiverseCore plugin) {
@ -33,7 +37,7 @@ public class HelpCommand extends PaginatedCoreCommand<Command> {
this.addKey("mv search");
this.addCommandExample("/mv help ?");
this.setPermission("multiverse.help", "Displays a nice help menu.", PermissionDefault.TRUE);
this.setItemsPerPage(7);
this.setItemsPerPage(7); // SUPPRESS CHECKSTYLE: MagicNumberCheck
}
@Override
@ -50,8 +54,8 @@ public class HelpCommand extends PaginatedCoreCommand<Command> {
} else if (c.getCommandUsage().matches("(?i).*" + filter + ".*")) {
filtered.add(c);
} else {
for(String example : c.getCommandExamples()) {
if(example.matches("(?i).*" + filter + ".*")) {
for (String example : c.getCommandExamples()) {
if (example.matches("(?i).*" + filter + ".*")) {
filtered.add(c);
break;
}
@ -76,7 +80,8 @@ public class HelpCommand extends PaginatedCoreCommand<Command> {
if (filterObject.getFilter().length() > 0) {
availableCommands = this.getFilteredItems(availableCommands, filterObject.getFilter());
if (availableCommands.size() == 0) {
sender.sendMessage(ChatColor.RED + "Sorry... " + ChatColor.WHITE + "No commands matched your filter: " + ChatColor.AQUA + filterObject.getFilter());
sender.sendMessage(ChatColor.RED + "Sorry... " + ChatColor.WHITE
+ "No commands matched your filter: " + ChatColor.AQUA + filterObject.getFilter());
return;
}
}

View File

@ -23,6 +23,9 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Imports a new world of the specified type.
*/
public class ImportCommand extends MultiverseCommand {
private MVWorldManager worldManager;
@ -115,7 +118,8 @@ public class ImportCommand extends MultiverseCommand {
// Make sure we don't already know about this world.
if (this.worldManager.isMVWorld(worldName)) {
sender.sendMessage(ChatColor.GREEN + "Multiverse" + ChatColor.WHITE + " already knows about '" + ChatColor.AQUA + worldName + ChatColor.WHITE + "'!");
sender.sendMessage(ChatColor.GREEN + "Multiverse" + ChatColor.WHITE
+ " already knows about '" + ChatColor.AQUA + worldName + ChatColor.WHITE + "'!");
return;
}
@ -123,8 +127,8 @@ public class ImportCommand extends MultiverseCommand {
String generator = CommandHandler.getFlag("-g", args);
boolean useSpawnAdjust = true;
for(String s : args) {
if(s.equalsIgnoreCase("-n")) {
for (String s : args) {
if (s.equalsIgnoreCase("-n")) {
useSpawnAdjust = false;
}
}
@ -139,8 +143,10 @@ public class ImportCommand extends MultiverseCommand {
if (worldFile.exists() && env != null) {
Command.broadcastCommandMessage(sender, "Starting import of world '" + worldName + "'...");
this.worldManager.addWorld(worldName, environment, null, generator, useSpawnAdjust);
Command.broadcastCommandMessage(sender, "Complete!");
if (this.worldManager.addWorld(worldName, environment, null, generator, useSpawnAdjust))
Command.broadcastCommandMessage(sender, ChatColor.GREEN + "Complete!");
else
Command.broadcastCommandMessage(sender, ChatColor.RED + "Failed!");
} else if (env == null) {
sender.sendMessage(ChatColor.RED + "FAILED.");
sender.sendMessage("That world environment did not exist.");

View File

@ -27,6 +27,9 @@ import java.util.List;
// Will use when we can compile with JDK 6
//import com.sun.xml.internal.ws.util.StringUtils;
/**
* Returns detailed information about a world.
*/
public class InfoCommand extends MultiverseCommand {
private MVWorldManager worldManager;
@ -106,17 +109,14 @@ public class InfoCommand extends MultiverseCommand {
message.add(new FancyHeader("General Info", colors));
message.add(new FancyMessage("World Name: ", world.getName(), colors));
message.add(new FancyMessage("World Alias: ", world.getColoredWorldString(), colors));
String enforced = "";
if (!MultiverseCore.EnforceGameModes) {
enforced = ChatColor.RED + " Not Enforced!";
}
message.add(new FancyMessage("Game Mode: ", world.getGameMode() + enforced, colors));
message.add(new FancyMessage("Game Mode: ", world.getGameMode().toString(), colors));
//message.add(new FancyMessage("Game Mode: ", StringUtils.capitalize(world.getGameMode().toString()), colors));
Location spawn = world.getSpawnLocation();
message.add(new FancyMessage("Spawn Location: ", LocationManipulation.strCoords(spawn), colors));
message.add(new FancyMessage("World Scale: ", world.getScaling() + "", colors));
if (world.getPrice() > 0) {
message.add(new FancyMessage("Price to enter this world: ", this.plugin.getBank().getFormattedAmount(p, world.getPrice(), world.getCurrency()), colors));
message.add(new FancyMessage("Price to enter this world: ",
this.plugin.getBank().getFormattedAmount(p, world.getPrice(), world.getCurrency()), colors));
} else {
message.add(new FancyMessage("Price to enter this world: ", ChatColor.GREEN + "FREE!", colors));
}
@ -148,13 +148,10 @@ public class InfoCommand extends MultiverseCommand {
message.add(new FancyHeader("Monster Settings", colors));
message.add(new FancyMessage("Multiverse Setting: ", world.canMonstersSpawn() + "", colors));
message.add(new FancyMessage("Bukkit Setting: ", world.getCBWorld().getAllowMonsters() + "", colors));
if (MultiverseCore.MobsDisabledInDefaultWorld) {
message.add(new FancyMessage(ChatColor.RED + "WARNING: ", "Monsters WILL NOT SPAWN IN THIS WORLD.", colors));
message.add(new FancyMessage(ChatColor.RED + "WARNING: ", "Check your server log for more details.", colors));
}
if (world.getMonsterList().size() > 0) {
if (world.canMonstersSpawn()) {
message.add(new FancyMessage("Monsters that" + ChatColor.RED + " CAN NOT " + ChatColor.GREEN + "spawn: ", toCommaSeperated(world.getMonsterList()), colors));
message.add(new FancyMessage("Monsters that" + ChatColor.RED + " CAN NOT "
+ ChatColor.GREEN + "spawn: ", toCommaSeperated(world.getMonsterList()), colors));
} else {
message.add(new FancyMessage("Monsters that" + ChatColor.GREEN + " CAN SPAWN: ", toCommaSeperated(world.getMonsterList()), colors));
}
@ -170,7 +167,8 @@ public class InfoCommand extends MultiverseCommand {
message.add(new FancyMessage("Bukkit Setting: ", world.getCBWorld().getAllowAnimals() + "", colors));
if (world.getMonsterList().size() > 0) {
if (world.canMonstersSpawn()) {
message.add(new FancyMessage("Animals that" + ChatColor.RED + " CAN NOT " + ChatColor.GREEN + "spawn: ", toCommaSeperated(world.getAnimalList()), colors));
message.add(new FancyMessage("Animals that" + ChatColor.RED + " CAN NOT "
+ ChatColor.GREEN + "spawn: ", toCommaSeperated(world.getAnimalList()), colors));
} else {
message.add(new FancyMessage("Animals that" + ChatColor.GREEN + " CAN SPAWN: ", toCommaSeperated(world.getAnimalList()), colors));
}
@ -198,6 +196,12 @@ public class InfoCommand extends MultiverseCommand {
return result;
}
/**
* Gets a "positive" or "negative" {@link ChatColor}.
*
* @param positive Whether this {@link ChatColor} should be "positive".
* @return The {@link ChatColor}.
*/
protected ChatColor getChatColor(boolean positive) {
return positive ? ChatColor.GREEN : ChatColor.RED;
}

View File

@ -18,6 +18,9 @@ import org.bukkit.permissions.PermissionDefault;
import java.util.ArrayList;
import java.util.List;
/**
* Displays a listing of all worlds that a player can enter.
*/
public class ListCommand extends PaginatedCoreCommand<String> {
public ListCommand(MultiverseCore plugin) {
@ -29,7 +32,7 @@ public class ListCommand extends PaginatedCoreCommand<String> {
this.addKey("mvl");
this.addKey("mv list");
this.setPermission("multiverse.core.list.worlds", "Displays a listing of all worlds that you can enter.", PermissionDefault.OP);
this.setItemsPerPage(8);
this.setItemsPerPage(8); // SUPPRESS CHECKSTYLE: MagicNumberCheck
}
private List<String> getFancyWorldList(Player p) {
@ -99,7 +102,8 @@ public class ListCommand extends PaginatedCoreCommand<String> {
if (filterObject.getFilter().length() > 0) {
availableWorlds = this.getFilteredItems(availableWorlds, filterObject.getFilter());
if (availableWorlds.size() == 0) {
sender.sendMessage(ChatColor.RED + "Sorry... " + ChatColor.WHITE + "No worlds matched your filter: " + ChatColor.AQUA + filterObject.getFilter());
sender.sendMessage(ChatColor.RED + "Sorry... " + ChatColor.WHITE
+ "No worlds matched your filter: " + ChatColor.AQUA + filterObject.getFilter());
return;
}
}

View File

@ -15,6 +15,9 @@ import org.bukkit.permissions.PermissionDefault;
import java.util.List;
/**
* Loads a world into Multiverse.
*/
public class LoadCommand extends MultiverseCommand {
public LoadCommand(MultiverseCore plugin) {

View File

@ -21,6 +21,9 @@ import java.util.List;
// This will contain all the properties that support the ADD/REMOVE
// Anything not in here will only support the SET action
/**
* Used to modify various aspects of worlds.
*/
public class ModifyAddCommand extends MultiverseCommand {
private MVWorldManager worldManager;
@ -36,7 +39,8 @@ public class ModifyAddCommand extends MultiverseCommand {
this.addCommandExample("/mvm " + ChatColor.GOLD + "add " + ChatColor.GREEN + "sheep " + ChatColor.RED + "animals");
this.addCommandExample("/mvm " + ChatColor.GOLD + "add " + ChatColor.GREEN + "creeper " + ChatColor.RED + "monsters");
this.addCommandExample("/mvm " + ChatColor.GOLD + "add " + ChatColor.GREEN + "MyWorld " + ChatColor.RED + "worldblacklist");
this.setPermission("multiverse.core.modify.add", "Modify various aspects of worlds. See the help wiki for how to use this command properly. If you do not include a world, the current world will be used.", PermissionDefault.OP);
this.setPermission("multiverse.core.modify.add", "Modify various aspects of worlds. See the help wiki for how to use this command properly. "
+ "If you do not include a world, the current world will be used.", PermissionDefault.OP);
this.worldManager = this.plugin.getMVWorldManager();
}
@ -78,7 +82,8 @@ public class ModifyAddCommand extends MultiverseCommand {
}
if (world.addToVariable(property, value)) {
sender.sendMessage(ChatColor.GREEN + "Success! " + ChatColor.AQUA + value + ChatColor.WHITE + " was " + ChatColor.GREEN + "added to " + ChatColor.GREEN + property);
sender.sendMessage(ChatColor.GREEN + "Success! " + ChatColor.AQUA
+ value + ChatColor.WHITE + " was " + ChatColor.GREEN + "added to " + ChatColor.GREEN + property);
} else {
sender.sendMessage(value + " could not be added to " + property);
}

View File

@ -18,6 +18,9 @@ import org.bukkit.permissions.PermissionDefault;
import java.util.List;
/**
* Removes all values from a world-property.
*/
public class ModifyClearCommand extends MultiverseCommand {
private MVWorldManager worldManager;
@ -33,7 +36,8 @@ public class ModifyClearCommand extends MultiverseCommand {
this.addCommandExample("/mvm " + ChatColor.GOLD + "clear " + ChatColor.RED + "animals");
this.addCommandExample("/mvm " + ChatColor.GOLD + "clear " + ChatColor.RED + "monsters");
this.addCommandExample("/mvm " + ChatColor.GOLD + "clear " + ChatColor.RED + "worldblacklist");
this.setPermission("multiverse.core.modify.clear", "Removes all values from a property. This will work on properties that contain lists.", PermissionDefault.OP);
this.setPermission("multiverse.core.modify.clear",
"Removes all values from a property. This will work on properties that contain lists.", PermissionDefault.OP);
this.worldManager = this.plugin.getMVWorldManager();
}
@ -73,9 +77,11 @@ public class ModifyClearCommand extends MultiverseCommand {
}
if (world.clearList(property)) {
sender.sendMessage(property + " was cleared. It contains 0 values now.");
sender.sendMessage(ChatColor.GREEN + "Success! " + ChatColor.AQUA + property + ChatColor.WHITE + " was " + ChatColor.GREEN + "CLEARED" + ChatColor.WHITE + ". It contains " + ChatColor.LIGHT_PURPLE + "0" + ChatColor.WHITE + " values now.");
sender.sendMessage(ChatColor.GREEN + "Success! " + ChatColor.AQUA + property + ChatColor.WHITE + " was "
+ ChatColor.GREEN + "CLEARED" + ChatColor.WHITE + ". It contains " + ChatColor.LIGHT_PURPLE + "0" + ChatColor.WHITE + " values now.");
} else {
sender.sendMessage(ChatColor.RED + "Error: " + ChatColor.GOLD + property + ChatColor.WHITE + " was " + ChatColor.GOLD + "NOT" + ChatColor.WHITE + " cleared.");
sender.sendMessage(ChatColor.RED + "Error: " + ChatColor.GOLD + property
+ ChatColor.WHITE + " was " + ChatColor.GOLD + "NOT" + ChatColor.WHITE + " cleared.");
}
}

View File

@ -19,6 +19,9 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Used to modify various aspects of worlds.
*/
public class ModifyCommand extends MultiverseCommand {
public ModifyCommand(MultiverseCore plugin) {
@ -34,7 +37,8 @@ public class ModifyCommand extends MultiverseCommand {
children.put("multiverse.core.modify.modify", true);
children.put("multiverse.core.modify.clear", true);
children.put("multiverse.core.modify.remove", true);
Permission modify = new Permission("multiverse.core.modify", "Modify various aspects of worlds. It requires add/set/clear/remove. See the examples below", PermissionDefault.OP, children);
Permission modify = new Permission("multiverse.core.modify",
"Modify various aspects of worlds. It requires add/set/clear/remove. See the examples below", PermissionDefault.OP, children);
this.addCommandExample(ChatColor.AQUA + "/mv modify set ?");
this.addCommandExample(ChatColor.GREEN + "/mv modify add ?");
this.addCommandExample(ChatColor.BLUE + "/mv modify clear ?");
@ -42,6 +46,13 @@ public class ModifyCommand extends MultiverseCommand {
this.setPermission(modify);
}
/**
* Validates the specified action.
*
* @param action The {@link Action}.
* @param property The property.
* @return Whether this action is valid.
*/
protected static boolean validateAction(Action action, String property) {
if (action != Action.Set) {
try {

View File

@ -18,6 +18,9 @@ import org.bukkit.permissions.PermissionDefault;
import java.util.List;
/**
* Removes values from a world-property.
*/
public class ModifyRemoveCommand extends MultiverseCommand {
private MVWorldManager worldManager;
@ -37,7 +40,8 @@ public class ModifyRemoveCommand extends MultiverseCommand {
this.addCommandExample("/mvm " + ChatColor.GOLD + "remove " + ChatColor.GREEN + "sheep " + ChatColor.RED + "animals");
this.addCommandExample("/mvm " + ChatColor.GOLD + "remove " + ChatColor.GREEN + "creeper " + ChatColor.RED + "monsters");
this.addCommandExample("/mvm " + ChatColor.GOLD + "remove " + ChatColor.GREEN + "MyWorld " + ChatColor.RED + "worldblacklist");
this.setPermission("multiverse.core.modify.remove", "Modify various aspects of worlds. See the help wiki for how to use this command properly. If you do not include a world, the current world will be used.", PermissionDefault.OP);
this.setPermission("multiverse.core.modify.remove", "Modify various aspects of worlds. See the help wiki for how to use this command properly. "
+ "If you do not include a world, the current world will be used.", PermissionDefault.OP);
this.worldManager = this.plugin.getMVWorldManager();
}
@ -78,9 +82,11 @@ public class ModifyRemoveCommand extends MultiverseCommand {
return;
}
if (world.removeFromVariable(property, value)) {
sender.sendMessage(ChatColor.GREEN + "Success! " + ChatColor.AQUA + value + ChatColor.WHITE + " was " + ChatColor.RED + "removed from " + ChatColor.GREEN + property);
sender.sendMessage(ChatColor.GREEN + "Success! " + ChatColor.AQUA + value + ChatColor.WHITE
+ " was " + ChatColor.RED + "removed from " + ChatColor.GREEN + property);
} else {
sender.sendMessage(ChatColor.RED + "There was an error removing " + ChatColor.GRAY + value + ChatColor.WHITE + " from " + ChatColor.GOLD + property);
sender.sendMessage(ChatColor.RED + "There was an error removing " + ChatColor.GRAY
+ value + ChatColor.WHITE + " from " + ChatColor.GOLD + property);
}
}

View File

@ -19,6 +19,9 @@ import org.bukkit.permissions.PermissionDefault;
import java.util.List;
/**
* Used to set world-properties.
*/
public class ModifySetCommand extends MultiverseCommand {
private MVWorldManager worldManager;
@ -48,7 +51,8 @@ public class ModifySetCommand extends MultiverseCommand {
this.addCommandExample("/mvm " + ChatColor.GOLD + "set " + ChatColor.GREEN + "heal " + ChatColor.RED + "true");
this.addCommandExample("/mvm " + ChatColor.GOLD + "set " + ChatColor.GREEN + "adjustspawn " + ChatColor.RED + "false");
this.addCommandExample("/mvm " + ChatColor.GOLD + "set " + ChatColor.GREEN + "spawn");
this.setPermission("multiverse.core.modify.set", "Modify various aspects of worlds. See the help wiki for how to use this command properly. If you do not include a world, the current world will be used.", PermissionDefault.OP);
this.setPermission("multiverse.core.modify.set", "Modify various aspects of worlds. See the help wiki for how to use this command properly. "
+ "If you do not include a world, the current world will be used.", PermissionDefault.OP);
}
@Override
@ -105,7 +109,8 @@ public class ModifySetCommand extends MultiverseCommand {
}
try {
if (world.setProperty(property, value, sender)) {
sender.sendMessage(ChatColor.GREEN + "Success!" + ChatColor.WHITE + " Property " + ChatColor.AQUA + property + ChatColor.WHITE + " was set to " + ChatColor.GREEN + value);
sender.sendMessage(ChatColor.GREEN + "Success!" + ChatColor.WHITE + " Property " + ChatColor.AQUA + property
+ ChatColor.WHITE + " was set to " + ChatColor.GREEN + value);
} else {
sender.sendMessage(world.getProperty(property, Object.class).getHelp());
}

View File

@ -8,18 +8,30 @@
package com.onarandombox.MultiverseCore.commands;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.utils.MVMessaging;
import com.pneumaticraft.commandhandler.Command;
import org.bukkit.command.CommandSender;
import java.util.List;
/**
* A generic Multiverse-command.
*/
public abstract class MultiverseCommand extends Command {
/**
* The reference to the core.
*/
protected MultiverseCore plugin;
/**
* The reference to {@link MVMessaging}.
*/
protected MVMessaging messaging;
public MultiverseCommand(MultiverseCore plugin) {
super(plugin);
this.plugin = plugin;
this.messaging = this.plugin.getMessaging();
}
@Override

View File

@ -14,28 +14,60 @@ import org.bukkit.plugin.java.JavaPlugin;
import java.util.List;
/**
* A generic paginated command.
* @param <T> The type of items on the page.
*/
public abstract class PaginatedCommand<T> extends Command {
protected int itemsPerPage = 9;
private static final int DEFAULT_ITEMS_PER_PAGE = 9;
/**
* The number of items per page.
*/
protected int itemsPerPage = DEFAULT_ITEMS_PER_PAGE;
public PaginatedCommand(JavaPlugin plugin) {
super(plugin);
}
/**
* Set the number of items per page.
*
* @param items The new number of items per page.
*/
protected void setItemsPerPage(int items) {
itemsPerPage = items;
}
/**
* Gets filtered items.
* @param availableItems All available items.
* @param filter The filter-{@link String}.
* @return A list of items that match the filter.
*/
protected abstract List<T> getFilteredItems(List<T> availableItems, String filter);
/**
* Constructs a single string from a list of strings.
*
* @param list The {@link List} of strings.
* @return A single {@link String}.
*/
protected String stitchThisString(List<String> list) {
String returnstr = "";
StringBuilder builder = new StringBuilder();
for (String s : list) {
returnstr += s + " ";
builder.append(s);
builder.append(' ');
}
return returnstr;
return builder.toString();
}
/**
* Shows a page.
*
* @param page The number of the page to show.
* @param sender The {@link CommandSender} that wants to see the page.
* @param cmds The items that should be displayed on the page.
*/
protected void showPage(int page, CommandSender sender, List<T> cmds) {
// Ensure the page is at least 1.
page = (page <= 0) ? 1 : page;
@ -52,8 +84,20 @@ public abstract class PaginatedCommand<T> extends Command {
}
}
/**
* Converts an item into a string.
*
* @param item The item.
* @return A {@link String}.
*/
protected abstract String getItemText(T item);
/**
* Constructs a {@link FilterObject} from a {@link List} of arguments.
*
* @param args The {@link List} of arguments.
* @return The {@link FilterObject}.
*/
protected FilterObject getPageAndFilter(List<String> args) {
int page = 1;
@ -80,6 +124,9 @@ public abstract class PaginatedCommand<T> extends Command {
return new FilterObject(page, filter);
}
/**
* "Key-Object" containing information about the page and the filter that were requested.
*/
protected class FilterObject {
private Integer page;
private String filter;
@ -89,14 +136,27 @@ public abstract class PaginatedCommand<T> extends Command {
this.filter = filter;
}
/**
* Gets the page.
* @return The page.
*/
public Integer getPage() {
return this.page;
}
/**
* Sets the page.
*
* @param page The new page.
*/
public void setPage(int page) {
this.page = page;
}
/**
* Gets the filter.
* @return The filter.
*/
public String getFilter() {
return this.filter;
}

View File

@ -9,7 +9,14 @@ package com.onarandombox.MultiverseCore.commands;
import com.onarandombox.MultiverseCore.MultiverseCore;
/**
* A generic paginated Multiverse-command.
* @param <T> The type of items on the page.
*/
public abstract class PaginatedCoreCommand<T> extends PaginatedCommand<T> {
/**
* The reference to the core.
*/
protected MultiverseCore plugin;
public PaginatedCoreCommand(MultiverseCore plugin) {

View File

@ -20,6 +20,9 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Removes a type of mob from a world.
*/
public class PurgeCommand extends MultiverseCommand {
private MVWorldManager worldManager;

View File

@ -15,6 +15,9 @@ import org.bukkit.permissions.PermissionDefault;
import java.util.ArrayList;
import java.util.List;
/**
* Regenerates a world.
*/
public class RegenCommand extends MultiverseCommand {
public RegenCommand(MultiverseCore plugin) {
@ -28,7 +31,8 @@ public class RegenCommand extends MultiverseCommand {
this.addCommandExample("/mv regen " + ChatColor.GREEN + "MyWorld" + ChatColor.GOLD + " -s");
this.addCommandExample("or specifiy a seed to get that one:");
this.addCommandExample("/mv regen " + ChatColor.GREEN + "MyWorld" + ChatColor.GOLD + " -s" + ChatColor.AQUA + " gargamel");
this.setPermission("multiverse.core.delete", "Deletes a world on your server. " + ChatColor.RED + "PERMANENTLY.", PermissionDefault.OP);
this.setPermission("multiverse.core.regen", "Regenerates a world on your server. The previous state will be lost "
+ ChatColor.RED + "PERMANENTLY.", PermissionDefault.OP);
}
@Override
@ -37,12 +41,13 @@ public class RegenCommand extends MultiverseCommand {
Boolean randomseed = (args.size() == 2 && args.get(1).equalsIgnoreCase("-s"));
String seed = (args.size() == 3) ? args.get(2) : "";
Class<?> paramTypes[] = {String.class, Boolean.class, Boolean.class, String.class};
Class<?>[] paramTypes = {String.class, Boolean.class, Boolean.class, String.class};
List<Object> objectArgs = new ArrayList<Object>();
objectArgs.add(args.get(0));
objectArgs.add(useseed);
objectArgs.add(randomseed);
objectArgs.add(seed);
this.plugin.getCommandHandler().queueCommand(sender, "mvregen", "regenWorld", objectArgs, paramTypes, ChatColor.GREEN + "World Regenerated!", ChatColor.RED + "World could NOT be regenerated!");
this.plugin.getCommandHandler().queueCommand(sender, "mvregen", "regenWorld", objectArgs,
paramTypes, ChatColor.GREEN + "World Regenerated!", ChatColor.RED + "World could NOT be regenerated!");
}
}

View File

@ -16,6 +16,9 @@ import org.bukkit.permissions.PermissionDefault;
import java.util.ArrayList;
import java.util.List;
/**
* Reloads worlds.yml and config.yml.
*/
public class ReloadCommand extends MultiverseCommand {
public ReloadCommand(MultiverseCore plugin) {

View File

@ -14,6 +14,9 @@ import org.bukkit.permissions.PermissionDefault;
import java.util.List;
/**
* Unloads a world and removes it from the config.
*/
public class RemoveCommand extends MultiverseCommand {
public RemoveCommand(MultiverseCore plugin) {
@ -24,7 +27,8 @@ public class RemoveCommand extends MultiverseCommand {
this.addKey("mvremove");
this.addKey("mv remove");
this.addCommandExample("/mv remove " + ChatColor.GREEN + "MyWorld");
this.setPermission("multiverse.core.remove", "Unloads a world from Multiverse and removes it from worlds.yml, this does NOT DELETE the world folder.", PermissionDefault.OP);
this.setPermission("multiverse.core.remove",
"Unloads a world from Multiverse and removes it from worlds.yml, this does NOT DELETE the world folder.", PermissionDefault.OP);
}
@Override

View File

@ -20,6 +20,9 @@ import org.bukkit.permissions.PermissionDefault;
import java.util.List;
/**
* Sets the spawn for a world.
*/
public class SetSpawnCommand extends MultiverseCommand {
public SetSpawnCommand(MultiverseCore plugin) {
super(plugin);
@ -40,6 +43,11 @@ public class SetSpawnCommand extends MultiverseCommand {
setWorldSpawn(sender);
}
/**
* Does the actual spawn-setting-work.
*
* @param sender The {@link CommandSender} that's setting the spawn.
*/
protected void setWorldSpawn(CommandSender sender) {
if (sender instanceof Player) {
Player p = (Player) sender;
@ -49,7 +57,7 @@ public class SetSpawnCommand extends MultiverseCommand {
if (foundWorld != null) {
foundWorld.setSpawnLocation(p.getLocation());
BlockSafety bs = new BlockSafety();
if(!bs.playerCanSpawnHereSafely(p.getLocation()) && foundWorld.getAdjustSpawn()) {
if (!bs.playerCanSpawnHereSafely(p.getLocation()) && foundWorld.getAdjustSpawn()) {
sender.sendMessage("It looks like that location would normally be unsafe. But I trust you.");
sender.sendMessage("I'm turning off the Safe-T-Teleporter for spawns to this world.");
sender.sendMessage("If you want this turned back on just do:");

View File

@ -14,6 +14,9 @@ import org.bukkit.permissions.PermissionDefault;
import java.util.List;
/**
* Takes the player to the latest bed he's slept in.
*/
public class SleepCommand extends MultiverseCommand {
public SleepCommand(MultiverseCore plugin) {

View File

@ -18,11 +18,15 @@ import org.bukkit.permissions.PermissionDefault;
import java.util.List;
/**
* Teleports a player to the spawn.
*/
public class SpawnCommand extends MultiverseCommand {
public SpawnCommand(MultiverseCore plugin) {
super(plugin);
Permission otherPerm = new Permission("multiverse.core.spawn.other", "Teleports another player to the spawn of the world they are in.", PermissionDefault.OP);
Permission otherPerm = new Permission("multiverse.core.spawn.other",
"Teleports another player to the spawn of the world they are in.", PermissionDefault.OP);
this.setName("Spawn");
this.setCommandUsage("/mv spawn" + ChatColor.GOLD + " [PLAYER]");
this.setArgRange(0, 1);

View File

@ -19,6 +19,9 @@ import org.getspout.spoutapi.player.SpoutPlayer;
import java.util.List;
/**
* Edit a world with spout.
*/
public class SpoutCommand extends MultiverseCommand {
public SpoutCommand(MultiverseCore plugin) {
@ -48,10 +51,13 @@ public class SpoutCommand extends MultiverseCommand {
}
PopupScreen pop = new GenericPopup();
GenericButton button = new GenericButton("Fish");
// TODO maybe use constants for these
// BEGIN CHECKSTYLE-SUPPRESSION: MagicNumberCheck
button.setX(50);
button.setY(50);
button.setWidth(100);
button.setHeight(40);
// END CHECKSTYLE-SUPPRESSION: MagicNumberCheck
pop.attachWidget(this.plugin, button);
sender.sendMessage(ChatColor.GREEN + "YAY!");
p.getMainScreen().attachPopupScreen(pop);

View File

@ -15,7 +15,6 @@ import com.onarandombox.MultiverseCore.destination.WorldDestination;
import com.onarandombox.MultiverseCore.enums.TeleportResult;
import com.onarandombox.MultiverseCore.event.MVTeleportEvent;
import com.onarandombox.MultiverseCore.utils.LocationManipulation;
import com.onarandombox.MultiverseCore.utils.MVMessaging;
import com.onarandombox.MultiverseCore.utils.SafeTTeleporter;
import org.bukkit.ChatColor;
import org.bukkit.Location;
@ -29,6 +28,9 @@ import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
/**
* Used to teleport players.
*/
public class TeleportCommand extends MultiverseCommand {
private SafeTTeleporter playerTeleporter;
@ -45,6 +47,8 @@ public class TeleportCommand extends MultiverseCommand {
this.setPermission(menu);
}
private static final int UNSAFE_TELEPORT_EXPIRE_DELAY = 15;
@Override
public void runCommand(CommandSender sender, List<String> args) {
// Check if the command was sent from a Player.
@ -59,7 +63,8 @@ public class TeleportCommand extends MultiverseCommand {
if (args.size() == 2) {
teleportee = this.plugin.getServer().getPlayer(args.get(0));
if (teleportee == null) {
sender.sendMessage("Sorry, I couldn't find player: " + args.get(0));
this.messaging.sendMessage(sender, String.format("Sorry, I couldn't find player: %s%s",
ChatColor.GOLD, args.get(0)), false);
return;
}
destinationName = args.get(1);
@ -67,7 +72,7 @@ public class TeleportCommand extends MultiverseCommand {
} else {
destinationName = args.get(0);
if (!(sender instanceof Player)) {
sender.sendMessage("From the console, you must specify a player to teleport");
this.messaging.sendMessage(sender, String.format("From the console, you must specify a player to teleport"), false);
return;
}
teleportee = (Player) sender;
@ -77,7 +82,9 @@ public class TeleportCommand extends MultiverseCommand {
String[] cannonSpeed = destinationName.split("-");
try {
double speed = Double.parseDouble(cannonSpeed[1]);
destinationName = "ca:" + teleportee.getWorld().getName() + ":" + teleportee.getLocation().getX() + "," + teleportee.getLocation().getY() + "," + teleportee.getLocation().getZ() + ":" + teleportee.getLocation().getPitch() + ":" + teleportee.getLocation().getYaw() + ":" + speed;
destinationName = "ca:" + teleportee.getWorld().getName() + ":" + teleportee.getLocation().getX()
+ "," + teleportee.getLocation().getY() + "," + teleportee.getLocation().getZ() + ":"
+ teleportee.getLocation().getPitch() + ":" + teleportee.getLocation().getYaw() + ":" + speed;
} catch (Exception e) {
destinationName = "i:invalid";
}
@ -95,7 +102,8 @@ public class TeleportCommand extends MultiverseCommand {
}
if (d != null && d instanceof InvalidDestination) {
sender.sendMessage("Multiverse does not know how to take you to: " + ChatColor.RED + destinationName);
this.messaging.sendMessage(sender, String.format("Multiverse does not know how to take you to %s%s",
ChatColor.RED, destinationName), false);
return;
}
@ -107,14 +115,17 @@ public class TeleportCommand extends MultiverseCommand {
if (teleportee.equals(teleporter)) {
teleporter.sendMessage("Doesn't look like you're allowed to go " + ChatColor.RED + "there...");
} else {
teleporter.sendMessage("Doesn't look like you're allowed to send " + ChatColor.GOLD + teleportee.getName() + ChatColor.WHITE + " to " + ChatColor.RED + "there...");
teleporter.sendMessage("Doesn't look like you're allowed to send " + ChatColor.GOLD
+ teleportee.getName() + ChatColor.WHITE + " to " + ChatColor.RED + "there...");
}
return;
} else if (teleporter != null && !this.plugin.getMVPerms().canTravelFromLocation(teleporter, d.getLocation(teleportee))) {
if (teleportee.equals(teleporter)) {
teleporter.sendMessage("DOH! Doesn't look like you can get to " + ChatColor.RED + "THERE from " + ChatColor.GREEN + ((Player) teleporter).getWorld().getName());
this.messaging.sendMessage(teleporter, String.format("DOH! Doesn't look like you can get to %s%s %sfrom where you are...",
ChatColor.GREEN, d.toString(), ChatColor.WHITE), false);
} else {
teleporter.sendMessage("DOH! Doesn't look like " + ChatColor.GREEN + ((Player) teleporter).getWorld().getName() + " can get to " + ChatColor.RED + "THERE from where they are...");
this.messaging.sendMessage(teleporter, String.format("DOH! Doesn't look like %s%s %scan get to %sTHERE from where they are...",
ChatColor.GREEN, ((Player) teleporter).getWorld().getName(), ChatColor.WHITE, ChatColor.RED), false);
}
return;
}
@ -127,14 +138,19 @@ public class TeleportCommand extends MultiverseCommand {
if (teleportee.getWorld().equals(w)) {
if (teleporter.equals(teleportee)) {
if (!this.plugin.getMVPerms().hasPermission(teleporter, "multiverse.core.spawn.self", true)) {
teleporter.sendMessage("Sorry you don't have permission to go to the world spawn!");
teleporter.sendMessage(ChatColor.RED + " (multiverse.core.spawn.self)");
this.messaging.sendMessages(teleporter, new String[]{
String.format("Sorry you don't have permission to go to the world spawn!"),
String.format("%s (multiverse.core.spawn.self)",
ChatColor.RED) }, false);
return;
}
} else {
if (!this.plugin.getMVPerms().hasPermission(teleporter, "multiverse.core.spawn.other", true)) {
teleporter.sendMessage("Sorry you don't have permission to send " + teleportee.getDisplayName() + "to the world spawn!");
teleporter.sendMessage(ChatColor.RED + " (multiverse.core.spawn.other)");
this.messaging.sendMessages(teleporter, new String[]{
String.format("Sorry you don't have permission to send %s to the world spawn!",
teleportee.getDisplayName()),
String.format("%s (multiverse.core.spawn.other)",
ChatColor.RED) }, false);
return;
}
}
@ -142,14 +158,14 @@ public class TeleportCommand extends MultiverseCommand {
}
if (d.getLocation(teleportee) == null) {
teleporter.sendMessage("Sorry Boss, I tried everything, but just couldn't teleport ya there!");
this.messaging.sendMessage(teleporter, "Sorry Boss, I tried everything, but just couldn't teleport ya there!", false);
return;
}
TeleportResult result = this.playerTeleporter.safelyTeleport(teleporter, teleportee, d);
if (result == TeleportResult.FAIL_UNSAFE) {
this.plugin.log(Level.FINE, "Could not teleport " + teleportee.getName() + " to " + LocationManipulation.strCoordsRaw(d.getLocation(teleportee)));
this.plugin.log(Level.FINE, "Queueing Command");
Class<?> paramTypes[] = {CommandSender.class, Player.class, Location.class};
Class<?>[] paramTypes = { CommandSender.class, Player.class, Location.class };
List<Object> items = new ArrayList<Object>();
items.add(teleporter);
items.add(teleportee);
@ -158,24 +174,31 @@ public class TeleportCommand extends MultiverseCommand {
if (!teleportee.equals(teleporter)) {
player = teleportee.getName();
}
String message = ChatColor.GREEN + "Multiverse" + ChatColor.WHITE + " did not teleport " + ChatColor.AQUA + player + ChatColor.WHITE + " to " + ChatColor.DARK_AQUA + d.getName() + ChatColor.WHITE + " because it was unsafe.";
this.plugin.getCommandHandler().queueCommand(sender, "mvteleport", "teleportPlayer", items, paramTypes, message, "Would you like to try anyway?", "", "", 15);
} else {
// Player was teleported successfully (or the tp event was fired I should say);
String message = String.format("%sMultiverse %sdid not teleport %s%s%sto %s%s%sbecause it was unsafe.",
ChatColor.GREEN, ChatColor.WHITE, ChatColor.AQUA, player, ChatColor.WHITE, ChatColor.DARK_AQUA, d.getName(), ChatColor.WHITE);
this.plugin.getCommandHandler().queueCommand(sender, "mvteleport", "teleportPlayer", items,
paramTypes, message, "Would you like to try anyway?", "", "", UNSAFE_TELEPORT_EXPIRE_DELAY);
}
// else: Player was teleported successfully (or the tp event was fired I should say)
}
private boolean checkSendPermissions(CommandSender teleporter, Player teleportee, MVDestination destination) {
MVMessaging message = this.plugin.getMessaging();
if (teleporter.equals(teleportee)) {
if (!this.plugin.getMVPerms().hasPermission(teleporter, "multiverse.teleport.self." + destination.getIdentifier(), true)) {
message.sendMessages(teleporter, new String[]{"You don't have permission to teleport yourself to a " + ChatColor.GREEN + destination.getType() + " Destination.", ChatColor.RED + " (multiverse.teleport.self." + destination.getIdentifier() + ")"});
this.messaging.sendMessages(teleporter, new String[]{
String.format("%sYou don't have permission to teleport %syourself %sto a %s%s %sDestination",
ChatColor.WHITE, ChatColor.AQUA, ChatColor.WHITE, ChatColor.RED, destination.getType(), ChatColor.WHITE),
String.format("%s (multiverse.teleport.self.%s)",
ChatColor.RED, destination.getIdentifier()) }, false);
return false;
}
} else {
if (!this.plugin.getMVPerms().hasPermission(teleporter, "multiverse.teleport.other." + destination.getIdentifier(), true)) {
message.sendMessages(teleporter, new String[]{"You don't have permission to teleport another player to a " + ChatColor.GREEN + destination.getType() + " Destination.", ChatColor.RED + " (multiverse.teleport.other." + destination.getIdentifier() + ")"});
this.messaging.sendMessages(teleporter, new String[]{
String.format("You don't have permission to teleport another player to a %s%s Destination.",
ChatColor.GREEN, destination.getType()),
String.format("%s(multiverse.teleport.other.%s)",
ChatColor.RED, destination.getIdentifier()) }, false);
return false;
}
}

View File

@ -15,6 +15,9 @@ import org.bukkit.permissions.PermissionDefault;
import java.util.List;
/**
* Unloads worlds from Multiverse.
*/
public class UnloadCommand extends MultiverseCommand {
public UnloadCommand(MultiverseCore plugin) {
@ -24,7 +27,8 @@ public class UnloadCommand extends MultiverseCommand {
this.setArgRange(1, 1);
this.addKey("mvunload");
this.addKey("mv unload");
this.setPermission("multiverse.core.unload", "Unloads a world from Multiverse. This does NOT remove the world folder. This does NOT remove it from the config file.", PermissionDefault.OP);
this.setPermission("multiverse.core.unload",
"Unloads a world from Multiverse. This does NOT remove the world folder. This does NOT remove it from the config file.", PermissionDefault.OP);
}
@Override

View File

@ -8,7 +8,7 @@
package com.onarandombox.MultiverseCore.commands;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.event.MVVersionRequestEvent;
import com.onarandombox.MultiverseCore.event.MVVersionEvent;
import com.onarandombox.MultiverseCore.utils.webpaste.PasteFailedException;
import com.onarandombox.MultiverseCore.utils.webpaste.PasteService;
import com.onarandombox.MultiverseCore.utils.webpaste.PasteServiceFactory;
@ -21,6 +21,9 @@ import org.bukkit.permissions.PermissionDefault;
import java.util.List;
import java.util.logging.Level;
/**
* Dumps version info to the console.
*/
public class VersionCommand extends MultiverseCommand {
public VersionCommand(MultiverseCore plugin) {
@ -31,11 +34,10 @@ public class VersionCommand extends MultiverseCommand {
this.addKey("mv version");
this.addKey("mvv");
this.addKey("mvversion");
this.setPermission("multiverse.core.version", "Dumps version info to the console, optionally to pastie.org with -p or pastebin.com with a -b.", PermissionDefault.TRUE);
this.setPermission("multiverse.core.version",
"Dumps version info to the console, optionally to pastie.org with -p or pastebin.com with a -b.", PermissionDefault.TRUE);
}
private String pasteBinBuffer = "";
@Override
public void runCommand(CommandSender sender, List<String> args) {
// Check if the command was sent from a Player.
@ -43,33 +45,42 @@ public class VersionCommand extends MultiverseCommand {
sender.sendMessage("Version info dumped to console. Please check your server logs.");
}
logAndAddToPasteBinBuffer("Multiverse-Core Version: " + this.plugin.getDescription().getVersion());
logAndAddToPasteBinBuffer("Bukkit Version: " + this.plugin.getServer().getVersion());
logAndAddToPasteBinBuffer("Loaded Worlds: " + this.plugin.getMVWorldManager().getMVWorlds().size());
logAndAddToPasteBinBuffer("Multiverse Plugins Loaded: " + this.plugin.getPluginCount());
logAndAddToPasteBinBuffer("Economy being used: " + this.plugin.getBank().getEconUsed());
logAndAddToPasteBinBuffer("Permissions Plugin: " + this.plugin.getMVPerms().getType());
logAndAddToPasteBinBuffer("Dumping Config Values: (version " + this.plugin.getMVConfiguration().getString("version", "NOT SET") + ")");
logAndAddToPasteBinBuffer("messagecooldown: " + "Not yet IMPLEMENTED");
logAndAddToPasteBinBuffer("teleportcooldown: " + "Not yet IMPLEMENTED");
logAndAddToPasteBinBuffer("worldnameprefix: " + MultiverseCore.PrefixChat);
logAndAddToPasteBinBuffer("enforceaccess: " + MultiverseCore.EnforceAccess);
logAndAddToPasteBinBuffer("enforcegamemodes: " + MultiverseCore.EnforceGameModes);
logAndAddToPasteBinBuffer("displaypermerrors: " + MultiverseCore.DisplayPermErrors);
logAndAddToPasteBinBuffer("teleportintercept: " + MultiverseCore.TeleportIntercept);
logAndAddToPasteBinBuffer("debug: " + MultiverseCore.GlobalDebug);
logAndAddToPasteBinBuffer("Special Code: FRN002");
StringBuilder buffer = new StringBuilder();
buffer.append("[Multiverse-Core] Multiverse-Core Version: ").append(this.plugin.getDescription().getVersion()).append('\n');
buffer.append("[Multiverse-Core] Bukkit Version: ").append(this.plugin.getServer().getVersion()).append('\n');
buffer.append("[Multiverse-Core] Loaded Worlds: ").append(this.plugin.getMVWorldManager().getMVWorlds().size()).append('\n');
buffer.append("[Multiverse-Core] Multiverse Plugins Loaded: ").append(this.plugin.getPluginCount()).append('\n');
buffer.append("[Multiverse-Core] Economy being used: ").append(this.plugin.getBank().getEconUsed()).append('\n');
buffer.append("[Multiverse-Core] Permissions Plugin: ").append(this.plugin.getMVPerms().getType()).append('\n');
buffer.append("[Multiverse-Core] Dumping Config Values: (version ")
.append(this.plugin.getMVConfiguration().getDouble("version", -1)).append(")").append('\n');
buffer.append("[Multiverse-Core] messagecooldown: ").append(this.plugin.getMessaging().getCooldown()).append('\n');
buffer.append("[Multiverse-Core] teleportcooldown: ").append("Not yet IMPLEMENTED").append('\n');
buffer.append("[Multiverse-Core] worldnameprefix: ").append(MultiverseCore.PrefixChat).append('\n');
buffer.append("[Multiverse-Core] enforceaccess: ").append(MultiverseCore.EnforceAccess).append('\n');
buffer.append("[Multiverse-Core] displaypermerrors: ").append(MultiverseCore.DisplayPermErrors).append('\n');
buffer.append("[Multiverse-Core] teleportintercept: ").append(MultiverseCore.TeleportIntercept).append('\n');
buffer.append("[Multiverse-Core] firstspawnoverride: ").append(MultiverseCore.FirstSpawnOverride).append('\n');
buffer.append("[Multiverse-Core] firstspawnworld: ").append(this.plugin.getMVConfiguration().getString("firstspawnworld", "NOT SET")).append('\n');
buffer.append("[Multiverse-Core] debug: ").append(MultiverseCore.GlobalDebug).append('\n');
buffer.append("[Multiverse-Core] Special Code: FRN002").append('\n');
MVVersionRequestEvent versionEvent = new MVVersionRequestEvent(pasteBinBuffer);
MVVersionEvent versionEvent = new MVVersionEvent(buffer.toString());
this.plugin.getServer().getPluginManager().callEvent(versionEvent);
pasteBinBuffer = versionEvent.getPasteBinBuffer();
// log to console
String data = versionEvent.getVersionInfo();
String[] lines = data.split("\n");
for (String line : lines) {
this.plugin.log(Level.INFO, line);
}
if (args.size() == 1) {
String pasteUrl = "";
if (args.get(0).equalsIgnoreCase("-p")) {
pasteUrl = this.postToService(PasteServiceType.PASTIE, true); // private post to pastie
pasteUrl = postToService(PasteServiceType.PASTIE, true, data); // private post to pastie
} else if (args.get(0).equalsIgnoreCase("-b")) {
pasteUrl = this.postToService(PasteServiceType.PASTEBIN, true); // private post to pastie
pasteUrl = postToService(PasteServiceType.PASTEBIN, true, data); // private post to pastie
} else {
return;
}
@ -79,11 +90,6 @@ public class VersionCommand extends MultiverseCommand {
}
}
private void logAndAddToPasteBinBuffer(String string) {
this.pasteBinBuffer += "[Multiverse-Core] " + string + "\n";
this.plugin.log(Level.INFO, string);
}
/**
* Send the current contents of this.pasteBinBuffer to a web service.
*
@ -91,10 +97,10 @@ public class VersionCommand extends MultiverseCommand {
* @param isPrivate Should the paste be marked as private.
* @return URL of visible paste
*/
private String postToService(PasteServiceType type, boolean isPrivate) {
private static String postToService(PasteServiceType type, boolean isPrivate, String pasteData) {
PasteService ps = PasteServiceFactory.getService(type, isPrivate);
try {
return ps.postData(ps.encodeData(this.pasteBinBuffer), ps.getPostURL());
return ps.postData(ps.encodeData(pasteData), ps.getPostURL());
} catch (PasteFailedException e) {
System.out.print(e);
return "Error posting to service";

View File

@ -18,6 +18,9 @@ import org.bukkit.permissions.PermissionDefault;
import java.util.ArrayList;
import java.util.List;
/**
* States who is in what world.
*/
public class WhoCommand extends MultiverseCommand {
private MVWorldManager worldManager;

View File

@ -0,0 +1,4 @@
/**
* This package contains all Commands.
*/
package com.onarandombox.MultiverseCore.commands;

View File

@ -0,0 +1,115 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2012. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.configuration;
/**
* A {@link String} config-property that will NOT be saved to the config.
*/
public class ActiveStringConfigProperty implements MVActiveConfigProperty<String> {
private String name;
private String value;
private String method;
private String help;
public ActiveStringConfigProperty(String name, String defaultValue, String help) {
this.name = name;
this.help = help;
this.value = defaultValue;
this.parseValue(defaultValue);
}
public ActiveStringConfigProperty(String name, String defaultValue, String help, String method) {
this(name, defaultValue, help);
this.method = method;
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return this.name;
}
/**
* {@inheritDoc}
*/
@Override
public String getValue() {
return this.value;
}
/**
* {@inheritDoc}
*/
@Override
public String getMethod() {
return this.method;
}
/**
* {@inheritDoc}
*/
@Override
public void setMethod(String methodName) {
this.method = methodName;
}
/**
* {@inheritDoc}
*/
@Override
public Class<?> getPropertyClass() {
return String.class;
}
/**
* {@inheritDoc}
*/
@Override
public boolean parseValue(String value) {
if (value == null) {
return false;
}
this.setValue(value);
return true;
}
/**
* {@inheritDoc}
*/
@Override
public String getConfigNode() {
return "";
}
/**
* {@inheritDoc}
*/
@Override
public String getHelp() {
return this.help;
}
/**
* {@inheritDoc}
*/
@Override
public boolean setValue(String value) {
if (value == null) {
return false;
}
this.value = value;
return true;
}
@Override
public String toString() {
return value;
}
}

View File

@ -9,12 +9,16 @@ package com.onarandombox.MultiverseCore.configuration;
import org.bukkit.configuration.ConfigurationSection;
public class BooleanConfigProperty implements MVConfigProperty<Boolean> {
/**
* A {@link Boolean} config-property.
*/
public class BooleanConfigProperty implements MVActiveConfigProperty<Boolean> {
private String name;
private Boolean value;
private String configNode;
private ConfigurationSection section;
private String help;
private String method;
public BooleanConfigProperty(ConfigurationSection section, String name, Boolean defaultValue, String help) {
this(section, name, defaultValue, name, help);
@ -29,16 +33,30 @@ public class BooleanConfigProperty implements MVConfigProperty<Boolean> {
this.setValue(this.section.getBoolean(this.configNode, defaultValue));
}
public BooleanConfigProperty(ConfigurationSection section, String name, Boolean defaultValue, String configNode, String help, String method) {
this(section, name, defaultValue, configNode, help);
this.method = method;
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return this.name;
}
/**
* {@inheritDoc}
*/
@Override
public Boolean getValue() {
return this.value;
}
/**
* {@inheritDoc}
*/
@Override
public boolean setValue(Boolean value) {
if (value == null) {
@ -49,6 +67,9 @@ public class BooleanConfigProperty implements MVConfigProperty<Boolean> {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean parseValue(String value) {
if (value == null) {
@ -61,18 +82,54 @@ public class BooleanConfigProperty implements MVConfigProperty<Boolean> {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public String getConfigNode() {
return this.configNode;
}
/**
* {@inheritDoc}
*/
@Override
public String getHelp() {
return this.help;
}
@Override
public String toString() {
return value.toString();
}
/**
* Gets the method that will be executed.
*
* @return The name of the method in MVWorld to be called.
*/
@Override
public String getHelp() {
return this.help;
public String getMethod() {
return this.method;
}
/**
* Sets the method that will be executed.
*
* @param methodName The name of the method in MVWorld to be called.
*/
@Override
public void setMethod(String methodName) {
this.method = methodName;
}
/**
* Returns the class of the object we're looking at.
*
* @return the class of the object we're looking at.
*/
@Override
public Class<?> getPropertyClass() {
return Boolean.class;
}
}

View File

@ -10,6 +10,9 @@ package com.onarandombox.MultiverseCore.configuration;
import com.onarandombox.MultiverseCore.enums.EnglishChatColor;
import org.bukkit.configuration.ConfigurationSection;
/**
* A {@link EnglishChatColor} config-property.
*/
public class ColorConfigProperty implements MVConfigProperty<EnglishChatColor> {
private String name;
private EnglishChatColor value;
@ -30,16 +33,25 @@ public class ColorConfigProperty implements MVConfigProperty<EnglishChatColor> {
this.parseValue(this.section.getString(this.configNode, defaultValue.toString()));
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return this.name;
}
/**
* {@inheritDoc}
*/
@Override
public EnglishChatColor getValue() {
return this.value;
}
/**
* {@inheritDoc}
*/
@Override
public boolean setValue(EnglishChatColor value) {
if (value == null) {
@ -50,6 +62,9 @@ public class ColorConfigProperty implements MVConfigProperty<EnglishChatColor> {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean parseValue(String value) {
EnglishChatColor color = EnglishChatColor.fromString(value);
@ -60,18 +75,24 @@ public class ColorConfigProperty implements MVConfigProperty<EnglishChatColor> {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public String getConfigNode() {
return this.configNode;
}
/**
* {@inheritDoc}
*/
@Override
public String getHelp() {
return this.help;
}
@Override
public String toString() {
return value.toString();
}
@Override
public String getHelp() {
return this.help;
}
}

View File

@ -1,5 +1,5 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2011. *
* Multiverse 2 Copyright (c) the Multiverse Team 2012. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
@ -22,74 +22,271 @@ public class ConfigPropertyFactory {
}
// Booleans
/**
* Constructs a new ConfigProperty.
*
* @param name The name of this ConfigProperty.
* @param defaultValue The default-value.
* @param help The text that's displayed when a user failed to set the property.
* @return The ConfigProperty.
*/
public BooleanConfigProperty getNewProperty(String name, boolean defaultValue, String help) {
return new BooleanConfigProperty(this.section, name, defaultValue, help);
}
/**
* Constructs a new ConfigProperty.
*
* @param name The name of this ConfigProperty.
* @param defaultValue The default-value.
* @param node The name of the configuration-node this ConfigProperty will be stored as.
* @param help The text that's displayed when a user failed to set the property.
* @return The ConfigProperty.
*/
public BooleanConfigProperty getNewProperty(String name, boolean defaultValue, String node, String help) {
return new BooleanConfigProperty(this.section, name, defaultValue, node, help);
}
/**
* Constructs a new ActiveBooleanConfigProperty
*
* This property will execute 'method' after it has been successfully set.
*
* @param name The name of this ConifgProperty
* @param defaultValue The default value.
* @param help What string is shown for help.
* @param node The name of the configuration-node this ConfigProperty will be stored as.
* @param method The method that should be executed.
* @return The ActiveStringConfigProperty
*/
public BooleanConfigProperty getNewProperty(String name, boolean defaultValue, String help, String node, String method) {
return new BooleanConfigProperty(this.section, name, defaultValue, help, node, method);
}
// Integers
/**
* Constructs a new ConfigProperty.
*
* @param name The name of this ConfigProperty.
* @param defaultValue The default-value.
* @param help The text that's displayed when a user failed to set the property.
* @return The ConfigProperty.
*/
public IntegerConfigProperty getNewProperty(String name, int defaultValue, String help) {
return new IntegerConfigProperty(this.section, name, defaultValue, help);
}
/**
* Constructs a new ConfigProperty.
*
* @param name The name of this ConfigProperty.
* @param defaultValue The default-value.
* @param node The name of the configuration-node this ConfigProperty will be stored as.
* @param help The text that's displayed when a user failed to set the property.
* @return The ConfigProperty.
*/
public IntegerConfigProperty getNewProperty(String name, int defaultValue, String node, String help) {
return new IntegerConfigProperty(this.section, name, defaultValue, node, help);
}
// Doubles
/**
* Constructs a new ConfigProperty.
*
* @param name The name of this ConfigProperty.
* @param defaultValue The default-value.
* @param help The text that's displayed when a user failed to set the property.
* @return The ConfigProperty.
*/
public DoubleConfigProperty getNewProperty(String name, double defaultValue, String help) {
return new DoubleConfigProperty(this.section, name, defaultValue, help);
}
/**
* Constructs a new ConfigProperty.
*
* @param name The name of this ConfigProperty.
* @param defaultValue The default-value.
* @param node The name of the configuration-node this ConfigProperty will be stored as.
* @param help The text that's displayed when a user failed to set the property.
* @return The ConfigProperty.
*/
public DoubleConfigProperty getNewProperty(String name, double defaultValue, String node, String help) {
return new DoubleConfigProperty(this.section, name, defaultValue, node, help);
}
/**
* Constructs a new ConfigProperty.
*
* @param name The name of this ConfigProperty.
* @param defaultValue The default-value.
* @param node The name of the configuration-node this ConfigProperty will be stored as.
* @param help The text that's displayed when a user failed to set the property.
* @param method The name of the method that's used to set this property.
* @return The ConfigProperty.
*/
public DoubleConfigProperty getNewProperty(String name, double defaultValue, String node, String help, String method) {
return new DoubleConfigProperty(this.section, name, defaultValue, node, help, method);
}
// Strings
/**
* Constructs a new ConfigProperty.
*
* @param name The name of this ConfigProperty.
* @param defaultValue The default-value.
* @param help The text that's displayed when a user failed to set the property.
* @return The ConfigProperty.
*/
public StringConfigProperty getNewProperty(String name, String defaultValue, String help) {
return new StringConfigProperty(this.section, name, defaultValue, help);
}
/**
* Constructs a new ConfigProperty.
*
* @param name The name of this ConfigProperty.
* @param defaultValue The default-value.
* @param node The name of the configuration-node this ConfigProperty will be stored as.
* @param help The text that's displayed when a user failed to set the property.
* @return The ConfigProperty.
*/
public StringConfigProperty getNewProperty(String name, String defaultValue, String node, String help) {
return new StringConfigProperty(this.section, name, defaultValue, node, help);
}
// Colors
/**
* Constructs a new ConfigProperty.
*
* @param name The name of this ConfigProperty.
* @param defaultValue The default-value.
* @param help The text that's displayed when a user failed to set the property.
* @return The ConfigProperty.
*/
public ColorConfigProperty getNewProperty(String name, EnglishChatColor defaultValue, String help) {
return new ColorConfigProperty(this.section, name, defaultValue, help);
}
/**
* Constructs a new ConfigProperty.
*
* @param name The name of this ConfigProperty.
* @param defaultValue The default-value.
* @param node The name of the configuration-node this ConfigProperty will be stored as.
* @param help The text that's displayed when a user failed to set the property.
* @return The ConfigProperty.
*/
public ColorConfigProperty getNewProperty(String name, EnglishChatColor defaultValue, String node, String help) {
return new ColorConfigProperty(this.section, name, defaultValue, node, help);
}
// Difficulty
/**
* Constructs a new ConfigProperty.
*
* @param name The name of this ConfigProperty.
* @param defaultValue The default-value.
* @param help The text that's displayed when a user failed to set the property.
* @return The ConfigProperty.
*/
public DifficultyConfigProperty getNewProperty(String name, Difficulty defaultValue, String help) {
return new DifficultyConfigProperty(this.section, name, defaultValue, help);
}
/**
* Constructs a new ConfigProperty.
*
* @param name The name of this ConfigProperty.
* @param defaultValue The default-value.
* @param node The name of the configuration-node this ConfigProperty will be stored as.
* @param help The text that's displayed when a user failed to set the property.
* @return The ConfigProperty.
*/
public DifficultyConfigProperty getNewProperty(String name, Difficulty defaultValue, String node, String help) {
return new DifficultyConfigProperty(this.section, name, defaultValue, node, help);
}
// GameMode
/**
* Constructs a new ConfigProperty.
*
* @param name The name of this ConfigProperty.
* @param defaultValue The default-value.
* @param help The text that's displayed when a user failed to set the property.
* @return The ConfigProperty.
*/
public GameModeConfigProperty getNewProperty(String name, GameMode defaultValue, String help) {
return new GameModeConfigProperty(this.section, name, defaultValue, help);
}
/**
* Constructs a new ConfigProperty.
*
* @param name The name of this ConfigProperty.
* @param defaultValue The default-value.
* @param node The name of the configuration-node this ConfigProperty will be stored as.
* @param help The text that's displayed when a user failed to set the property.
* @return The ConfigProperty.
*/
public GameModeConfigProperty getNewProperty(String name, GameMode defaultValue, String node, String help) {
return new GameModeConfigProperty(this.section, name, defaultValue, node, help);
}
// GameMode
/**
* Constructs a new ConfigProperty.
*
* @param name The name of this ConfigProperty.
* @param defaultValue The default-value.
* @param help The text that's displayed when a user failed to set the property.
* @return The ConfigProperty.
*/
public LocationConfigProperty getNewProperty(String name, Location defaultValue, String help) {
return new LocationConfigProperty(this.section, name, defaultValue, help);
}
/**
* Constructs a new ConfigProperty.
*
* @param name The name of this ConfigProperty.
* @param defaultValue The default-value.
* @param node The name of the configuration-node this ConfigProperty will be stored as.
* @param help The text that's displayed when a user failed to set the property.
* @return The ConfigProperty.
*/
public LocationConfigProperty getNewProperty(String name, Location defaultValue, String node, String help) {
return new LocationConfigProperty(this.section, name, defaultValue, node, help);
}
/**
* Constructs a new ConfigProperty.
*
* @param name The name of this ConfigProperty.
* @param defaultValue The default-value.
* @param node The name of the configuration-node this ConfigProperty will be stored as.
* @param help The text that's displayed when a user failed to set the property.
* @param method The name of the method that's used to set this property.
* @return The ConfigProperty.
*/
public LocationConfigProperty getNewProperty(String name, Location defaultValue, String node, String help, String method) {
return new LocationConfigProperty(this.section, name, defaultValue, node, help, method);
}
/**
* Constructs a new ActiveStringConfigProperty
*
* This property will execute 'method' after it has been successfully set.
* This string will NOT be saved to the config file.
*
* @param name The name of this ConifgProperty
* @param defaultValue The default value.
* @param help What string is shown for help.
* @param method The method that should be executed.
* @param saveToConfig Should the variable save to the config?
* @return The ActiveStringConfigProperty
*/
public ActiveStringConfigProperty getNewProperty(String name, String defaultValue, String help, String method, boolean saveToConfig) {
return new ActiveStringConfigProperty(name, defaultValue, help, method);
}
}

View File

@ -10,7 +10,10 @@ package com.onarandombox.MultiverseCore.configuration;
import org.bukkit.Difficulty;
import org.bukkit.configuration.ConfigurationSection;
public class DifficultyConfigProperty implements MVConfigProperty<Difficulty> {
/**
* A {@link Difficulty} config-property.
*/
public class DifficultyConfigProperty implements MVActiveConfigProperty<Difficulty> {
private String name;
private Difficulty value;
private String configNode;
@ -30,16 +33,25 @@ public class DifficultyConfigProperty implements MVConfigProperty<Difficulty> {
this.parseValue(this.section.getString(this.configNode, defaultValue.toString()));
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return this.name;
}
/**
* {@inheritDoc}
*/
@Override
public Difficulty getValue() {
return this.value;
}
/**
* {@inheritDoc}
*/
@Override
public boolean setValue(Difficulty value) {
if (value == null) {
@ -50,6 +62,9 @@ public class DifficultyConfigProperty implements MVConfigProperty<Difficulty> {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean parseValue(String value) {
try {
@ -63,18 +78,52 @@ public class DifficultyConfigProperty implements MVConfigProperty<Difficulty> {
}
}
/**
* {@inheritDoc}
*/
@Override
public String getConfigNode() {
return this.configNode;
}
/**
* {@inheritDoc}
*/
@Override
public String getHelp() {
return this.help;
}
@Override
public String toString() {
return value.toString();
}
/**
* Gets the method that will be executed.
*
* @return The name of the method in MVWorld to be called.
*/
@Override
public String getHelp() {
return this.help;
public String getMethod() {
return "setDifficulty";
}
/**
* Sets the method that will be executed.
*
* @param methodName The name of the method in MVWorld to be called.
*/
@Override
public void setMethod(String methodName) {
// Unused here. This will only ever be setDifficulty.
}
/**
* {@inheritDoc}
*/
@Override
public Class<?> getPropertyClass() {
return Difficulty.class;
}
}

View File

@ -9,12 +9,16 @@ package com.onarandombox.MultiverseCore.configuration;
import org.bukkit.configuration.ConfigurationSection;
public class DoubleConfigProperty implements MVConfigProperty<Double> {
/**
* A {@link Double} config-property.
*/
public class DoubleConfigProperty implements MVActiveConfigProperty<Double> {
private String name;
private Double value;
private String configNode;
private ConfigurationSection section;
private String help;
private String method;
public DoubleConfigProperty(ConfigurationSection section, String name, Double defaultValue, String help) {
this(section, name, defaultValue, name, help);
@ -29,16 +33,30 @@ public class DoubleConfigProperty implements MVConfigProperty<Double> {
this.setValue(this.section.getDouble(this.configNode, defaultValue));
}
public DoubleConfigProperty(ConfigurationSection section, String name, Double defaultValue, String configNode, String help, String method) {
this(section, name, defaultValue, configNode, help);
this.method = method;
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return this.name;
}
/**
* {@inheritDoc}
*/
@Override
public Double getValue() {
return this.value;
}
/**
* {@inheritDoc}
*/
@Override
public boolean setValue(Double value) {
if (value == null) {
@ -49,6 +67,9 @@ public class DoubleConfigProperty implements MVConfigProperty<Double> {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean parseValue(String value) {
try {
@ -59,18 +80,54 @@ public class DoubleConfigProperty implements MVConfigProperty<Double> {
}
}
/**
* {@inheritDoc}
*/
@Override
public String getConfigNode() {
return this.configNode;
}
/**
* {@inheritDoc}
*/
@Override
public String getHelp() {
return this.help;
}
@Override
public String toString() {
return value.toString();
}
/**
* Gets the method that will be executed.
*
* @return The name of the method in MVWorld to be called.
*/
@Override
public String getHelp() {
return this.help;
public String getMethod() {
return this.method;
}
/**
* Sets the method that will be executed.
*
* @param methodName The name of the method in MVWorld to be called.
*/
@Override
public void setMethod(String methodName) {
this.method = methodName;
}
/**
* Returns the class of the object we're looking at.
*
* @return the class of the object we're looking at.
*/
@Override
public Class<?> getPropertyClass() {
return Double.class;
}
}

View File

@ -10,7 +10,10 @@ package com.onarandombox.MultiverseCore.configuration;
import org.bukkit.GameMode;
import org.bukkit.configuration.ConfigurationSection;
public class GameModeConfigProperty implements MVConfigProperty<GameMode> {
/**
* A {@link GameMode} config-property.
*/
public class GameModeConfigProperty implements MVActiveConfigProperty<GameMode> {
private String name;
private GameMode value;
private String configNode;
@ -30,16 +33,25 @@ public class GameModeConfigProperty implements MVConfigProperty<GameMode> {
this.parseValue(this.section.getString(this.configNode, defaultValue.toString()));
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return this.name;
}
/**
* {@inheritDoc}
*/
@Override
public GameMode getValue() {
return this.value;
}
/**
* {@inheritDoc}
*/
@Override
public boolean setValue(GameMode value) {
if (value == null) {
@ -50,6 +62,9 @@ public class GameModeConfigProperty implements MVConfigProperty<GameMode> {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean parseValue(String value) {
try {
@ -63,18 +78,52 @@ public class GameModeConfigProperty implements MVConfigProperty<GameMode> {
}
}
/**
* {@inheritDoc}
*/
@Override
public String getConfigNode() {
return this.configNode;
}
/**
* {@inheritDoc}
*/
@Override
public String getHelp() {
return this.help;
}
@Override
public String toString() {
return value.toString();
}
/**
* Gets the method that will be executed.
*
* @return The name of the method in MVWorld to be called.
*/
@Override
public String getHelp() {
return this.help;
public String getMethod() {
return "setActualGameMode";
}
/**
* Sets the method that will be executed.
*
* @param methodName The name of the method in MVWorld to be called.
*/
@Override
public void setMethod(String methodName) {
// Not required. Gamemode will only ever be one.
}
/**
* {@inheritDoc}
*/
@Override
public Class<?> getPropertyClass() {
return GameMode.class;
}
}

View File

@ -9,6 +9,9 @@ package com.onarandombox.MultiverseCore.configuration;
import org.bukkit.configuration.ConfigurationSection;
/**
* A {@link Integer} config-property.
*/
public class IntegerConfigProperty implements MVConfigProperty<Integer> {
private String name;
private Integer value;
@ -29,16 +32,25 @@ public class IntegerConfigProperty implements MVConfigProperty<Integer> {
this.setValue(this.section.getInt(this.configNode, defaultValue));
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return this.name;
}
/**
* {@inheritDoc}
*/
@Override
public Integer getValue() {
return this.value;
}
/**
* {@inheritDoc}
*/
@Override
public boolean setValue(Integer value) {
if (value == null) {
@ -49,6 +61,9 @@ public class IntegerConfigProperty implements MVConfigProperty<Integer> {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean parseValue(String value) {
try {
@ -59,18 +74,24 @@ public class IntegerConfigProperty implements MVConfigProperty<Integer> {
}
}
/**
* {@inheritDoc}
*/
@Override
public String getConfigNode() {
return this.configNode;
}
/**
* {@inheritDoc}
*/
@Override
public String getHelp() {
return this.help;
}
@Override
public String toString() {
return value.toString();
}
@Override
public String getHelp() {
return this.help;
}
}

View File

@ -11,12 +11,16 @@ import com.onarandombox.MultiverseCore.utils.LocationManipulation;
import org.bukkit.Location;
import org.bukkit.configuration.ConfigurationSection;
public class LocationConfigProperty implements MVConfigProperty<Location> {
/**
* A {@link Location} config-property.
*/
public class LocationConfigProperty implements MVActiveConfigProperty<Location> {
private String name;
private Location value;
private String configNode;
private ConfigurationSection section;
private String help;
private String method;
public LocationConfigProperty(ConfigurationSection section, String name, Location defaultValue, String help) {
this(section, name, defaultValue, name, help);
@ -31,37 +35,55 @@ public class LocationConfigProperty implements MVConfigProperty<Location> {
this.setValue(this.getLocationFromConfig(defaultValue));
}
public LocationConfigProperty(ConfigurationSection section, String name, Location defaultValue, String configNode, String help, String method) {
this(section, name, defaultValue, configNode, help);
this.method = method;
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return this.name;
}
/**
* {@inheritDoc}
*/
@Override
public Location getValue() {
return this.value;
}
/**
* {@inheritDoc}
*/
@Override
public boolean parseValue(String value) {
Location parsed = LocationManipulation.stringToLocation(value);
return this.setValue(parsed);
}
/**
* {@inheritDoc}
*/
@Override
public String getConfigNode() {
return this.configNode;
}
@Override
public String toString() {
return LocationManipulation.strCoordsRaw(this.value);
}
/**
* {@inheritDoc}
*/
@Override
public String getHelp() {
return this.help;
}
/**
* {@inheritDoc}
*/
@Override
public boolean setValue(Location value) {
if (value == null) {
@ -91,4 +113,39 @@ public class LocationConfigProperty implements MVConfigProperty<Location> {
}
return defaultValue;
}
@Override
public String toString() {
return LocationManipulation.strCoordsRaw(this.value);
}
/**
* Gets the method that will be executed.
*
* @return The name of the method in MVWorld to be called.
*/
@Override
public String getMethod() {
return this.method;
}
/**
* Sets the method that will be executed.
*
* @param methodName The name of the method in MVWorld to be called.
*/
@Override
public void setMethod(String methodName) {
this.method = methodName;
}
/**
* Returns the class of the object we're looking at.
*
* @return the class of the object we're looking at.
*/
@Override
public Class<?> getPropertyClass() {
return Location.class;
}
}

View File

@ -0,0 +1,35 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2012. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.configuration;
/**
* An "active" {@link MVConfigProperty} that uses the specified method to be "actually" set.
* @param <T> The type of the config-property.
* @see MVConfigProperty
*/
public interface MVActiveConfigProperty<T> extends MVConfigProperty<T> {
/**
* Gets the method that will be executed.
*
* @return The name of the method in MVWorld to be called.
*/
String getMethod();
/**
* Sets the method that will be executed.
*
* @param methodName The name of the method in MVWorld to be called.
*/
void setMethod(String methodName);
/**
* Returns the class of the object we're looking at.
* @return the class of the object we're looking at.
*/
Class<?> getPropertyClass();
}

View File

@ -17,8 +17,17 @@ import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
@SuppressWarnings("deprecation")
/*
* This is a mess, so I'm just going to suppress all warnings here.
* BEGIN CHECKSTYLE-SUPPRESSION: ALL
*/
/**
* @deprecated This isn't used any more, is it?
*/
@Deprecated
public abstract class MVConfigMigrator {
public List<String> createdDefaults = new ArrayList<String>();
public abstract boolean migrate(String name, File folder);
@ -60,3 +69,7 @@ public abstract class MVConfigMigrator {
return oldFolder;
}
}
/*
* END CHECKSTYLE-SUPPRESSION: ALL
*/

View File

@ -7,6 +7,11 @@
package com.onarandombox.MultiverseCore.configuration;
/**
* A generic config-property.
*
* @param <T> The type of the config-property.
*/
public interface MVConfigProperty<T> {
/**
* Gets the name of this property.
@ -40,6 +45,7 @@ public interface MVConfigProperty<T> {
* Sets the value of this property.
*
* @param value The T representation of this value.
* @return True the value was successfully set.
*/
boolean setValue(T value);
@ -52,5 +58,10 @@ public interface MVConfigProperty<T> {
*/
boolean parseValue(String value);
/**
* Gets the name of the config-node that this {@link MVConfigProperty} is saved as.
*
* @return The name of the config-node that this {@link MVConfigProperty} is saved as.
*/
String getConfigNode();
}

View File

@ -9,6 +9,9 @@ package com.onarandombox.MultiverseCore.configuration;
import org.bukkit.configuration.ConfigurationSection;
/**
* A {@link String} config-property.
*/
public class StringConfigProperty implements MVConfigProperty<String> {
private String name;
private String value;
@ -29,16 +32,25 @@ public class StringConfigProperty implements MVConfigProperty<String> {
this.parseValue(this.section.getString(this.configNode, defaultValue));
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return this.name;
}
/**
* {@inheritDoc}
*/
@Override
public String getValue() {
return this.value;
}
/**
* {@inheritDoc}
*/
@Override
public boolean parseValue(String value) {
if (value == null) {
@ -48,21 +60,25 @@ public class StringConfigProperty implements MVConfigProperty<String> {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public String getConfigNode() {
return this.configNode;
}
@Override
public String toString() {
return value;
}
/**
* {@inheritDoc}
*/
@Override
public String getHelp() {
return this.help;
}
/**
* {@inheritDoc}
*/
@Override
public boolean setValue(String value) {
if (value == null) {
@ -72,4 +88,9 @@ public class StringConfigProperty implements MVConfigProperty<String> {
this.section.set(configNode, this.value);
return true;
}
@Override
public String toString() {
return value;
}
}

View File

@ -0,0 +1,4 @@
/**
* This package contains the Multiverse-configuration.
*/
package com.onarandombox.MultiverseCore.configuration;

View File

@ -17,21 +17,34 @@ import org.bukkit.util.Vector;
import java.util.Arrays;
import java.util.List;
/**
* An anchor-{@link MVDestination}.
*/
public class AnchorDestination implements MVDestination {
private boolean isValid;
private Location location;
private MultiverseCore plugin;
private String name;
/**
* {@inheritDoc}
*/
@Override
public String getIdentifier() {
return "a";
}
/**
* {@inheritDoc}
*/
@Override
public Vector getVelocity() {
return new Vector(0, 0, 0);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isThisType(JavaPlugin plugin, String destination) {
if (!(plugin instanceof MultiverseCore)) {
@ -47,16 +60,25 @@ public class AnchorDestination implements MVDestination {
return parsed.get(0).equalsIgnoreCase("a");
}
/**
* {@inheritDoc}
*/
@Override
public Location getLocation(Entity e) {
return this.location;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isValid() {
return this.isValid;
}
/**
* {@inheritDoc}
*/
@Override
public void setDestination(JavaPlugin plugin, String destination) {
if (!(plugin instanceof MultiverseCore)) {
@ -73,7 +95,7 @@ public class AnchorDestination implements MVDestination {
}
this.name = parsed.get(1);
this.location = this.plugin.getAnchorManager().getAnchorLocation(parsed.get(1));
if(this.location == null) {
if (this.location == null) {
this.isValid = false;
return;
}
@ -83,11 +105,17 @@ public class AnchorDestination implements MVDestination {
this.isValid = true;
}
/**
* {@inheritDoc}
*/
@Override
public String getType() {
return "Anchor";
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return "Anchor: " + this.name;
@ -101,11 +129,17 @@ public class AnchorDestination implements MVDestination {
return "i:Invalid Destination";
}
/**
* {@inheritDoc}
*/
@Override
public String getRequiredPermission() {
return "multiverse.access." + this.location.getWorld().getName();
}
/**
* {@inheritDoc}
*/
@Override
public boolean useSafeTeleporter() {
// This is an ANCHOR destination, don't safely teleport here.

View File

@ -14,16 +14,25 @@ import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.Vector;
/**
* A bed-{@link MVDestination}.
*/
public class BedDestination implements MVDestination {
private boolean isValid;
private Location knownBedLoc;
/**
* {@inheritDoc}
*/
@Override
public String getIdentifier() {
return "b";
}
/**
* {@inheritDoc}
*/
@Override
public boolean isThisType(JavaPlugin plugin, String destination) {
String[] split = destination.split(":");
@ -31,6 +40,9 @@ public class BedDestination implements MVDestination {
return this.isValid;
}
/**
* {@inheritDoc}
*/
@Override
public Location getLocation(Entity entity) {
if (entity instanceof Player) {
@ -40,31 +52,49 @@ public class BedDestination implements MVDestination {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public Vector getVelocity() {
return new Vector();
}
/**
* {@inheritDoc}
*/
@Override
public void setDestination(JavaPlugin plugin, String destination) {
// Not needed.
}
/**
* {@inheritDoc}
*/
@Override
public boolean isValid() {
return this.isValid;
}
/**
* {@inheritDoc}
*/
@Override
public String getType() {
return "Bed";
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return "Bed";
}
/**
* {@inheritDoc}
*/
@Override
public String getRequiredPermission() {
if (knownBedLoc != null) {
@ -73,6 +103,9 @@ public class BedDestination implements MVDestination {
return "";
}
/**
* {@inheritDoc}
*/
@Override
public boolean useSafeTeleporter() {
// Bukkit should have already checked this.

View File

@ -17,12 +17,19 @@ import org.bukkit.util.Vector;
import java.util.Arrays;
import java.util.List;
/**
* A cannon-{@link MVDestination}.
*/
public class CannonDestination implements MVDestination {
private final String coordRegex = "(-?[\\d]+\\.?[\\d]*),(-?[\\d]+\\.?[\\d]*),(-?[\\d]+\\.?[\\d]*)";
private boolean isValid;
private Location location;
private double speed;
/**
* {@inheritDoc}
*/
@Override
public Vector getVelocity() {
double pitchRadians = Math.toRadians(location.getPitch());
double yawRadians = Math.toRadians(location.getYaw());
@ -35,20 +42,28 @@ public class CannonDestination implements MVDestination {
return new Vector(x, y, z);
}
/**
* {@inheritDoc}
*/
@Override
public String getIdentifier() {
return "ca";
}
// NEED ca:world:x,y,z:pitch:yaw:speed
// so basically 6
private static final int SPLIT_SIZE = 6;
/**
* {@inheritDoc}
*/
@Override
public boolean isThisType(JavaPlugin plugin, String destination) {
if (!(plugin instanceof MultiverseCore)) {
return false;
}
List<String> parsed = Arrays.asList(destination.split(":"));
// NEED ca:world:x,y,z:pitch:yaw:speed
// so basically 6
if (parsed.size() != 6) {
if (parsed.size() != SPLIT_SIZE) {
return false;
}
// If it's not an Cannon type
@ -66,35 +81,44 @@ public class CannonDestination implements MVDestination {
}
try {
// BEGIN CHECKSTYLE-SUPPRESSION: MagicNumberCheck
Float.parseFloat(parsed.get(3));
Float.parseFloat(parsed.get(4));
Float.parseFloat(parsed.get(5));
// END CHECKSTYLE-SUPPRESSION: MagicNumberCheck
} catch (NumberFormatException e) {
return false;
}
return true;
}
/**
* {@inheritDoc}
*/
@Override
public Location getLocation(Entity e) {
return this.location;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isValid() {
return this.isValid;
}
/**
* {@inheritDoc}
*/
@Override
public void setDestination(JavaPlugin plugin, String destination) {
if (!(plugin instanceof MultiverseCore)) {
return;
}
List<String> parsed = Arrays.asList(destination.split(":"));
// Need at least: e:world:x,y,z
// OR e:world:x,y,z:pitch:yaw
// so basically 3 or 5
if (parsed.size() != 6) {
if (parsed.size() != SPLIT_SIZE) {
this.isValid = false;
return;
}
@ -129,9 +153,11 @@ public class CannonDestination implements MVDestination {
this.location.setZ(coords[2]);
try {
// BEGIN CHECKSTYLE-SUPPRESSION: MagicNumberCheck
this.location.setPitch(Float.parseFloat(parsed.get(3)));
this.location.setYaw(Float.parseFloat(parsed.get(4)));
this.speed = Math.abs(Float.parseFloat(parsed.get(5)));
// END CHECKSTYLE-SUPPRESSION: MagicNumberCheck
} catch (NumberFormatException e) {
this.isValid = false;
return;
@ -141,18 +167,30 @@ public class CannonDestination implements MVDestination {
}
/**
* {@inheritDoc}
*/
@Override
public String getType() {
return "Cannon!";
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return "Cannon (" + this.location.getX() + ", " + this.location.getY() + ", " + this.location.getZ() + ":" +
this.location.getPitch() + ":" + this.location.getYaw() + ":" + this.speed + ")";
return "Cannon (" + this.location.getX() + ", " + this.location.getY() + ", " + this.location.getZ() + ":"
+ this.location.getPitch() + ":" + this.location.getYaw() + ":" + this.speed + ")";
}
/**
* Sets this {@link CannonDestination}.
*
* @param location The {@link Location}.
* @param speed The speed.
*/
public void setDestination(Location location, double speed) {
if (location != null) {
this.location = location;
@ -162,21 +200,28 @@ public class CannonDestination implements MVDestination {
this.isValid = false;
}
@Override
public String toString() {
if (isValid) {
return "ca:" + location.getWorld().getName() + ":" + location.getX() + "," + location.getY() + "," + location.getZ() + ":" + location.getPitch() + ":" + location.getYaw() + ":" + this.speed;
}
return "i:Invalid Destination";
}
/**
* {@inheritDoc}
*/
@Override
public String getRequiredPermission() {
return "multiverse.access." + this.location.getWorld().getName();
}
/**
* {@inheritDoc}
*/
@Override
public boolean useSafeTeleporter() {
return false;
}
@Override
public String toString() {
if (isValid) {
return "ca:" + location.getWorld().getName() + ":" + location.getX() + "," + location.getY()
+ "," + location.getZ() + ":" + location.getPitch() + ":" + location.getYaw() + ":" + this.speed;
}
return "i:Invalid Destination";
}
}

View File

@ -66,6 +66,13 @@ public class DestinationFactory {
return new InvalidDestination();
}
/**
* Registers a {@link MVDestination}.
*
* @param c The {@link Class} of the {@link MVDestination} to register.
* @param identifier The {@link String}-identifier.
* @return True if the class was successfully registered.
*/
public boolean registerDestinationType(Class<? extends MVDestination> c, String identifier) {
if (this.destList.containsKey(identifier)) {
return false;
@ -79,12 +86,14 @@ public class DestinationFactory {
Permission other = this.plugin.getServer().getPluginManager().getPermission("multiverse.teleport.other." + identifier);
PermissionTools pt = new PermissionTools(this.plugin);
if (self == null) {
self = new Permission("multiverse.teleport.self." + identifier, "Permission to teleport yourself for the " + identifier + " destination.", PermissionDefault.OP);
self = new Permission("multiverse.teleport.self." + identifier,
"Permission to teleport yourself for the " + identifier + " destination.", PermissionDefault.OP);
this.plugin.getServer().getPluginManager().addPermission(self);
pt.addToParentPerms("multiverse.teleport.self." + identifier);
}
if (other == null) {
other = new Permission("multiverse.teleport.other." + identifier, "Permission to teleport others for the " + identifier + " destination.", PermissionDefault.OP);
other = new Permission("multiverse.teleport.other." + identifier,
"Permission to teleport others for the " + identifier + " destination.", PermissionDefault.OP);
this.plugin.getServer().getPluginManager().addPermission(other);
pt.addToParentPerms("multiverse.teleport.other." + identifier);
}

View File

@ -17,20 +17,33 @@ import org.bukkit.util.Vector;
import java.util.Arrays;
import java.util.List;
/**
* An exact {@link MVDestination}.
*/
public class ExactDestination implements MVDestination {
private final String coordRegex = "(-?[\\d]+\\.?[\\d]*),(-?[\\d]+\\.?[\\d]*),(-?[\\d]+\\.?[\\d]*)";
private boolean isValid;
private Location location;
/**
* {@inheritDoc}
*/
@Override
public String getIdentifier() {
return "e";
}
/**
* {@inheritDoc}
*/
@Override
public Vector getVelocity() {
return new Vector(0, 0, 0);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isThisType(JavaPlugin plugin, String destination) {
if (!(plugin instanceof MultiverseCore)) {
@ -40,7 +53,7 @@ public class ExactDestination implements MVDestination {
// Need at least: e:world:x,y,z
// OR e:world:x,y,z:pitch:yaw
// so basically 3 or 5
if (!(parsed.size() == 3 || parsed.size() == 5)) {
if (!(parsed.size() == 3 || parsed.size() == 5)) { // SUPPRESS CHECKSTYLE: MagicNumberCheck
return false;
}
// If it's not an Exact type
@ -63,23 +76,32 @@ public class ExactDestination implements MVDestination {
try {
Float.parseFloat(parsed.get(3));
Float.parseFloat(parsed.get(4));
Float.parseFloat(parsed.get(4)); // SUPPRESS CHECKSTYLE: MagicNumberCheck
} catch (NumberFormatException e) {
return false;
}
return true;
}
/**
* {@inheritDoc}
*/
@Override
public Location getLocation(Entity e) {
return this.location;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isValid() {
return this.isValid;
}
/**
* {@inheritDoc}
*/
@Override
public void setDestination(JavaPlugin plugin, String destination) {
if (!(plugin instanceof MultiverseCore)) {
@ -89,7 +111,7 @@ public class ExactDestination implements MVDestination {
// Need at least: e:world:x,y,z
// OR e:world:x,y,z:pitch:yaw
// so basically 3 or 5
if (!(parsed.size() == 3 || parsed.size() == 5)) {
if (!(parsed.size() == 3 || parsed.size() == 5)) { // SUPPRESS CHECKSTYLE: MagicNumberCheck
this.isValid = false;
return;
}
@ -130,7 +152,7 @@ public class ExactDestination implements MVDestination {
try {
this.location.setPitch(Float.parseFloat(parsed.get(3)));
this.location.setYaw(Float.parseFloat(parsed.get(4)));
this.location.setYaw(Float.parseFloat(parsed.get(4))); // SUPPRESS CHECKSTYLE: MagicNumberCheck
} catch (NumberFormatException e) {
this.isValid = false;
return;
@ -139,16 +161,28 @@ public class ExactDestination implements MVDestination {
}
/**
* {@inheritDoc}
*/
@Override
public String getType() {
return "Exact";
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return "Exact (" + this.location.getX() + ", " + this.location.getY() + ", " + this.location.getZ() + ":" + location.getPitch() + ":" + location.getYaw() + ")";
return "Exact (" + this.location.getX() + ", " + this.location.getY() + ", " + this.location.getZ()
+ ":" + location.getPitch() + ":" + location.getYaw() + ")";
}
/**
* Sets this {@link ExactDestination}.
*
* @param location The {@link Location}.
*/
public void setDestination(Location location) {
if (location != null) {
this.location = location;
@ -157,19 +191,29 @@ public class ExactDestination implements MVDestination {
this.isValid = false;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
if (isValid) {
return "e:" + location.getWorld().getName() + ":" + location.getX() + "," + location.getY() + "," + location.getZ() + ":" + location.getPitch() + ":" + location.getYaw();
return "e:" + location.getWorld().getName() + ":" + location.getX() + "," + location.getY()
+ "," + location.getZ() + ":" + location.getPitch() + ":" + location.getYaw();
}
return "i:Invalid Destination";
}
/**
* {@inheritDoc}
*/
@Override
public String getRequiredPermission() {
return "multiverse.access." + this.location.getWorld().getName();
}
/**
* {@inheritDoc}
*/
@Override
public boolean useSafeTeleporter() {
// This is an EXACT destination, don't safely teleport here.

View File

@ -14,38 +14,62 @@ import org.bukkit.entity.Entity;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.Vector;
/**
* An invalid {@link MVDestination}.
*/
public class InvalidDestination implements MVDestination {
/**
* {@inheritDoc}
*/
@Override
public String getIdentifier() {
return "i";
}
/**
* {@inheritDoc}
*/
@Override
public boolean isThisType(JavaPlugin plugin, String destination) {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public Location getLocation(Entity e) {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isValid() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public void setDestination(JavaPlugin plugin, String destination) {
// Nothing needed, it's invalid.
}
/**
* {@inheritDoc}
*/
@Override
public String getType() {
return ChatColor.RED + "Invalid Destination";
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return ChatColor.RED + "Invalid Destination";
@ -56,15 +80,25 @@ public class InvalidDestination implements MVDestination {
return "i:Invalid Destination";
}
/**
* {@inheritDoc}
*/
@Override
public String getRequiredPermission() {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public Vector getVelocity() {
return new Vector(0, 0, 0);
}
/**
* {@inheritDoc}
*/
@Override
public boolean useSafeTeleporter() {
return false;

View File

@ -14,16 +14,25 @@ import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.Vector;
/**
* A player-{@link MVDestination}.
*/
public class PlayerDestination implements MVDestination {
private String player;
private boolean isValid;
private JavaPlugin plugin;
/**
* {@inheritDoc}
*/
@Override
public String getIdentifier() {
return "pl";
}
/**
* {@inheritDoc}
*/
@Override
public boolean isThisType(JavaPlugin plugin, String destination) {
String[] items = destination.split(":");
@ -36,6 +45,9 @@ public class PlayerDestination implements MVDestination {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public Location getLocation(Entity e) {
Player p = plugin.getServer().getPlayer(this.player);
@ -52,11 +64,17 @@ public class PlayerDestination implements MVDestination {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isValid() {
return this.isValid;
}
/**
* {@inheritDoc}
*/
@Override
public void setDestination(JavaPlugin plugin, String destination) {
String[] items = destination.split(":");
@ -71,11 +89,17 @@ public class PlayerDestination implements MVDestination {
this.plugin = plugin;
}
/**
* {@inheritDoc}
*/
@Override
public String getType() {
return "Player";
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return this.player;
@ -86,15 +110,25 @@ public class PlayerDestination implements MVDestination {
return "pl:" + this.player;
}
/**
* {@inheritDoc}
*/
@Override
public String getRequiredPermission() {
return "";
}
/**
* {@inheritDoc}
*/
@Override
public Vector getVelocity() {
return new Vector(0, 0, 0);
}
/**
* {@inheritDoc}
*/
@Override
public boolean useSafeTeleporter() {
return true;

View File

@ -16,17 +16,26 @@ import org.bukkit.entity.Entity;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.Vector;
/**
* A world-{@link MVDestination}.
*/
public class WorldDestination implements MVDestination {
private boolean isValid;
private MultiverseWorld world;
private float yaw = -1;
private String direction = "";
/**
* {@inheritDoc}
*/
@Override
public String getIdentifier() {
return "w";
}
/**
* {@inheritDoc}
*/
@Override
public boolean isThisType(JavaPlugin plugin, String destination) {
String[] items = destination.split(":");
@ -48,6 +57,9 @@ public class WorldDestination implements MVDestination {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public Location getLocation(Entity e) {
Location spawnLoc = getAcurateSpawnLocation(e, this.world);
@ -62,15 +74,23 @@ public class WorldDestination implements MVDestination {
if (world != null) {
return world.getSpawnLocation();
} else {
// add 0.5 to x and z to center people
// (spawn location is stored as int meaning that you would spawn in the corner of a block)
return e.getWorld().getSpawnLocation().add(.5, 0, .5);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean isValid() {
return this.isValid;
}
/**
* {@inheritDoc}
*/
@Override
public void setDestination(JavaPlugin plugin, String destination) {
String[] items = destination.split(":");
@ -97,11 +117,17 @@ public class WorldDestination implements MVDestination {
}
}
/**
* {@inheritDoc}
*/
@Override
public String getType() {
return "World";
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return this.world.getColoredWorldString();
@ -115,6 +141,9 @@ public class WorldDestination implements MVDestination {
return this.world.getCBWorld().getName();
}
/**
* {@inheritDoc}
*/
@Override
public String getRequiredPermission() {
// TODO: Potenitally replace spaces wiht tabs for friendlier yaml.
@ -122,10 +151,17 @@ public class WorldDestination implements MVDestination {
return "multiverse.access." + this.world.getName();
}
/**
* {@inheritDoc}
*/
@Override
public Vector getVelocity() {
return new Vector(0, 0, 0);
}
/**
* {@inheritDoc}
*/
@Override
public boolean useSafeTeleporter() {
return true;

View File

@ -0,0 +1,4 @@
/**
* This package contains all destination-types.
*/
package com.onarandombox.MultiverseCore.destination;

View File

@ -7,6 +7,24 @@
package com.onarandombox.MultiverseCore.enums;
/**
* A enum containing all actions that can be used to modify world-properties.
*/
public enum Action {
Set, Add, Remove, Clear
/**
* Setting a property.
*/
Set,
/**
* Adding something to a list-property.
*/
Add,
/**
* Removing something from a list-property.
*/
Remove,
/**
* Clearing a list-property.
*/
Clear
}

View File

@ -7,6 +7,20 @@
package com.onarandombox.MultiverseCore.enums;
/**
* An enum containing all list-properties.
*/
public enum AddProperties {
worldblacklist, animals, monsters
/**
* Worlds that people cannot go to from a world.
*/
worldblacklist,
/**
* Animal-exceptions.
*/
animals,
/**
* Monster-exceptions.
*/
monsters
}

View File

@ -7,9 +7,52 @@
package com.onarandombox.MultiverseCore.enums;
/**
* An enum containing all config-properties that can be set.
*/
public enum ConfigProperty {
messagecooldown, teleportcooldown, worldnameprefix, enforcegamemodes, enforceaccess, displaypermerrors, debug, firstspawnworld, teleportintercept, firstspawnoverride;
/**
* How long to leave in between sending a message to the player. (NOT YET IMPLEMENTED)
*/
messagecooldown,
/**
* How fast are people allowed to use /MVTP (NOT YET IMPLEMENTED).
*/
teleportcooldown,
/**
* Prefix chat-messages with world-names.
*/
worldnameprefix,
/**
* If value is set to false, Multiverse will NOT enforce world access permissions.
*/
enforceaccess,
/**
* Whether users should get detailed information about the permissions they would need.
*/
displaypermerrors,
/**
* Debug-information.
*/
debug,
/**
* The world new users will spawn in.
*/
firstspawnworld,
/**
* Whether Multiverse should intercept teleports.
*/
teleportintercept,
/**
* Whether Multiverse should override the first spawn.
*/
firstspawnoverride;
/**
* Constructs a string containing all values in this enum.
*
* @return That {@link String}.
*/
public static String getAllValues() {
String buffer = "";
for (ConfigProperty c : ConfigProperty.values()) {

View File

@ -9,22 +9,44 @@ package com.onarandombox.MultiverseCore.enums;
import org.bukkit.ChatColor;
/**
* A regular {@link ChatColor} represented by an english string.
*/
public enum EnglishChatColor {
/*
* I know. this is quite ugly.
*/
/** AQUA. */
AQUA("AQUA", ChatColor.AQUA),
/** BLACK. */
BLACK("BLACK", ChatColor.BLACK),
/** BLUE. */
BLUE("BLUE", ChatColor.BLUE),
/** DARKAQUA. */
DARKAQUA("DARKAQUA", ChatColor.DARK_AQUA),
/** DARKBLUE. */
DARKBLUE("DARKBLUE", ChatColor.DARK_BLUE),
/** DARKGRAY. */
DARKGRAY("DARKGRAY", ChatColor.DARK_GRAY),
/** DARKGREEN. */
DARKGREEN("DARKGREEN", ChatColor.DARK_GREEN),
/** DARKPURPLE. */
DARKPURPLE("DARKPURPLE", ChatColor.DARK_PURPLE),
/** DARKRED. */
DARKRED("DARKRED", ChatColor.DARK_RED),
/** GOLD. */
GOLD("GOLD", ChatColor.GOLD),
/** GRAY. */
GRAY("GRAY", ChatColor.GRAY),
/** GREEN. */
GREEN("GREEN", ChatColor.GREEN),
/** LIGHTPURPLE. */
LIGHTPURPLE("LIGHTPURPLE", ChatColor.LIGHT_PURPLE),
/** RED. */
RED("RED", ChatColor.RED),
/** YELLOW. */
YELLOW("YELLOW", ChatColor.YELLOW),
/** WHITE. */
WHITE("WHITE", ChatColor.WHITE);
private ChatColor color;
private String text;
@ -34,14 +56,26 @@ public enum EnglishChatColor {
this.text = name;
}
/**
* Gets the text.
* @return The text.
*/
public String getText() {
return this.text;
}
/**
* Gets the color.
* @return The color as {@link ChatColor}.
*/
public ChatColor getColor() {
return this.color;
}
/**
* Constructs a string containing all available colors.
* @return That {@link String}.
*/
public static String getAllColors() {
String buffer = "";
for (EnglishChatColor c : EnglishChatColor.values()) {
@ -50,6 +84,11 @@ public enum EnglishChatColor {
return buffer;
}
/**
* Constructs an {@link EnglishChatColor} from a {@link String}.
* @param text The {@link String}.
* @return The {@link EnglishChatColor}.
*/
public static EnglishChatColor fromString(String text) {
if (text != null) {
for (EnglishChatColor c : EnglishChatColor.values()) {

View File

@ -7,6 +7,32 @@
package com.onarandombox.MultiverseCore.enums;
/**
* An enum containing possible teleport-results.
*/
public enum TeleportResult {
FAIL_PERMISSION, FAIL_UNSAFE, FAIL_TOO_POOR, FAIL_INVALID, FAIL_OTHER, SUCCESS
/**
* Insufficient permissions.
*/
FAIL_PERMISSION,
/**
* The teleport was unsafe.
*/
FAIL_UNSAFE,
/**
* The player was to poor.
*/
FAIL_TOO_POOR,
/**
* The teleport was invalid.
*/
FAIL_INVALID,
/**
* Unknown reason.
*/
FAIL_OTHER,
/**
* The player was successfully teleported.
*/
SUCCESS
}

View File

@ -0,0 +1,4 @@
/**
* This package contains all enums.
*/
package com.onarandombox.MultiverseCore.enums;

View File

@ -1,30 +0,0 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2011. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.event;
import org.bukkit.event.Event;
import java.util.List;
public class MVConfigMigrateEvent extends Event {
private static final long serialVersionUID = 3647950355746345397L;
private List<String> configsLoaded;
public MVConfigMigrateEvent(List<String> configsLoaded) {
super("MVConfigMigrate");
this.configsLoaded = configsLoaded;
}
public void addConfig(String config) {
this.configsLoaded.add(config);
}
public List<String> getAllConfigsLoaded() {
return this.configsLoaded;
}
}

View File

@ -11,6 +11,9 @@ import org.bukkit.event.Event;
import java.util.List;
/**
* Called when the Multiverse-config should be reloaded.
*/
public class MVConfigReloadEvent extends Event {
private static final long serialVersionUID = 3647950355746345397L;
private List<String> configsLoaded;
@ -20,10 +23,18 @@ public class MVConfigReloadEvent extends Event {
this.configsLoaded = configsLoaded;
}
/**
* Adds a config to this event.
* @param config The config to add.
*/
public void addConfig(String config) {
this.configsLoaded.add(config);
}
/**
* Gets all loaded configs.
* @return A list of all loaded configs.
*/
public List<String> getAllConfigsLoaded() {
return this.configsLoaded;
}

View File

@ -0,0 +1,54 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2011. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.event;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
/**
* This event is thrown when a portal is touched.
*/
public class MVPlayerTouchedPortalEvent extends Event implements Cancellable {
private Player p;
private Location l;
private boolean isCancelled;
public MVPlayerTouchedPortalEvent(Player p, Location l) {
super("MVPlayerTouchedPortalEvent");
this.p = p;
this.l = l;
}
/**
* Gets the {@link Location} of the portal-block that was touched.
* @return The {@link Location} of the portal-block that was touched.
*/
public Location getBlockTouched() {
return this.l;
}
/**
* Gets the {@link Player} that's touching the portal.
* @return The {@link Player} that's touching the portal.
*/
public Player getPlayer() {
return this.p;
}
@Override
public boolean isCancelled() {
return this.isCancelled;
}
@Override
public void setCancelled(boolean b) {
this.isCancelled = b;
}
}

View File

@ -11,6 +11,9 @@ import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
/**
* Called when a player is respawning.
*/
public class MVRespawnEvent extends Event {
private Player player;
private Location location;
@ -24,18 +27,34 @@ public class MVRespawnEvent extends Event {
this.respawnMethod = respawnMethod;
}
/**
* Gets the {@link Player} that's respawning.
* @return The {@link Player} that's respawning.
*/
public Player getPlayer() {
return this.player;
}
/**
* Gets the respawn-method.
* @return The respawn-method.
*/
public String getRespawnMethod() {
return this.respawnMethod;
}
/**
* Gets the player's respawn-{@link Location}.
* @return The player's respawn-{@link Location}.
*/
public Location getPlayersRespawnLocation() {
return this.location;
}
/**
* Sets the player's respawn-{@link Location}.
* @param l The new respawn-{@link Location}.
*/
public void setRespawnLocation(Location l) {
this.location = l;
}

View File

@ -8,6 +8,7 @@
package com.onarandombox.MultiverseCore.event;
import com.onarandombox.MultiverseCore.api.MVDestination;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@ -68,6 +69,14 @@ public class MVTeleportEvent extends Event implements Cancellable {
return this.dest;
}
/**
* Looks if this {@link MVTeleportEvent} is using the {@link SafeTTeleporter}.
* @return True if this {@link MVTeleportEvent} is using the {@link SafeTTeleporter}.
*/
public boolean isUsingSafeTTeleporter() {
return useSafeTeleport;
}
@Override
public boolean isCancelled() {
return this.isCancelled;

View File

@ -0,0 +1,32 @@
package com.onarandombox.MultiverseCore.event;
import org.bukkit.event.Event;
/**
* Called when somebody requests version information about Multiverse.
*/
public class MVVersionEvent extends Event {
private final StringBuilder versionInfoBuilder;
public MVVersionEvent(String versionInfo) {
super("MVVersionEvent");
versionInfoBuilder = new StringBuilder(versionInfo);
}
/**
* Gets the version-info currently saved in this event.
* @return The version-info.
*/
public String getVersionInfo() {
return versionInfoBuilder.toString();
}
/**
* Appends more version-info to the version-info currently saved in this event.
* @param moreVersionInfo The version-info to add. Should end with '\n'.
*/
public void appendVersionInfo(String moreVersionInfo) {
versionInfoBuilder.append(moreVersionInfo);
}
}

View File

@ -9,6 +9,11 @@ package com.onarandombox.MultiverseCore.event;
import org.bukkit.event.Event;
/**
* Called when somebody requests version information about Multiverse.
* @deprecated Use {@link MVVersionEvent} instead.
*/
@Deprecated
public class MVVersionRequestEvent extends Event {
private String pasteBinBuffer;
@ -18,10 +23,22 @@ public class MVVersionRequestEvent extends Event {
this.pasteBinBuffer = pasteBinBuffer;
}
/**
* Gets the pasteBinBuffer.
* @return The pasteBinBuffer.
* @deprecated Use {@link MVVersionEvent} instead.
*/
@Deprecated
public String getPasteBinBuffer() {
return this.pasteBinBuffer;
}
/**
* Sets the pasteBinBuffer.
* @param buffer The new pasteBinBuffer.
* @deprecated Use {@link MVVersionEvent} instead.
*/
@Deprecated
public void setPasteBinBuffer(String buffer) {
this.pasteBinBuffer = buffer;
}

View File

@ -15,7 +15,7 @@ import org.bukkit.event.Event;
/**
* This event is fired *before* the property is actually changed.
* <p>
* If it is cancled, no change will happen.
* If it is cancelled, no change will happen.
* <p>
* If you want to get the values of the world before the change, query the world.
* If you want to get the value being changed, use getProperty()
@ -36,14 +36,26 @@ public class MVWorldPropertyChangeEvent extends Event implements Cancellable {
this.value = value;
}
/**
* Gets the changed world property's name.
* @return The changed world property's name.
*/
public String getPropertyName() {
return this.name;
}
/**
* Gets the new value.
* @return The new value.
*/
public String getNewValue() {
return this.value;
}
/**
* Sets the new value.
* @param value The new new value.
*/
public void setNewValue(String value) {
this.value = value;
}

View File

@ -0,0 +1,4 @@
/**
* This package contains all events.
*/
package com.onarandombox.MultiverseCore.event;

View File

@ -7,6 +7,9 @@
package com.onarandombox.MultiverseCore.exceptions;
/**
* Thrown when a world-property doesn't exist.
*/
public class PropertyDoesNotExistException extends Exception {
public PropertyDoesNotExistException(String name) {
super(name);

View File

@ -0,0 +1,4 @@
/**
* This package contains all exceptions.
*/
package com.onarandombox.MultiverseCore.exceptions;

View File

@ -10,7 +10,6 @@ package com.onarandombox.MultiverseCore.listeners;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.utils.PermissionTools;
import org.bukkit.World;
import org.bukkit.entity.Animals;
import org.bukkit.entity.CreatureType;
@ -29,16 +28,17 @@ import org.bukkit.event.entity.FoodLevelChangeEvent;
import java.util.List;
import java.util.logging.Level;
/**
* Multiverse's {@link EntityListener}.
*/
public class MVEntityListener extends EntityListener {
private MultiverseCore plugin;
private MVWorldManager worldManager;
private PermissionTools pt;
public MVEntityListener(MultiverseCore plugin) {
this.plugin = plugin;
this.worldManager = plugin.getMVWorldManager();
this.pt = new PermissionTools(this.plugin);
}
@Override
@ -73,6 +73,7 @@ public class MVEntityListener extends EntityListener {
/**
* Handle Animal/Monster Spawn settings, seems like a more concrete method than using CraftBukkit.
* @param event The event.
*/
@Override
public void onCreatureSpawn(CreatureSpawnEvent event) {

View File

@ -12,20 +12,26 @@ import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.event.MVRespawnEvent;
import com.onarandombox.MultiverseCore.utils.PermissionTools;
import com.onarandombox.MultiverseCore.utils.SafeTTeleporter;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.player.*;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerListener;
import org.bukkit.event.player.PlayerPortalEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import java.util.logging.Level;
/**
* Multiverse's {@link PlayerListener}.
*/
public class MVPlayerListener extends PlayerListener {
private MultiverseCore plugin;
private SafeTTeleporter mvteleporter;
private MVWorldManager worldManager;
private PermissionTools pt;
@ -107,7 +113,7 @@ public class MVPlayerListener extends PlayerListener {
Player p = event.getPlayer();
if (!p.hasPlayedBefore()) {
this.plugin.log(Level.FINE, "Player joined first!");
if(MultiverseCore.FirstSpawnOverride) {
if (MultiverseCore.FirstSpawnOverride) {
this.plugin.log(Level.FINE, "Moving NEW player to(firstspawnoverride): " + worldManager.getFirstSpawnWorld().getSpawnLocation());
this.spawnNewPlayer(p);
}
@ -116,20 +122,14 @@ public class MVPlayerListener extends PlayerListener {
this.plugin.log(Level.FINE, "Player joined AGAIN!");
}
// Handle the Players GameMode setting for the new world.
if (MultiverseCore.EnforceGameModes) {
this.handleGameMode(event.getPlayer(), event.getPlayer().getWorld());
}
}
@Override
public void onPlayerChangedWorld(PlayerChangedWorldEvent event) {
// Handle the Players GameMode setting for the new world.
if (MultiverseCore.EnforceGameModes) {
// Not yet implemented, but eventually we'll switch to this!
//if (this.plugin.getMVWorldManager().getMVWorld(event.getPlayer().getWorld()).getEnforceGameMode())
// Permissions now determine whether or not to handle a gamemode.
this.handleGameMode(event.getPlayer(), event.getPlayer().getWorld());
}
}
@Override
public void onPlayerQuit(PlayerQuitEvent event) {
@ -154,7 +154,8 @@ public class MVPlayerListener extends PlayerListener {
teleporter = this.plugin.getServer().getPlayer(teleporterName);
}
}
this.plugin.log(Level.FINEST, "Inferred sender '" + teleporter + "' from name '" + teleporterName + "', fetched from name '" + teleportee.getName() + "'");
this.plugin.log(Level.FINEST, String.format("Inferred sender '%s' from name '%s', fetched from name '%s'",
teleporter, teleporterName, teleportee.getName()));
MultiverseWorld fromWorld = this.worldManager.getMVWorld(event.getFrom().getWorld().getName());
MultiverseWorld toWorld = this.worldManager.getMVWorld(event.getTo().getWorld().getName());
if (event.getFrom().getWorld().equals(event.getTo().getWorld())) {
@ -166,37 +167,28 @@ public class MVPlayerListener extends PlayerListener {
// Charge the teleporter
event.setCancelled(!pt.playerHasMoneyToEnter(fromWorld, toWorld, teleporter, teleportee, true));
if (event.isCancelled() && teleporter != null) {
this.plugin.log(Level.FINE, "Player '" + teleportee.getName() + "' was DENIED ACCESS to '" + event.getTo().getWorld().getName() +
"' because '" + teleporter.getName() + "' don't have the FUNDS required to enter it.");
this.plugin.log(Level.FINE, String.format("Player '%s' was DENIED ACCESS to '%s' because '%s' don't have the FUNDS required to enter it.",
teleportee.getName(), event.getTo().getWorld().getName(), teleporter.getName()));
return;
}
if (MultiverseCore.EnforceAccess) {
event.setCancelled(!pt.playerCanGoFromTo(fromWorld, toWorld, teleporter, teleportee));
if (event.isCancelled() && teleporter != null) {
this.plugin.log(Level.FINE, "Player '" + teleportee.getName() + "' was DENIED ACCESS to '" + event.getTo().getWorld().getName() +
"' because '" + teleporter.getName() + "' don't have: multiverse.access." + event.getTo().getWorld().getName());
this.plugin.log(Level.FINE, String.format("Player '%s' was DENIED ACCESS to '%s' because '%s' don't have: multiverse.access.%s",
teleportee.getName(), event.getTo().getWorld().getName(), teleporter.getName(), event.getTo().getWorld().getName()));
}
} else {
this.plugin.log(Level.FINE, "Player '" + teleportee.getName() + "' was allowed to go to '" + event.getTo().getWorld().getName() + "' because enforceaccess is off.");
this.plugin.log(Level.FINE, String.format("Player '%s' was allowed to go to '%s' because enforceaccess is off.",
teleportee.getName(), event.getTo().getWorld().getName()));
}
}
@Override
public void onPlayerPortal(PlayerPortalEvent event) {
if (event.isCancelled() || event.getFrom() == null) {
if (event.isCancelled() || (event.getFrom() == null)) {
return;
}
// REMEMBER! getTo MAY be NULL HERE!!!
// If the player was actually outside of the portal, adjust the from location
if (event.getFrom().getWorld().getBlockAt(event.getFrom()).getType() != Material.PORTAL) {
Location newloc = SafeTTeleporter.findPortalBlockNextTo(event.getFrom());
// TODO: Fix this. Currently, we only check for PORTAL blocks. I'll have to figure out what
// TODO: we want to do here.
if (newloc != null) {
event.setFrom(newloc);
}
}
// Wait for the adjust, then return!
// The adjust should have happened much earlier.
if (event.getTo() == null) {
return;
}
@ -209,25 +201,32 @@ public class MVPlayerListener extends PlayerListener {
}
event.setCancelled(!pt.playerHasMoneyToEnter(fromWorld, toWorld, event.getPlayer(), event.getPlayer(), true));
if (event.isCancelled()) {
this.plugin.log(Level.FINE, "Player '" + event.getPlayer().getName() + "' was DENIED ACCESS to '" + event.getTo().getWorld().getName() +
"' because they don't have the FUNDS required to enter.");
this.plugin.log(Level.FINE, String.format("Player '%s' was DENIED ACCESS to '%s' because they don't have the FUNDS required to enter.",
event.getPlayer().getName(), event.getTo().getWorld().getName()));
return;
}
if (MultiverseCore.EnforceAccess) {
event.setCancelled(!pt.playerCanGoFromTo(fromWorld, toWorld, event.getPlayer(), event.getPlayer()));
if (event.isCancelled()) {
this.plugin.log(Level.FINE, "Player '" + event.getPlayer().getName() + "' was DENIED ACCESS to '" + event.getTo().getWorld().getName() +
"' because they don't have: multiverse.access." + event.getTo().getWorld().getName());
this.plugin.log(Level.FINE, String.format("Player '%s' was DENIED ACCESS to '%s' because they don't have: multiverse.access.%s",
event.getPlayer().getName(), event.getTo().getWorld().getName(), event.getTo().getWorld().getName()));
}
} else {
this.plugin.log(Level.FINE, "Player '" + event.getPlayer().getName() + "' was allowed to go to '" + event.getTo().getWorld().getName() + "' because enforceaccess is off.");
this.plugin.log(Level.FINE, String.format("Player '%s' was allowed to go to '%s' because enforceaccess is off.",
event.getPlayer().getName(), event.getTo().getWorld().getName()));
}
}
private void spawnNewPlayer(Player player) {
private void spawnNewPlayer(final Player player) {
// Spawn the player 1 tick after the login. I'm sure there's GOT to be a better way to do this...
this.plugin.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin, new SpawnNewbie(player, this.plugin.getMVWorldManager().getFirstSpawnWorld().getSpawnLocation()), 1L);
this.plugin.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin,
new Runnable() {
public void run() {
player.teleport(plugin.getMVWorldManager().getFirstSpawnWorld().getSpawnLocation());
}
}, 1L);
}
// FOLLOWING 2 Methods and Private class handle Per Player GameModes.
private void handleGameMode(Player player, World world) {
@ -237,53 +236,34 @@ public class MVPlayerListener extends PlayerListener {
}
}
public void handleGameMode(Player player, MultiverseWorld world) {
/**
* Handles the gamemode for the specified {@link Player}.
* @param player The {@link Player}.
* @param world The world the player is in.
*/
public void handleGameMode(final Player player, final MultiverseWorld world) {
// We perform this task one tick later to MAKE SURE that the player actually reaches the
// destination world, otherwise we'd be changing the player mode if they havent moved anywhere.
if (!this.pt.playerCanIgnoreGameModeRestriction(world, player)) {
this.plugin.log(Level.FINE, "Handeling gamemode for player: " + player.getName());
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin, new HandleGameMode(player, world), 1L);
} else {
this.plugin.log(Level.FINE, "Player: " + player.getName() + " is IMMUNE to gamemode changes!");
}
}
private class SpawnNewbie implements Runnable {
private Player player;
private Location spawn;
private SpawnNewbie(Player player, Location spawn) {
this.player = player;
this.spawn = spawn;
}
@Override
public void run() {
this.player.teleport(this.spawn);
}
}
/**
* The following private class is used to handle player game mode changes within a scheduler.
*/
private class HandleGameMode implements Runnable {
private Player player;
private MultiverseWorld world;
private HandleGameMode(Player player, MultiverseWorld world) {
this.player = player;
this.world = world;
}
@Override
this.plugin.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin,
new Runnable() {
public void run() {
// Check that the player is in the new world and they haven't been teleported elsewhere or the event cancelled.
if (player.getWorld().getName().equals(world.getCBWorld().getName())) {
if (player.getWorld() == world.getCBWorld()) {
MultiverseCore.staticLog(Level.FINE, "Handeling gamemode for player: " + player.getName() + ", " + world.getGameMode().toString());
MultiverseCore.staticLog(Level.FINE, "PWorld: " + player.getWorld());
MultiverseCore.staticLog(Level.FINE, "AWorld: " + world);
player.setGameMode(world.getGameMode());
} else {
MultiverseCore.staticLog(Level.FINE,
String.format("The gamemode was NOT changed for player '%s' because he is now in world '%s' instead of world '%s'",
player.getName(), player.getWorld().getName(), world.getName()));
}
}
}, 1L);
} else {
this.plugin.log(Level.FINE, "Player: " + player.getName() + " is IMMUNE to gamemode changes!");
}
}
}

View File

@ -16,6 +16,9 @@ import org.bukkit.event.server.ServerListener;
import java.util.Arrays;
import java.util.logging.Level;
/**
* Multiverse's {@link ServerListener}.
*/
public class MVPluginListener extends ServerListener {
private MultiverseCore plugin;
@ -24,7 +27,10 @@ public class MVPluginListener extends ServerListener {
this.plugin = plugin;
}
/** Keep an eye out for Plugins which we can utilize. */
/**
* Keep an eye out for Plugins which we can utilize.
* @param event The event.
*/
@Override
public void onPluginEnable(PluginEnableEvent event) {
// Let AllPay handle all econ plugin loadings, only go for econ plugins we support
@ -38,7 +44,10 @@ public class MVPluginListener extends ServerListener {
}
}
/** We'll check if any of the plugins we rely on decide to Disable themselves. */
/**
* We'll check if any of the plugins we rely on decide to Disable themselves.
* @param event The event.
*/
@Override
public void onPluginDisable(PluginDisableEvent event) {
// TODO: Disable econ when it disables.

View File

@ -0,0 +1,55 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2012. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.listeners;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.utils.SafeTTeleporter;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.event.Event.Type;
import org.bukkit.event.player.PlayerListener;
import org.bukkit.event.player.PlayerPortalEvent;
import java.util.logging.Level;
/**
* Multiverse's second {@link PlayerListener}.
* <p>
* Used to double-monitor {@link Type#PLAYER_PORTAL}.
*/
public class MVPortalAdjustListener extends PlayerListener {
private MultiverseCore plugin;
public MVPortalAdjustListener(MultiverseCore core) {
this.plugin = core;
}
@Override
public void onPlayerPortal(PlayerPortalEvent event) {
this.plugin.log(Level.FINE, "CALLING CORE-ADJUST!!!");
if (event.isCancelled() || event.getFrom() == null) {
return;
}
// REMEMBER! getTo MAY be NULL HERE!!!
// If the player was actually outside of the portal, adjust the from location
if (event.getFrom().getWorld().getBlockAt(event.getFrom()).getType() != Material.PORTAL) {
Location newloc = SafeTTeleporter.findPortalBlockNextTo(event.getFrom());
// TODO: Fix this. Currently, we only check for PORTAL blocks. I'll have to figure out what
// TODO: we want to do here.
if (newloc != null) {
event.setFrom(newloc);
}
}
// Wait for the adjust, then return!
if (event.getTo() == null) {
return;
}
}
}

View File

@ -13,6 +13,9 @@ import org.bukkit.event.weather.ThunderChangeEvent;
import org.bukkit.event.weather.WeatherChangeEvent;
import org.bukkit.event.weather.WeatherListener;
/**
* Multiverse's {@link WeatherListener}.
*/
public class MVWeatherListener extends WeatherListener {
private MultiverseCore plugin;
@ -22,7 +25,6 @@ public class MVWeatherListener extends WeatherListener {
@Override
public void onWeatherChange(WeatherChangeEvent event) {
MultiverseWorld world = this.plugin.getMVWorldManager().getMVWorld(event.getWorld().getName());
if (world != null) {
// If it's going to start raining and we have weather disabled
@ -32,7 +34,6 @@ public class MVWeatherListener extends WeatherListener {
@Override
public void onThunderChange(ThunderChangeEvent event) {
MultiverseWorld world = this.plugin.getMVWorldManager().getMVWorld(event.getWorld().getName());
if (world != null) {
// If it's going to start raining and we have weather disabled

View File

@ -0,0 +1,96 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2011. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.listeners;
import org.bukkit.event.CustomEventListener;
import org.bukkit.event.Event;
import com.onarandombox.MultiverseCore.event.MVConfigReloadEvent;
import com.onarandombox.MultiverseCore.event.MVPlayerTouchedPortalEvent;
import com.onarandombox.MultiverseCore.event.MVRespawnEvent;
import com.onarandombox.MultiverseCore.event.MVTeleportEvent;
import com.onarandombox.MultiverseCore.event.MVVersionEvent;
import com.onarandombox.MultiverseCore.event.MVWorldDeleteEvent;
import com.onarandombox.MultiverseCore.event.MVWorldPropertyChangeEvent;
/**
* Subclasses of this listener can be used to conveniently listen to MultiverseCore-events.
*/
public abstract class MultiverseCoreListener extends CustomEventListener {
/**
* {@inheritDoc}
*/
@Override
public final void onCustomEvent(Event event) {
if (event.getEventName().equals("MVConfigReload") && event instanceof MVConfigReloadEvent) {
onMVConfigReload((MVConfigReloadEvent) event);
} else if (event.getEventName().equals("MVPlayerTouchedPortalEvent") && event instanceof MVPlayerTouchedPortalEvent) {
onPlayerTouchedPortal((MVPlayerTouchedPortalEvent) event);
} else if (event.getEventName().equals("MVRespawn") && event instanceof MVRespawnEvent) {
onPlayerRespawn((MVRespawnEvent) event);
} else if (event.getEventName().equals("SafeTTeleporter") && event instanceof MVTeleportEvent) {
onPlayerTeleport((MVTeleportEvent) event);
} else if (event.getEventName().equals("MVVersionEvent") && event instanceof MVVersionEvent) {
onVersionRequest((MVVersionEvent) event);
} else if (event.getEventName().equals("MVWorldDeleteEvent") && event instanceof MVWorldDeleteEvent) {
onWorldDelete((MVWorldDeleteEvent) event);
} else if (event.getEventName().equals("MVWorldPropertyChange") && event instanceof MVWorldPropertyChangeEvent) {
onWorldPropertyChange((MVWorldPropertyChangeEvent) event);
}
}
/**
* Called when a {@link MVWorldPropertyChangeEvent} is fired.
* @param event The event.
*/
public void onWorldPropertyChange(MVWorldPropertyChangeEvent event) {
}
/**
* Called when a {@link MVWorldDeleteEvent} is fired.
* @param event The event.
*/
public void onWorldDelete(MVWorldDeleteEvent event) {
}
/**
* Called when a {@link MVVersionEvent} is fired.
* @param event The event.
*/
public void onVersionRequest(MVVersionEvent event) {
}
/**
* Called when a {@link MVTeleportEvent} is fired.
* @param event The event.
*/
public void onPlayerTeleport(MVTeleportEvent event) {
}
/**
* Called when a {@link MVRespawnEvent} is fired.
* @param event The event.
*/
public void onPlayerRespawn(MVRespawnEvent event) {
}
/**
* Called when a {@link MVPlayerTouchedPortalEvent} is fired.
* @param event The event.
*/
public void onPlayerTouchedPortal(MVPlayerTouchedPortalEvent event) {
}
/**
* Called when a {@link MVConfigReloadEvent} is fired.
* @param event The event.
*/
public void onMVConfigReload(MVConfigReloadEvent event) {
}
}

View File

@ -0,0 +1,4 @@
/**
* This package contains all listeners.
*/
package com.onarandombox.MultiverseCore.listeners;

View File

@ -0,0 +1,4 @@
/**
* The "master"-package, containing everything related to Multiverse-Core.
*/
package com.onarandombox.MultiverseCore;

View File

@ -17,12 +17,16 @@ import org.bukkit.entity.Player;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
/**
* Manages anchors.
*/
public class AnchorManager {
private MultiverseCore plugin;
private Map<String, Location> anchors;
@ -33,15 +37,18 @@ public class AnchorManager {
this.anchors = new HashMap<String, Location>();
}
/**
* Loads all anchors.
*/
public void loadAnchors() {
this.anchors = new HashMap<String, Location>();
this.anchorConfig = YamlConfiguration.loadConfiguration(new File(this.plugin.getDataFolder(), "anchors.yml"));
this.ensureConfigIsPrepared();
ConfigurationSection anchors = this.anchorConfig.getConfigurationSection("anchors");
Set<String> anchorKeys = anchors.getKeys(false);
ConfigurationSection anchorsSection = this.anchorConfig.getConfigurationSection("anchors");
Set<String> anchorKeys = anchorsSection.getKeys(false);
for (String key : anchorKeys) {
//world:x,y,z:pitch:yaw
Location anchorLocation = LocationManipulation.stringToLocation(anchors.getString(key, ""));
Location anchorLocation = LocationManipulation.stringToLocation(anchorsSection.getString(key, ""));
if (anchorLocation != null) {
MultiverseCore.staticLog(Level.INFO, "Loading anchor: '" + key + "'...");
this.anchors.put(key, anchorLocation);
@ -58,6 +65,10 @@ public class AnchorManager {
}
}
/**
* Saves all anchors.
* @return True if all anchors were successfully saved.
*/
public boolean saveAnchors() {
try {
this.anchorConfig.save(new File(this.plugin.getDataFolder(), "anchors.yml"));
@ -68,6 +79,11 @@ public class AnchorManager {
}
}
/**
* Gets the {@link Location} associated with an anchor.
* @param anchor The name of the anchor.
* @return The {@link Location}.
*/
public Location getAnchorLocation(String anchor) {
if (this.anchors.containsKey(anchor)) {
return this.anchors.get(anchor);
@ -75,11 +91,23 @@ public class AnchorManager {
return null;
}
/**
* Saves an anchor.
* @param anchor The name of the anchor.
* @param location The location of the anchor as string.
* @return True if the anchor was successfully saved.
*/
public boolean saveAnchorLocation(String anchor, String location) {
Location parsed = LocationManipulation.stringToLocation(location);
return parsed != null && this.saveAnchorLocation(anchor, parsed);
}
/**
* Saves an anchor.
* @param anchor The name of the anchor.
* @param l The {@link Location} of the anchor.
* @return True if the anchor was successfully saved.
*/
public boolean saveAnchorLocation(String anchor, Location l) {
if (l == null) {
return false;
@ -89,29 +117,43 @@ public class AnchorManager {
return this.saveAnchors();
}
/**
* Gets all anchors.
* @return An unmodifiable {@link Set} containing all anchors.
*/
public Set<String> getAllAnchors() {
return this.anchors.keySet();
return Collections.unmodifiableSet(this.anchors.keySet());
}
/**
* Gets all anchors that the specified {@link Player} can access.
* @param p The {@link Player}.
* @return An unmodifiable {@link Set} containing all anchors the specified {@link Player} can access.
*/
public Set<String> getAnchors(Player p) {
if (p == null) {
return this.anchors.keySet();
}
Set<String> anchors = new HashSet<String>();
for(String anchor : this.anchors.keySet()) {
Set<String> myAnchors = new HashSet<String>();
for (String anchor : this.anchors.keySet()) {
Location ancLoc = this.anchors.get(anchor);
if(ancLoc == null) {
if (ancLoc == null) {
continue;
}
if(p.hasPermission("multiverse.access." + ancLoc.getWorld().getName())) {
anchors.add(anchor);
if (p.hasPermission("multiverse.access." + ancLoc.getWorld().getName())) {
myAnchors.add(anchor);
}
}
return anchors;
return Collections.unmodifiableSet(myAnchors);
}
/**
* Deletes the specified anchor.
* @param s The name of the anchor.
* @return True if the anchor was successfully deleted.
*/
public boolean deleteAnchor(String s) {
if(this.anchors.containsKey(s)) {
if (this.anchors.containsKey(s)) {
this.anchors.remove(s);
this.anchorConfig.set("anchors." + s, null);
return this.saveAnchors();

View File

@ -11,32 +11,40 @@ import com.onarandombox.MultiverseCore.MultiverseCore;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Minecart;
import org.bukkit.entity.Vehicle;
import java.util.logging.Level;
/**
* Used to determine block/location-related facts.
*/
public class BlockSafety {
public BlockSafety() {
// TODO Auto-generated constructor stub
}
/**
* This function checks whether the block at the given coordinates are above air or not.
* @param l The {@link Location} of the block.
* @return True if the block at that {@link Location} is above air.
*/
public boolean isBlockAboveAir(Location l) {
Location downOne = new Location(l.getWorld(), l.getX(), l.getY(), l.getZ());
Location downOne = l.clone();
downOne.setY(downOne.getY() - 1);
return (downOne.getBlock().getType() == Material.AIR);
}
public boolean blockIsNotSafe(World world, double x, double y, double z) {
Location l = new Location(world, x, y, z);
return !playerCanSpawnHereSafely(l);
// TODO maybe remove this?
private boolean blockIsNotSafe(World world, double x, double y, double z) {
return !playerCanSpawnHereSafely(world, x, y, z);
}
/**
* Checks if a player can spawn safely at the given coordinates.
* @param world The {@link World}.
* @param x The x-coordinate.
* @param y The y-coordinate.
* @param z The z-coordinate.
* @return True if a player can spawn safely at the given coordinates.
*/
public boolean playerCanSpawnHereSafely(World world, double x, double y, double z) {
Location l = new Location(world, x, y, z);
return playerCanSpawnHereSafely(l);
@ -50,7 +58,7 @@ public class BlockSafety {
* @return Whether the player can spawn safely at the given {@link Location}
*/
public boolean playerCanSpawnHereSafely(Location l) {
if(l == null) {
if (l == null) {
// Can't safely spawn at a null location!
return false;
}
@ -62,20 +70,24 @@ public class BlockSafety {
upOne.setY(upOne.getY() + 1);
downOne.setY(downOne.getY() - 1);
if (this.isSolidBlock(world.getBlockAt(actual).getType()) ||
this.isSolidBlock(upOne.getBlock().getType())) {
MultiverseCore.staticLog(Level.FINER, "Error Here (Actual)? (" + actual.getBlock().getType() + ")[" + this.isSolidBlock(actual.getBlock().getType()) + "]");
MultiverseCore.staticLog(Level.FINER, "Error Here (upOne)? (" + upOne.getBlock().getType() + ")[" + this.isSolidBlock(upOne.getBlock().getType()) + "]");
if (this.isSolidBlock(world.getBlockAt(actual).getType())
|| this.isSolidBlock(upOne.getBlock().getType())) {
MultiverseCore.staticLog(Level.FINER, "Error Here (Actual)? ("
+ actual.getBlock().getType() + ")[" + this.isSolidBlock(actual.getBlock().getType()) + "]");
MultiverseCore.staticLog(Level.FINER, "Error Here (upOne)? ("
+ upOne.getBlock().getType() + ")[" + this.isSolidBlock(upOne.getBlock().getType()) + "]");
return false;
}
if (downOne.getBlock().getType() == Material.LAVA || downOne.getBlock().getType() == Material.STATIONARY_LAVA) {
MultiverseCore.staticLog(Level.FINER, "Error Here (downOne)? (" + downOne.getBlock().getType() + ")[" + this.isSolidBlock(downOne.getBlock().getType()) + "]");
MultiverseCore.staticLog(Level.FINER, "Error Here (downOne)? ("
+ downOne.getBlock().getType() + ")[" + this.isSolidBlock(downOne.getBlock().getType()) + "]");
return false;
}
if (downOne.getBlock().getType() == Material.FIRE) {
MultiverseCore.staticLog(Level.FINER, "There's fire below! (" + actual.getBlock().getType() + ")[" + this.isSolidBlock(actual.getBlock().getType()) + "]");
MultiverseCore.staticLog(Level.FINER, "There's fire below! ("
+ actual.getBlock().getType() + ")[" + this.isSolidBlock(actual.getBlock().getType()) + "]");
return false;
}
@ -87,9 +99,14 @@ public class BlockSafety {
return true;
}
/**
* Gets the location of the top block at the specified {@link Location}.
* @param l Any {@link Location}.
* @return The {@link Location} of the top-block.
*/
public Location getTopBlock(Location l) {
Location check = l.clone();
check.setY(127);
check.setY(127); // SUPPRESS CHECKSTYLE: MagicNumberCheck
while (check.getY() > 0) {
if (this.playerCanSpawnHereSafely(check)) {
return check;
@ -99,10 +116,15 @@ public class BlockSafety {
return null;
}
/**
* Gets the location of the top block at the specified {@link Location}.
* @param l Any {@link Location}.
* @return The {@link Location} of the top-block.
*/
public Location getBottomBlock(Location l) {
Location check = l.clone();
check.setY(0);
while (check.getY() <= 126) {
while (check.getY() < 127) { // SUPPRESS CHECKSTYLE: MagicNumberCheck
if (this.playerCanSpawnHereSafely(check)) {
return check;
}
@ -111,7 +133,7 @@ public class BlockSafety {
return null;
}
/**
/*
* If someone has a better way of this... Please either tell us, or submit a pull request!
*/
private boolean isSolidBlock(Material type) {
@ -174,16 +196,23 @@ public class BlockSafety {
return false;
case WATER:
return false;
}
default:
return true;
}
}
public boolean isEntitiyOnTrack(Entity e, Location l) {
/**
* Checks if an entity would be on track at the specified {@link Location}.
* @param l The {@link Location}.
* @return True if an entity would be on tracks at the specified {@link Location}.
*/
public boolean isEntitiyOnTrack(Location l) {
Material currentBlock = l.getBlock().getType();
return (currentBlock == Material.POWERED_RAIL || currentBlock == Material.DETECTOR_RAIL || currentBlock == Material.RAILS);
}
public void showDangers(Location l) {
// TODO maybe remove this?
private void showDangers(Location l) {
Location actual = new Location(l.getWorld(), l.getX(), l.getY(), l.getZ());
Location upOne = new Location(l.getWorld(), l.getX(), l.getY(), l.getZ());
Location downOne = new Location(l.getWorld(), l.getX(), l.getY(), l.getZ());
@ -204,7 +233,7 @@ public class BlockSafety {
* @param l The {@link Location}
* @return Whether there are 2 blocks of water
*/
public boolean hasTwoBlocksofWaterBelow(Location l) {
private boolean hasTwoBlocksofWaterBelow(Location l) {
if (l.getBlockY() < 0) {
return false;
}
@ -221,17 +250,26 @@ public class BlockSafety {
return hasTwoBlocksofWaterBelow(oneBelow);
}
/**
* Checks if the specified {@link Minecart} can spawn safely.
* @param cart The {@link Minecart}.
* @return True if the minecart can spawn safely.
*/
public boolean canSpawnCartSafely(Minecart cart) {
if (this.isBlockAboveAir(cart.getLocation())) {
return true;
}
if (this.isEntitiyOnTrack(cart, LocationManipulation.getNextBlock(cart))) {
if (this.isEntitiyOnTrack(LocationManipulation.getNextBlock(cart))) {
return true;
}
return false;
}
/**
* Checks if the specified {@link Vehicle} can spawn safely.
* @param vehicle The {@link Vehicle}.
* @return True if the vehicle can spawn safely.
*/
public boolean canSpawnVehicleSafely(Vehicle vehicle) {
if (this.isBlockAboveAir(vehicle.getLocation())) {
return true;

View File

@ -18,6 +18,9 @@ import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
/**
* The Multiverse debug-logger.
*/
public class DebugLog {
private FileHandler fh;
@ -51,13 +54,16 @@ public class DebugLog {
/**
* Log a message at a certain level.
*
* @param level
* @param msg
* @param level The log-{@link Level}.
* @param msg the message.
*/
public void log(Level level, String msg) {
this.log.log(level, msg);
}
/**
* Our log-{@link Formatter}.
*/
private class LogFormatter extends Formatter {
private final SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@ -83,6 +89,9 @@ public class DebugLog {
}
}
/**
* Closes this {@link DebugLog}.
*/
public void close() {
this.fh.close();
}

View File

@ -9,6 +9,9 @@ package com.onarandombox.MultiverseCore.utils;
import org.bukkit.ChatColor;
/**
* A color-scheme.
*/
public class FancyColorScheme {
private ChatColor headerColor;
private ChatColor mainColor;
@ -22,22 +25,43 @@ public class FancyColorScheme {
this.defContentColor = defaultColor;
}
/**
* Gets the header's {@link ChatColor}.
* @return The header's {@link ChatColor}.
*/
public ChatColor getHeader() {
return this.headerColor;
}
/**
* Gets the main {@link ChatColor}.
* @return The main {@link ChatColor}.
*/
public ChatColor getMain() {
return this.mainColor;
}
/**
* Gets the alt {@link ChatColor}.
* @return The alt {@link ChatColor}.
*/
public ChatColor getAlt() {
return this.altColor;
}
/**
* Gets the default {@link ChatColor}.
* @return The default {@link ChatColor}.
*/
public ChatColor getDefault() {
return this.defContentColor;
}
/**
* Gets either the main or the alt {@link ChatColor}.
* @param main True if the main-color is desired, false to get the alt color.
* @return The desired {@link ChatColor}.
*/
public ChatColor getMain(boolean main) {
return main ? this.getMain() : this.getAlt();
}

View File

@ -9,23 +9,30 @@ package com.onarandombox.MultiverseCore.utils;
import com.onarandombox.MultiverseCore.api.FancyText;
/**
* A colored text-header.
*/
public class FancyHeader implements FancyText {
private FancyColorScheme colors;
private String text;
private StringBuilder text;
public FancyHeader(String text, FancyColorScheme scheme) {
this.colors = scheme;
this.text = text;
this.text = new StringBuilder(text);
}
@Override
public String getFancyText() {
return colors.getHeader() + "--- " + text + colors.getHeader() + " ---";
return String.format("%s--- %s%s ---", colors.getHeader(), text.toString(), colors.getHeader());
}
/**
* Appends text to this {@link FancyHeader}.
* @param string The text to append.
*/
public void appendText(String string) {
this.text += string;
this.text.append(string);
}
}

View File

@ -9,6 +9,9 @@ package com.onarandombox.MultiverseCore.utils;
import com.onarandombox.MultiverseCore.api.FancyText;
/**
* A colored text-message.
*/
public class FancyMessage implements FancyText {
private String title;
private String message;
@ -27,10 +30,16 @@ public class FancyMessage implements FancyText {
this.colors = scheme;
}
/**
* Makes this {@link FancyMessage} use the main-color.
*/
public void setColorMain() {
this.main = true;
}
/**
* Makes this {@link FancyMessage} use the alt-color.
*/
public void setColorAlt() {
this.main = false;
}
@ -40,10 +49,18 @@ public class FancyMessage implements FancyText {
return this.colors.getMain(this.main) + this.title + this.colors.getDefault() + message;
}
/**
* Specifies whether this {@link FancyMessage} should use the alt-color.
* @param altColor Whether this {@link FancyMessage} should use the alt-color.
*/
public void setAltColor(boolean altColor) {
this.main = !altColor;
}
/**
* Specifies whether this {@link FancyMessage} should use the main-color.
* @param mainColor Whether this {@link FancyMessage} should use the main-color.
*/
public void setMainColor(boolean mainColor) {
this.main = mainColor;
}

View File

@ -9,18 +9,19 @@ package com.onarandombox.MultiverseCore.utils;
import java.io.File;
/**
* File-utilities.
*/
public class FileUtils {
protected FileUtils()
{
protected FileUtils() {
throw new UnsupportedOperationException();
}
/*
* Delete a folder Courtesy of: lithium3141
/**
* Used to delete a folder.
*
* @param file The folder to delete
*
* @return true if success
* @param file The folder to delete.
* @return true if the folder was successfully deleted.
*/
public static boolean deleteFolder(File file) {
if (file.exists()) {

View File

@ -15,16 +15,20 @@ import org.bukkit.entity.Vehicle;
import org.bukkit.util.Vector;
import java.text.DecimalFormat;
import java.util.Formatter;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Utility class to manipulate locations.
*/
public class LocationManipulation {
private LocationManipulation() { }
private static Map<String, Integer> orientationInts = new HashMap<String, Integer>();
static {
// BEGIN CHECKSTYLE-SUPPRESSION: MagicNumberCheck
orientationInts.put("n", 180);
orientationInts.put("ne", 225);
orientationInts.put("e", 270);
@ -33,6 +37,10 @@ public class LocationManipulation {
orientationInts.put("sw", 45);
orientationInts.put("w", 90);
orientationInts.put("nw", 135);
// "freeze" the map:
orientationInts = Collections.unmodifiableMap(orientationInts);
// END CHECKSTYLE-SUPPRESSION: MagicNumberCheck
}
/**
@ -49,10 +57,21 @@ public class LocationManipulation {
if (location == null) {
return "";
}
StringBuilder l = new StringBuilder();
Formatter formatter = new Formatter(l);
formatter.format("%s:%.2f,%.2f,%.2f:%.2f:%.2f", location.getWorld().getName(), location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch());
return formatter.toString();
return String.format("%s:%.2f,%.2f,%.2f:%.2f:%.2f", location.getWorld().getName(),
location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch());
}
/**
* This method simply does some rounding, rather than forcing a call to the server to get the blockdata.
*
* @param l The location to round to the block location
* @return A rounded location.
*/
public static Location getBlockLocation(Location l) {
l.setX(l.getBlockX());
l.setY(l.getBlockY());
l.setZ(l.getBlockZ());
return l;
}
/**
@ -75,7 +94,7 @@ public class LocationManipulation {
// Split the whole string, format is:
// {'world', 'x,y,z'[, 'pitch', 'yaw']}
String[] split = locationString.split(":");
if (split.length < 2 || split.length > 4) {
if (split.length < 2 || split.length > 4) { // SUPPRESS CHECKSTYLE: MagicNumberCheck
return null;
}
// Split the xyz string, format is:
@ -97,7 +116,7 @@ public class LocationManipulation {
if (split.length >= 3) {
yaw = (float) Double.parseDouble(split[2]);
}
if (split.length == 4) {
if (split.length == 4) { // SUPPRESS CHECKSTYLE: MagicNumberCheck
pitch = (float) Double.parseDouble(split[3]);
}
return new Location(w, Double.parseDouble(xyzsplit[0]), Double.parseDouble(xyzsplit[1]), Double.parseDouble(xyzsplit[2]), yaw, pitch);
@ -132,7 +151,7 @@ public class LocationManipulation {
* @return The {@link String}
*/
public static String strCoordsRaw(Location l) {
if(l == null) {
if (l == null) {
return "null";
}
String result = "";
@ -154,6 +173,7 @@ public class LocationManipulation {
* @return The NESW Direction
*/
public static String getDirection(Location location) {
// BEGIN CHECKSTYLE-SUPPRESSION: MagicNumberCheck
double r = (location.getYaw() % 360) + 180;
// Remember, these numbers are every 45 degrees with a 22.5 offset, to detect boundaries.
String dir;
@ -175,6 +195,7 @@ public class LocationManipulation {
dir = "nw";
else
dir = "n";
// END CHECKSTYLE-SUPPRESSION: MagicNumberCheck
return dir;
}

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