From 91f7debb08b776227439081c43e2b658acf26bda Mon Sep 17 00:00:00 2001 From: "main()" Date: Sun, 4 Mar 2012 15:14:42 +0100 Subject: [PATCH] MVWorld + SerializationConfig = Awesome Yes, I did it. --- pom.xml | 2 +- .../onarandombox/MultiverseCore/MVWorld.java | 1366 +++++++++-------- .../MultiverseCore/MultiverseCore.java | 3 + .../MultiverseCoreConfiguration.java | 13 + .../api/MultiverseCoreConfig.java | 2 +- .../MultiverseCore/api/MultiverseWorld.java | 524 ++++--- .../commands/ConfigCommand.java | 2 +- .../commands/ModifyAddCommand.java | 1 + .../commands/ModifyClearCommand.java | 1 + .../commands/ModifyRemoveCommand.java | 1 + .../commands/ModifySetCommand.java | 9 +- .../ActiveStringConfigProperty.java | 115 -- .../configuration/BooleanConfigProperty.java | 135 -- .../configuration/ColorConfigProperty.java | 98 -- .../configuration/ConfigPropertyFactory.java | 306 ---- .../DifficultyConfigProperty.java | 129 -- .../configuration/DoubleConfigProperty.java | 133 -- .../configuration/GameModeConfigProperty.java | 129 -- .../configuration/IntegerConfigProperty.java | 97 -- .../configuration/LocationConfigProperty.java | 154 -- .../configuration/MVActiveConfigProperty.java | 2 + .../configuration/MVConfigProperty.java | 2 + .../PortalTypeConfigProperty.java | 97 -- .../configuration/SpawnLocation.java | 98 ++ .../configuration/SpawnSettings.java | 50 + .../configuration/StringConfigProperty.java | 96 -- .../configuration/SubSpawnSettings.java | 59 + .../configuration/WorldPropertyValidator.java | 27 + .../enums/EnglishChatColor.java | 9 + .../event/MVWorldPropertyChangeEvent.java | 34 +- .../PropertyDoesNotExistException.java | 4 + .../MultiverseCore/utils/WorldManager.java | 178 +-- .../test/TestWorldProperties.java | 8 +- .../MultiverseCore/test/TestWorldStuff.java | 4 +- .../test/utils/MockWorldFactory.java | 40 + .../test/utils/TestInstanceCreator.java | 6 + 36 files changed, 1418 insertions(+), 2516 deletions(-) delete mode 100644 src/main/java/com/onarandombox/MultiverseCore/configuration/ActiveStringConfigProperty.java delete mode 100644 src/main/java/com/onarandombox/MultiverseCore/configuration/BooleanConfigProperty.java delete mode 100644 src/main/java/com/onarandombox/MultiverseCore/configuration/ColorConfigProperty.java delete mode 100644 src/main/java/com/onarandombox/MultiverseCore/configuration/ConfigPropertyFactory.java delete mode 100644 src/main/java/com/onarandombox/MultiverseCore/configuration/DifficultyConfigProperty.java delete mode 100644 src/main/java/com/onarandombox/MultiverseCore/configuration/DoubleConfigProperty.java delete mode 100644 src/main/java/com/onarandombox/MultiverseCore/configuration/GameModeConfigProperty.java delete mode 100644 src/main/java/com/onarandombox/MultiverseCore/configuration/IntegerConfigProperty.java delete mode 100644 src/main/java/com/onarandombox/MultiverseCore/configuration/LocationConfigProperty.java delete mode 100644 src/main/java/com/onarandombox/MultiverseCore/configuration/PortalTypeConfigProperty.java create mode 100644 src/main/java/com/onarandombox/MultiverseCore/configuration/SpawnLocation.java create mode 100644 src/main/java/com/onarandombox/MultiverseCore/configuration/SpawnSettings.java delete mode 100644 src/main/java/com/onarandombox/MultiverseCore/configuration/StringConfigProperty.java create mode 100644 src/main/java/com/onarandombox/MultiverseCore/configuration/SubSpawnSettings.java create mode 100644 src/main/java/com/onarandombox/MultiverseCore/configuration/WorldPropertyValidator.java diff --git a/pom.xml b/pom.xml index 8739e055..158ab819 100644 --- a/pom.xml +++ b/pom.xml @@ -196,7 +196,7 @@ me.main__.util SerializationConfig - 1.3 + 1.5 jar compile diff --git a/src/main/java/com/onarandombox/MultiverseCore/MVWorld.java b/src/main/java/com/onarandombox/MultiverseCore/MVWorld.java index 3d376a39..7fc86550 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MVWorld.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MVWorld.java @@ -9,14 +9,23 @@ package com.onarandombox.MultiverseCore; import com.onarandombox.MultiverseCore.api.BlockSafety; import com.onarandombox.MultiverseCore.api.MultiverseWorld; -import com.onarandombox.MultiverseCore.configuration.ConfigPropertyFactory; -import com.onarandombox.MultiverseCore.configuration.MVActiveConfigProperty; -import com.onarandombox.MultiverseCore.configuration.MVConfigProperty; +import com.onarandombox.MultiverseCore.configuration.SpawnLocation; +import com.onarandombox.MultiverseCore.configuration.SpawnSettings; +import com.onarandombox.MultiverseCore.configuration.WorldPropertyValidator; import com.onarandombox.MultiverseCore.enums.AllowedPortalType; import com.onarandombox.MultiverseCore.enums.EnglishChatColor; -import com.onarandombox.MultiverseCore.event.MVWorldPropertyChangeEvent; import com.onarandombox.MultiverseCore.exceptions.PropertyDoesNotExistException; import com.onarandombox.MultiverseCore.api.SafeTTeleporter; + +import me.main__.util.SerializationConfig.ChangeDeniedException; +import me.main__.util.SerializationConfig.IllegalPropertyValueException; +import me.main__.util.SerializationConfig.NoSuchPropertyException; +import me.main__.util.SerializationConfig.Property; +import me.main__.util.SerializationConfig.SerializationConfig; +import me.main__.util.SerializationConfig.Serializor; +import me.main__.util.SerializationConfig.ValidateAllWith; +import me.main__.util.SerializationConfig.VirtualProperty; + import org.bukkit.ChatColor; import org.bukkit.Difficulty; import org.bukkit.GameMode; @@ -25,15 +34,13 @@ import org.bukkit.World; import org.bukkit.World.Environment; import org.bukkit.WorldType; import org.bukkit.command.CommandSender; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.serialization.SerializableAs; import org.bukkit.entity.Player; import org.bukkit.permissions.Permission; import org.bukkit.permissions.PermissionDefault; -import java.io.File; -import java.io.IOException; -import java.lang.reflect.Method; +import java.lang.ref.Reference; +import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -46,157 +53,429 @@ import java.util.regex.Pattern; /** * The implementation of a Multiverse handled world. */ -public class MVWorld implements MultiverseWorld { +@SerializableAs("MVWorld") +@ValidateAllWith(WorldPropertyValidator.class) +public class MVWorld extends SerializationConfig implements MultiverseWorld { + private static final int SPAWN_LOCATION_SEARCH_TOLERANCE = 16; + private static final int SPAWN_LOCATION_SEARCH_RADIUS = 16; + + /* + * We have to use setCBWorld(), setPlugin() and initPerms() to prepare this object for use. + */ + public MVWorld(Map values) { + super(values); + } private MultiverseCore plugin; // Hold the Plugin Instance. - private FileConfiguration config; // Hold the Configuration File. - private ConfigurationSection worldSection; // Holds the section of the config file for this world. - private World world; // The World Instance. + private Reference world; // A reference to the World Instance. private Environment environment; // Hold the Environment type EG Environment.NETHER / Environment.NORMAL - private Long seed; // The world seed + private long seed; // The world seed private String name; // The Worlds Name, EG its folder name. - private Map> masterList; - private Map> propertyList; + /** + * Validates the scale-property. + */ + private final class ScalePropertyValidator extends WorldPropertyValidator { + @Override + public Double validateChange(String property, Double newValue, Double oldValue, + MVWorld object) throws ChangeDeniedException { + if (newValue <= 0) { + plugin.log(Level.FINE, "Someone tried to set a scale <= 0, aborting!"); + throw new ChangeDeniedException(); + } + return super.validateChange(property, newValue, oldValue, object); + } + } + + /** + * Validates the respawnWorld-property. + */ + private final class RespawnWorldPropertyValidator extends WorldPropertyValidator { + @Override + public String validateChange(String property, String newValue, String oldValue, + MVWorld object) throws ChangeDeniedException { + if (!plugin.getMVWorldManager().isMVWorld(newValue)) + throw new ChangeDeniedException(); + return super.validateChange(property, newValue, oldValue, object); + } + } + + /** + * Serializor for the time-property. + */ + private static final class TimePropertySerializor implements Serializor { + // BEGIN CHECKSTYLE-SUPPRESSION: MagicNumberCheck + private static final String TIME_REGEX = "(\\d\\d?):?(\\d\\d)(a|p)?m?"; + private static final Map TIME_ALIASES; + static { + Map staticTimes = new HashMap(); + 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); + } + + @Override + public String serialize(Long from) { + // I'm tired, so they get time in 24 hour for now. + // Someone else can add 12 hr format if they want :P + + int hours = (int) ((from / 1000 + 8) % 24); + int minutes = (int) (60 * (from % 1000) / 1000); + + return String.format("%d:%02d", hours, minutes); + } + + @Override + public Long deserialize(String serialized, Class wanted) throws IllegalPropertyValueException { + if (TIME_ALIASES.containsKey(serialized.toLowerCase())) { + serialized = TIME_ALIASES.get(serialized.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. + Pattern pattern = Pattern.compile(TIME_REGEX, Pattern.CASE_INSENSITIVE); + Matcher matcher = pattern.matcher(serialized); + 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, am/pm) + 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) { + hour = 0; + } + // Clamp the hour + if (hour > 23 || hour < 0) { + throw new IllegalPropertyValueException("Illegal hour!"); + } + // Clamp the minute + if (minute > 59 || minute < 0) { + throw new IllegalPropertyValueException("Illegal minute!"); + } + // 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; + } + + return (long) totaltime; + } + // END CHECKSTYLE-SUPPRESSION: MagicNumberCheck + } + + /** + * Used to apply the allowWeather-property. + */ + private final class AllowWeatherPropertyValidator extends WorldPropertyValidator { + @Override + public Boolean validateChange(String property, Boolean newValue, Boolean oldValue, + MVWorld object) throws ChangeDeniedException { + if (!newValue) { + world.get().setStorm(false); + world.get().setThundering(false); + } + return super.validateChange(property, newValue, oldValue, object); + } + } + + /** + * Used to apply the spawning-property. + */ + private final class SpawningPropertyValidator extends WorldPropertyValidator { + @Override + public Boolean validateChange(String property, Boolean newValue, Boolean oldValue, + MVWorld object) throws ChangeDeniedException { + boolean allowMonsters, allowAnimals; + if (getAnimalList().isEmpty()) { + allowAnimals = canAnimalsSpawn(); + } else { + allowAnimals = true; + } + if (getMonsterList().isEmpty()) { + allowMonsters = canMonstersSpawn(); + } else { + allowMonsters = true; + } + world.get().setSpawnFlags(allowMonsters, allowAnimals); + plugin.getMVWorldManager().getTheWorldPurger().purgeWorld(MVWorld.this); + return super.validateChange(property, newValue, oldValue, object); + } + } + + /** + * Serializor for the difficulty-property. + */ + private static final class DifficultyPropertySerializor implements Serializor { + @Override + public String serialize(Difficulty from) { + return from.toString(); + } + + @Override + public Difficulty deserialize(String serialized, Class wanted) throws IllegalPropertyValueException { + try { + return Difficulty.getByValue(Integer.parseInt(serialized)); + } catch (Exception e) { + } + try { + return Difficulty.valueOf(serialized.toUpperCase()); + } catch (Exception e) { + } + throw new IllegalPropertyValueException(); + } + } + + /** + * Serializor for the gameMode-property. + */ + private static final class GameModePropertySerializor implements Serializor { + @Override + public String serialize(GameMode from) { + return from.toString(); + } + + @Override + public GameMode deserialize(String serialized, Class wanted) throws IllegalPropertyValueException { + try { + return GameMode.getByValue(Integer.parseInt(serialized)); + } catch (NumberFormatException nfe) { + } + try { + return GameMode.valueOf(serialized.toUpperCase()); + } catch (Exception e) { + } + throw new IllegalPropertyValueException(); + } + } + + + /** + * Used to apply the gameMode-property. + */ + private final class GameModePropertyValidator extends WorldPropertyValidator { + @Override + public GameMode validateChange(String property, GameMode newValue, GameMode oldValue, + MVWorld object) throws ChangeDeniedException { + for (Player p : plugin.getServer().getWorld(getName()).getPlayers()) { + plugin.log(Level.FINER, String.format("Setting %s's GameMode to %s", + p.getName(), newValue.toString())); + plugin.getPlayerListener().handleGameMode(p, MVWorld.this); + } + return super.validateChange(property, newValue, oldValue, object); + } + } + + /** + * Validator for the spawnLocation-property. + */ + private final class SpawnLocationPropertyValidator extends WorldPropertyValidator { + @Override + public Location validateChange(String property, Location newValue, Location oldValue, + MVWorld object) throws ChangeDeniedException { + if (newValue == null) + throw new ChangeDeniedException(); + if (adjustSpawn) { + BlockSafety bs = plugin.getBlockSafety(); + // verify that the location is safe + if (!bs.playerCanSpawnHereSafely(newValue)) { + // it's not ==> find a better one! + plugin.log(Level.WARNING, String.format("Somebody tried to set the spawn location for '%s' to an unsafe value! Adjusting...", getAlias())); + plugin.log(Level.WARNING, "Old Location: " + plugin.getLocationManipulation().strCoordsRaw(oldValue)); + plugin.log(Level.WARNING, "New (unsafe) Location: " + plugin.getLocationManipulation().strCoordsRaw(newValue)); + SafeTTeleporter teleporter = plugin.getSafeTTeleporter(); + newValue = teleporter.getSafeLocation(newValue, SPAWN_LOCATION_SEARCH_TOLERANCE, SPAWN_LOCATION_SEARCH_RADIUS); + if (newValue == null) { + plugin.log(Level.WARNING, "Couldn't fix the location. I have to abort the spawn location-change :/"); + throw new ChangeDeniedException(); + } + plugin.log(Level.WARNING, "New (safe) Location: " + plugin.getLocationManipulation().strCoordsRaw(newValue)); + } + } + return super.validateChange(property, newValue, oldValue, object); + } + } + + /** + * Serializor for the color-property. + */ + private static final class EnumPropertySerializor> implements Serializor { + @Override + public String serialize(T from) { + return from.toString(); + } + + @Override + public T deserialize(String serialized, Class wanted) throws IllegalPropertyValueException { + try { + return Enum.valueOf(wanted, serialized.toUpperCase()); + } catch (IllegalArgumentException e) { + throw new IllegalPropertyValueException(e); + } + } + } + + // -------------------------------------------------------------- + // Begin properties + @Property(description = "Sorry, 'hidden' must either be: true or false.") + private boolean hidden; + @Property(description = "Alias must be a valid string.") + private String alias; + @Property(serializor = EnumPropertySerializor.class, description = "Sorry, 'color' must be a valid color-name.") + private EnglishChatColor color; + @Property(description = "Sorry, 'pvp' must either be: true or false.") + private VirtualProperty pvp = new VirtualProperty() { + @Override + public void set(Boolean newValue) { + world.get().setPVP(newValue); + } + + @Override + public Boolean get() { + return world.get().getPVP(); + } + }; + @Property(validator = ScalePropertyValidator.class, description = "Scale must be a positive double value. ex: 2.3") + private double scale; + @Property(validator = RespawnWorldPropertyValidator.class, description = "You must set this to the NAME not alias of a world.") + private String respawnWorld; + @Property(validator = AllowWeatherPropertyValidator.class, description = "Sorry, this must either be: true or false.") + private boolean allowWeather; + @Property(serializor = DifficultyPropertySerializor.class, description = "Difficulty must be set as one of the following: peaceful easy normal hard") + private VirtualProperty difficulty = new VirtualProperty() { + @Override + public void set(Difficulty newValue) { + world.get().setDifficulty(newValue); + } + + @Override + public Difficulty get() { + return world.get().getDifficulty(); + } + }; + @Property(validator = SpawningPropertyValidator.class, description = "Sorry, 'animals' must either be: true or false.") + private SpawnSettings spawning; + @Property(description = "Currency must be an integer between -1 and the highest Minecraft item ID.") + private int currency; + @Property(description = "Price must be a double value. ex: 1.2. Set to a negative value to give players money for entering this world.") + private double price; + @Property(description = "Sorry, 'hunger' must either be: true or false.") + private boolean hunger; + @Property(description = "Sorry, 'autoheal' must either be: true or false.") + private boolean autoHeal; + @Property(description = "Sorry, 'adjustspawn' must either be: true or false.") + private boolean adjustSpawn; + @Property(serializor = EnumPropertySerializor.class, description = "Allow portal forming must be NONE, ALL, NETHER or END.") + private AllowedPortalType portalForm; + @Property(serializor = GameModePropertySerializor.class, validator = GameModePropertyValidator.class, + description = "GameMode must be set as one of the following: survival creative") + private GameMode gameMode; + @Property(description = "Sorry, this must either be: true or false.") + private VirtualProperty keepSpawnInMemory = new VirtualProperty() { + @Override + public void set(Boolean newValue) { + world.get().setKeepSpawnInMemory(newValue); + } + + @Override + public Boolean get() { + return world.get().getKeepSpawnInMemory(); + } + }; + @Property + private SpawnLocation spawnLocation; + @Property(validator = SpawnLocationPropertyValidator.class, + description = "There is no help available for this variable. Go bug Rigby90 about it.") + private VirtualProperty spawn = new VirtualProperty() { + @Override + public void set(Location newValue) { + world.get().setSpawnLocation(newValue.getBlockX(), newValue.getBlockY(), newValue.getBlockZ()); + spawnLocation = new SpawnLocation(newValue); + } + + @Override + public Location get() { + spawnLocation.setWorld(getCBWorld()); + // basically, everybody should accept our "SpawnLocation", right? + // so just returning it should be fine + return spawnLocation; + } + }; + @Property(description = "Set this to false ONLY if you don't want this world to load itself on server restart.") + private boolean autoLoad; + @Property(description = "If a player dies in this world, shoudld they go to their bed?") + private boolean bedRespawn; + @Property + private List worldBlacklist; + @SuppressWarnings("unused") // it IS used! + @Property(serializor = TimePropertySerializor.class, description = "Set the time to whatever you want! (Will NOT freeze time)") + private VirtualProperty time = new VirtualProperty() { + @Override + public void set(Long newValue) { + world.get().setTime(newValue); + } + + @Override + public Long get() { + return world.get().getTime(); + } + }; + // End of properties + // -------------------------------------------------------------- private Permission permission; private Permission exempt; - - private boolean canSave = false; // Prevents all the setters from constantly saving to the config when being called from the constructor. - private Map propertyAliases; private Permission ignoreperm; - private static final Map TIME_ALIASES; - private WorldType type; - - static { - Map staticTimes = new HashMap(); - 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(boolean fixSpawn) { + if (!fixSpawn) { + this.adjustSpawn = false; + } } - public MVWorld(World world, FileConfiguration config, MultiverseCore instance, Long seed, String generatorString, boolean fixSpawn) { - this.config = config; - this.plugin = instance; + /** + * Sets the CB-World. + *

+ * This is used to set some values after deserialization. + * @param cbWorld The new world. + * @param thePlugin The reference to the plugin. + */ + public void init(World cbWorld, MultiverseCore thePlugin) { + this.plugin = thePlugin; - // Set local values that CANNOT be changed by user - this.world = world; - this.name = world.getName(); - this.seed = seed; - this.environment = world.getEnvironment(); - this.type = world.getWorldType(); + // Weak reference so the CB-World can be unloaded even if this object still exists! + this.world = new WeakReference(cbWorld); + this.environment = cbWorld.getEnvironment(); + this.seed = cbWorld.getSeed(); + this.name = cbWorld.getName(); + if (this.spawnLocation == null) + this.spawnLocation = new SpawnLocation(readSpawnFromWorld(cbWorld)); - // Initialize our lists - this.initLists(); - worldSection = config.getConfigurationSection("worlds." + this.name); - if (worldSection == null) { - config.createSection("worlds." + this.name); - worldSection = config.getConfigurationSection("worlds." + this.name); - } - // Write these files to the config (once it's saved) - if (generatorString != null) { - worldSection.set("generator", generatorString); - } - if (seed != null) { - worldSection.set("seed", this.seed); - } - worldSection.set("environment", this.environment.toString()); - - worldSection.set("type", this.type.toString()); - - // Start NEW config awesomeness. - ConfigPropertyFactory fac = new ConfigPropertyFactory(this.worldSection); - this.propertyList = new HashMap>(); - // The format of these are either: - // getNewProperty(name, defaultValue, helpText) - // or - // 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, "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 + ".")); - this.propertyList.put("portalform", fac.getNewProperty("portalform", AllowedPortalType.ALL, - "Allow portal forming must be NONE, ALL, NETHER or END.")); - 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 + ".", "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())); - - - // Set aliases - this.propertyAliases = new HashMap(); - this.propertyAliases.put("curr", "currency"); - this.propertyAliases.put("scaling", "scale"); - this.propertyAliases.put("aliascolor", "color"); - this.propertyAliases.put("heal", "autoheal"); - this.propertyAliases.put("storm", "weather"); - this.propertyAliases.put("spawnmemory", "memory"); - this.propertyAliases.put("mode", "gamemode"); - this.propertyAliases.put("diff", "difficulty"); - - // Things I haven't converted yet. - this.getMobExceptions(); - List tempWorldBlacklist = worldSection.getStringList("worldblacklist"); - if (tempWorldBlacklist != null) - this.getWorldBlacklist().addAll(tempWorldBlacklist); - - // Enable and do the save. - this.canSave = true; - this.saveConfig(); + this.initPerms(); + } + /** + * Initializes permissions. + */ + private void initPerms() { 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(), @@ -216,79 +495,104 @@ public class MVWorld implements MultiverseWorld { } catch (IllegalArgumentException e) { this.plugin.log(Level.FINER, "Permissions nodes were already added for " + this.name); } - - // Sync all active settings. - this.setActualPVP(); - this.verifyScaleSetProperly(); - this.setActualKeepSpawnInMemory(); - this.setActualDifficulty(); - this.setActualGameMode(); - this.setActualSpawn(); - this.syncMobs(); } - /** - * Used by the active PVP-property to set the "actual" PVP-property. - * @return True if the property was successfully set. - */ - 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."); + private Location readSpawnFromWorld(World w) { + Location location = w.getSpawnLocation(); + // Set the worldspawn to our configspawn + BlockSafety bs = this.plugin.getBlockSafety(); + // Verify that location was safe + if (!bs.playerCanSpawnHereSafely(location)) { + if (!this.getAdjustSpawn()) { + this.plugin.log(Level.FINE, "Spawn location from world.dat file was unsafe!!"); + this.plugin.log(Level.FINE, "NOT adjusting spawn for '" + this.getAlias() + "' because you told me not to."); + this.plugin.log(Level.FINE, "To turn on spawn adjustment for this world simply type:"); + this.plugin.log(Level.FINE, "/mvm set adjustspawn true " + this.getAlias()); + return location; + } + // If it's not, find a better one. + SafeTTeleporter teleporter = this.plugin.getSafeTTeleporter(); + this.plugin.log(Level.WARNING, "Spawn location from world.dat file was unsafe. Adjusting..."); + this.plugin.log(Level.WARNING, "Original Location: " + plugin.getLocationManipulation().strCoordsRaw(location)); + Location newSpawn = teleporter.getSafeLocation(location, + 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(); + if (newSpawn != null) { + this.plugin.log(Level.INFO, String.format("New Spawn for '%s' is located at: %s", + this.getName(), plugin.getLocationManipulation().locationToString(newSpawn))); + return newSpawn; + } else { + // If it's a standard end world, let's check in a better place: + Location newerSpawn; + newerSpawn = bs.getTopBlock(new Location(w, 0, 0, 0)); + if (newerSpawn != null) { + this.plugin.log(Level.INFO, String.format("New Spawn for '%s' is located at: %s", + this.getName(), plugin.getLocationManipulation().locationToString(newerSpawn))); + return newerSpawn; + } else { + this.plugin.log(Level.SEVERE, "Safe spawn NOT found!!!"); + } + } } - return true; + return location; } /** - * Used by the active keepSpawnInMemory-property to set the "actual" property. - * @return True if the property was successfully set. + * {@inheritDoc} */ - public boolean setActualKeepSpawnInMemory() { - // Ensure the memory setting is correct - this.getCBWorld().setKeepSpawnInMemory(this.getKnownProperty("memory", Boolean.class).getValue()); - return true; + @Override + protected void setDefaults() { + this.hidden = false; + this.alias = new String(); + this.color = EnglishChatColor.WHITE; + this.scale = getDefaultScale(environment); + this.respawnWorld = new String(); + this.allowWeather = true; + this.spawning = new SpawnSettings(); + this.currency = -1; + this.price = 0D; + this.hunger = true; + this.autoHeal = true; + this.adjustSpawn = true; + this.portalForm = AllowedPortalType.ALL; + this.gameMode = GameMode.SURVIVAL; + this.spawnLocation = (world != null) ? new SpawnLocation(world.get().getSpawnLocation()) : null; + this.autoLoad = true; + this.bedRespawn = true; + this.worldBlacklist = new ArrayList(); } /** - * Used by the active difficulty-property to set the "actual" property. - * @return True if the property was successfully set. + * getAliases(). + * @return The alias-map. + * @see SerializationConfig */ - public boolean setActualDifficulty() { - this.getCBWorld().setDifficulty(this.getKnownProperty("difficulty", Difficulty.class).getValue()); - return true; + protected static Map getAliases() { + Map aliases = new HashMap(); + aliases.put("curr", "currency"); + aliases.put("scaling", "scale"); + aliases.put("aliascolor", "color"); + aliases.put("heal", "autoHeal"); + aliases.put("storm", "allowWeather"); + aliases.put("weather", "allowWeather"); + aliases.put("spawnmemory", "keepSpawnInMemory"); + aliases.put("memory", "keepSpawnInMemory"); + aliases.put("mode", "gameMode"); + aliases.put("diff", "difficulty"); + aliases.put("spawnlocation", "spawn"); + return aliases; } - /** - * 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) { + private static double getDefaultScale(Environment environment) { if (environment == Environment.NETHER) { return 8.0; // SUPPRESS CHECKSTYLE: MagicNumberCheck } return 1.0; } - private void addToUpperLists(Permission permission) { + private void addToUpperLists(Permission perm) { Permission all = this.plugin.getServer().getPluginManager().getPermission("multiverse.*"); Permission allWorlds = this.plugin.getServer().getPluginManager().getPermission("multiverse.access.*"); Permission allExemption = this.plugin.getServer().getPluginManager().getPermission("multiverse.exempt.*"); @@ -297,7 +601,7 @@ public class MVWorld implements MultiverseWorld { allWorlds = new Permission("multiverse.access.*"); this.plugin.getServer().getPluginManager().addPermission(allWorlds); } - allWorlds.getChildren().put(permission.getName(), true); + allWorlds.getChildren().put(perm.getName(), true); if (allExemption == null) { allExemption = new Permission("multiverse.exempt.*"); this.plugin.getServer().getPluginManager().addPermission(allExemption); @@ -314,283 +618,166 @@ public class MVWorld implements MultiverseWorld { this.plugin.getServer().getPluginManager().recalculatePermissionDefaults(allWorlds); } + /** + * {@inheritDoc} + */ + @Override + public World getCBWorld() { + return this.world.get(); + } + /** * {@inheritDoc} */ @Override public String getColoredWorldString() { - EnglishChatColor worldColor = this.getKnownProperty("color", EnglishChatColor.class).getValue(); - String alias = this.getKnownProperty("alias", String.class).getValue(); - if (worldColor == null) { - this.setKnownProperty("color", "WHITE", null); - return alias + ChatColor.WHITE; - } else if (worldColor.getColor() == null) { - return alias + ChatColor.WHITE; - } if (alias.length() == 0) { alias = this.getName(); } - return worldColor.getColor() + alias + ChatColor.WHITE; - } - - // TODO: Migrate this method. - private void getMobExceptions() { - List temp; - temp = this.worldSection.getStringList("animals.exceptions"); - // Add Animals to the exclusion list - if (temp != null) { - for (String s : temp) { - this.masterList.get("animals").add(s.toUpperCase()); - } - } - temp = this.worldSection.getStringList("monsters.exceptions"); - // Add Monsters to the exclusion list - if (temp != null) { - for (String s : temp) { - this.masterList.get("monsters").add(s.toUpperCase()); - } + if ((color == null) || (color.getColor() == null)) { + this.setPropertyValueUnchecked("color", EnglishChatColor.WHITE); } + return color.getColor() + alias + ChatColor.WHITE; } /** * {@inheritDoc} + * + * @deprecated This is deprecated. */ @Override - public World getCBWorld() { - return this.world; - } - - private void initLists() { - this.masterList = new HashMap>(); - this.masterList.put("worldblacklist", new ArrayList()); - this.masterList.put("animals", new ArrayList()); - this.masterList.put("monsters", new ArrayList()); + @Deprecated + public boolean clearList(String property) { + return clearVariable(property); } /** * {@inheritDoc} + * + * @deprecated This is deprecated. */ @Override + @Deprecated public boolean clearVariable(String property) { - if (this.masterList.keySet().contains(property)) { - this.masterList.get(property).clear(); - } else { + List list = getOldAndEvilList(property); + if (list == null) return false; - } - this.worldSection.set(property.toLowerCase(), new ArrayList()); - this.saveConfig(); + list.clear(); return true; } - /** - * {@inheritDoc} - */ - @Override - public boolean addToVariable(String property, String value) { - property = property.toLowerCase(); - if (this.masterList.keySet().contains(property)) { - - if (property.equals("animals") || property.equals("monsters")) { - this.masterList.get(property).add(value.toUpperCase()); - this.worldSection.set(property.toLowerCase() + ".exceptions", this.masterList.get(property)); - this.syncMobs(); - } else { - this.masterList.get(property).add(value); - this.worldSection.set(property.toLowerCase(), this.masterList.get(property)); - } - saveConfig(); - return true; - } - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean removeFromVariable(String property, String value) { - property = property.toLowerCase(); - if (this.masterList.keySet().contains(property)) { - - if (property.equals("animals") || property.equals("monsters")) { - this.masterList.get(property).remove(value.toUpperCase()); - this.worldSection.set(property + ".exceptions", this.masterList.get(property)); - this.syncMobs(); - } else { - this.masterList.get(property).remove(value); - this.worldSection.set(property, this.masterList.get(property)); - } - saveConfig(); - return true; - } - return false; - } - - /** - * 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()); - } else { - this.world.setSpawnFlags(this.world.getAllowMonsters(), true); - } - if (this.getMonsterList().isEmpty()) { - this.world.setSpawnFlags(this.getKnownProperty("monsters", Boolean.class).getValue(), this.world.getAllowAnimals()); - } else { - this.world.setSpawnFlags(true, this.world.getAllowAnimals()); - } - this.plugin.getMVWorldManager().getTheWorldPurger().purgeWorld(this); - } - - /** - * {@inheritDoc} - */ - @Override - public void setKeepSpawnInMemory(boolean value) { - this.getKnownProperty("memory", Boolean.class).setValue(value); - saveConfig(); - } - - /** - * {@inheritDoc} - */ - @Override - // TODO: Provide better feedback - public boolean setProperty(String name, String value, CommandSender sender) throws PropertyDoesNotExistException { - if (!this.isValidPropertyName(name)) { - throw new PropertyDoesNotExistException(name); - } - return this.setKnownProperty(name, value, sender) || this.setKnownProperty(this.propertyAliases.get(name), value, sender); - - } - - private boolean isValidPropertyName(String name) { - return this.propertyList.containsKey(name) || this.propertyAliases.containsKey(name); - } - - /** - * {@inheritDoc} - */ - @Override - public String getPropertyValue(String name) throws PropertyDoesNotExistException { - if (this.propertyList.containsKey(name)) { - return this.getKnownProperty(name, Object.class).toString(); - } - throw new PropertyDoesNotExistException(name); - } - /** * {@inheritDoc} * - * @deprecated Use {@link #getProperty(String, Class)} instead + * @deprecated This is deprecated. */ @Override @Deprecated - public MVConfigProperty getProperty(String property) throws PropertyDoesNotExistException { - return getProperty(property, Object.class); + public boolean addToVariable(String property, String value) { + List list = getOldAndEvilList(property); + if (list == null) + return false; + list.add(value); + return true; } /** * {@inheritDoc} + * + * @deprecated This is deprecated. */ @Override - public MVConfigProperty getProperty(String name, Class expected) throws PropertyDoesNotExistException { - MVConfigProperty p = this.getKnownProperty(name, expected); - if (p == null) { - throw new PropertyDoesNotExistException(name); - } - return p; + @Deprecated + public boolean removeFromVariable(String property, String value) { + List list = getOldAndEvilList(property); + if (list == null) + return false; + list.remove(value); + return true; } /** - * This method should only be used from inside this class when it is KNOWN that the property exists. - * - * @param name The known name of a property - * @param expected The Type of the expected value - * @return The property object. + * @deprecated This is deprecated. */ - @SuppressWarnings("unchecked") - private MVConfigProperty getKnownProperty(String name, Class expected) { - try { - if (this.propertyList.containsKey(name)) { - return (MVConfigProperty) this.propertyList.get(name); - } else if (this.propertyAliases.containsKey(name)) { - // If the property was defined in the alias table, make sure to grab the actual name - return (MVConfigProperty) this.propertyList.get(this.propertyAliases.get(name)); - } - } catch (ClassCastException e) { - return null; - } + @Deprecated + private List getOldAndEvilList(String property) { + if (property.equalsIgnoreCase("worldblacklist")) + return this.worldBlacklist; + else if (property.equalsIgnoreCase("animals")) + return this.spawning.getAnimalSettings().getExceptions(); + else if (property.equalsIgnoreCase("monsters")) + return this.spawning.getMonsterSettings().getExceptions(); return null; } /** - * This method should only be used from inside this class when it is KNOWN that the property exists. + * {@inheritDoc} * - * @param name The known name of a property. - * @param value The value that is trying to be set. - * @param sender The person sending the command, MAY BE NULL. - * @return True if the property was saved, false if not. + * @deprecated This is deprecated. */ - private boolean setKnownProperty(String name, String value, CommandSender sender) { - MVConfigProperty property; - if (this.propertyList.containsKey(name)) { - property = this.getKnownProperty(name, Object.class); - } else if (this.propertyAliases.containsKey(name)) { - return this.setKnownProperty(this.propertyAliases.get(name), value, sender); - } else { - return false; - } - // Only allow people to cancel events when they're not the initializations. - if (this.canSave) { - MVWorldPropertyChangeEvent propertyChangeEvent = new MVWorldPropertyChangeEvent(this, sender, name, value); - this.plugin.getServer().getPluginManager().callEvent(propertyChangeEvent); - if (propertyChangeEvent.isCancelled()) { - this.plugin.log(Level.FINE, "Someone else cancelled the WorldPropertyChanged Event!!!"); - return false; - } - value = propertyChangeEvent.getNewValue(); - } - if (property.parseValue(value)) { - if (property instanceof MVActiveConfigProperty) { - return this.setActiveProperty((MVActiveConfigProperty) property); - } - this.saveConfig(); - return true; - } - return false; + @Override + @Deprecated + public com.onarandombox.MultiverseCore.configuration.MVConfigProperty getProperty(String property, + Class expected) throws PropertyDoesNotExistException { + throw new UnsupportedOperationException("'MVConfigProperty getProperty(String,Class)' is no longer supported!"); } - private boolean setActiveProperty(MVActiveConfigProperty property) { + /** + * {@inheritDoc} + * + * @deprecated This is deprecated. + */ + @Override + @Deprecated + public boolean setProperty(String name, String value, CommandSender sender) throws PropertyDoesNotExistException { + return this.setPropertyValue(name, value); + } + + /** + * {@inheritDoc} + */ + @Override + public String getPropertyValue(String property) throws PropertyDoesNotExistException { try { - if (property.getMethod() == null) { - // This property did not have a method. - this.saveConfig(); - return true; - } - Method method = this.getClass().getMethod(property.getMethod()); - Object returnVal = method.invoke(this); - if (returnVal instanceof Boolean) { - if ((Boolean) returnVal) { - this.saveConfig(); - } - return (Boolean) returnVal; - } else { - this.saveConfig(); - return true; - } - } catch (Exception e) { - // TODO: I don't care about 3 catches, - // TODO: I hate pokemon errors :/ - FernFerret - e.printStackTrace(); - return false; + return this.getProperty(property, true); + } catch (NoSuchPropertyException e) { + throw new PropertyDoesNotExistException(property, e); } } + /** + * {@inheritDoc} + */ + @Override + public boolean setPropertyValue(String property, String value) throws PropertyDoesNotExistException { + try { + return this.setProperty(property, value, true); + } catch (NoSuchPropertyException e) { + throw new PropertyDoesNotExistException(property, e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public String getPropertyHelp(String property) throws PropertyDoesNotExistException { + try { + return this.getPropertyDescription(property, true); + } catch (NoSuchPropertyException e) { + throw new PropertyDoesNotExistException(property, e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public WorldType getWorldType() { + // This variable is not settable in-game, therefore does not get a property. + return world.get().getWorldType(); + } + /** * {@inheritDoc} */ @@ -622,7 +809,7 @@ public class MVWorld implements MultiverseWorld { * {@inheritDoc} */ @Override - public void setSeed(Long seed) { + public void setSeed(long seed) { // This variable is not settable in-game, therefore does not get a property. this.seed = seed; } @@ -649,12 +836,10 @@ public class MVWorld implements MultiverseWorld { */ @Override public String getAlias() { - String alias = this.getKnownProperty("alias", String.class).getValue(); - if (alias == null || alias.length() == 0) { + if (this.alias == null || this.alias.length() == 0) { return this.name; } - return alias; - + return this.alias; } /** @@ -662,7 +847,7 @@ public class MVWorld implements MultiverseWorld { */ @Override public void setAlias(String alias) { - this.setKnownProperty("alias", alias, null); + this.setPropertyValueUnchecked("alias", alias); } /** @@ -670,7 +855,7 @@ public class MVWorld implements MultiverseWorld { */ @Override public boolean canAnimalsSpawn() { - return this.getKnownProperty("animals", Boolean.class).getValue(); + return this.spawning.getAnimalSettings().doSpawn(); } /** @@ -678,7 +863,7 @@ public class MVWorld implements MultiverseWorld { */ @Override public void setAllowAnimalSpawn(boolean animals) { - this.setKnownProperty("animals", animals + "", null); + this.setPropertyValueUnchecked("spawning.animals.spawn", animals); } /** @@ -686,7 +871,8 @@ public class MVWorld implements MultiverseWorld { */ @Override public List getAnimalList() { - return this.masterList.get("animals"); + // These don't fire events at the moment. Should they? + return this.spawning.getAnimalSettings().getExceptions(); } /** @@ -694,7 +880,7 @@ public class MVWorld implements MultiverseWorld { */ @Override public boolean canMonstersSpawn() { - return this.getKnownProperty("monsters", Boolean.class).getValue(); + return this.spawning.getMonsterSettings().doSpawn(); } /** @@ -702,7 +888,7 @@ public class MVWorld implements MultiverseWorld { */ @Override public void setAllowMonsterSpawn(boolean monsters) { - this.setKnownProperty("monsters", monsters + "", null); + this.setPropertyValueUnchecked("spawning.monsters.spawn", monsters); } /** @@ -710,7 +896,8 @@ public class MVWorld implements MultiverseWorld { */ @Override public List getMonsterList() { - return this.masterList.get("monsters"); + // These don't fire events at the moment. Should they? + return this.spawning.getMonsterSettings().getExceptions(); } /** @@ -718,7 +905,7 @@ public class MVWorld implements MultiverseWorld { */ @Override public boolean isPVPEnabled() { - return this.getKnownProperty("pvp", Boolean.class).getValue(); + return this.pvp.get(); } /** @@ -726,7 +913,7 @@ public class MVWorld implements MultiverseWorld { */ @Override public void setPVPMode(boolean pvp) { - this.setKnownProperty("pvp", pvp + "", null); + this.setPropertyValueUnchecked("pvp", pvp); } /** @@ -734,7 +921,7 @@ public class MVWorld implements MultiverseWorld { */ @Override public boolean isHidden() { - return this.getKnownProperty("hidden", Boolean.class).getValue(); + return this.hidden; } /** @@ -742,7 +929,7 @@ public class MVWorld implements MultiverseWorld { */ @Override public void setHidden(boolean hidden) { - this.setKnownProperty("hidden", hidden + "", null); + this.setPropertyValueUnchecked("hidden", hidden); } /** @@ -750,7 +937,7 @@ public class MVWorld implements MultiverseWorld { */ @Override public List getWorldBlacklist() { - return this.masterList.get("worldblacklist"); + return this.worldBlacklist; } /** @@ -758,7 +945,7 @@ public class MVWorld implements MultiverseWorld { */ @Override public double getScaling() { - return this.getKnownProperty("scale", Double.class).getValue(); + return this.scale; } /** @@ -766,7 +953,7 @@ public class MVWorld implements MultiverseWorld { */ @Override public boolean setScaling(double scaling) { - return this.setKnownProperty("scale", scaling + "", null); + return this.setPropertyValueUnchecked("scale", scaling); } /** @@ -774,13 +961,16 @@ public class MVWorld implements MultiverseWorld { */ @Override public boolean setColor(String aliasColor) { - return this.setKnownProperty("color", aliasColor, null); + return this.setPropertyUnchecked("color", aliasColor); } /** * {@inheritDoc} + * + * @deprecated This is deprecated. */ - @Override // TODO This method should be static. (Maybe EnglishChatColor would be a good place?) + @Override + @Deprecated public boolean isValidAliasColor(String aliasColor) { return (EnglishChatColor.fromString(aliasColor) != null); } @@ -790,22 +980,7 @@ public class MVWorld implements MultiverseWorld { */ @Override public ChatColor getColor() { - return this.getKnownProperty("color", EnglishChatColor.class).getValue().getColor(); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean clearList(String property) { - if (this.masterList.containsKey(property)) { - this.masterList.get(property).clear(); - this.worldSection.set(property.toLowerCase(), this.masterList.get(property)); - this.syncMobs(); - saveConfig(); - return true; - } - return false; + return this.color.getColor(); } /** @@ -824,7 +999,7 @@ public class MVWorld implements MultiverseWorld { */ @Override public World getRespawnToWorld() { - return (this.plugin.getServer().getWorld(this.getKnownProperty("respawn", String.class).getValue())); + return this.plugin.getServer().getWorld(respawnWorld); } /** @@ -833,7 +1008,7 @@ public class MVWorld implements MultiverseWorld { @Override public boolean setRespawnToWorld(String respawnToWorld) { if (!this.plugin.getMVWorldManager().isMVWorld(respawnToWorld)) return false; - return this.setKnownProperty("respawn", respawnToWorld, null); + return this.setPropertyValueUnchecked("respawnWorld", respawnToWorld); } /** @@ -849,7 +1024,7 @@ public class MVWorld implements MultiverseWorld { */ @Override public int getCurrency() { - return this.getKnownProperty("curr", Integer.class).getValue(); + return this.currency; } /** @@ -857,7 +1032,7 @@ public class MVWorld implements MultiverseWorld { */ @Override public void setCurrency(int currency) { - this.setKnownProperty("curr", currency + "", null); + this.setPropertyValueUnchecked("currency", currency); } /** @@ -865,7 +1040,7 @@ public class MVWorld implements MultiverseWorld { */ @Override public double getPrice() { - return this.getKnownProperty("price", Double.class).getValue(); + return this.price; } /** @@ -873,7 +1048,7 @@ public class MVWorld implements MultiverseWorld { */ @Override public void setPrice(double price) { - this.setKnownProperty("price", price + "", null); + this.setPropertyValueUnchecked("price", price); } /** @@ -884,40 +1059,17 @@ public class MVWorld implements MultiverseWorld { return this.exempt; } - private void saveConfig() { - if (this.canSave) { - try { - 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."); - } - } - } - /** * {@inheritDoc} */ @Override - public boolean setGameMode(String gameMode) { - return this.setKnownProperty("mode", gameMode, null); + public boolean setGameMode(String mode) { + return this.setPropertyUnchecked("gameMode", mode); } - /** - * 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; + @Override + public boolean setGameMode(GameMode mode) { + return this.setPropertyValueUnchecked("gameMode", mode); } /** @@ -925,7 +1077,7 @@ public class MVWorld implements MultiverseWorld { */ @Override public GameMode getGameMode() { - return this.getKnownProperty("mode", GameMode.class).getValue(); + return this.gameMode; } /** @@ -933,20 +1085,7 @@ public class MVWorld implements MultiverseWorld { */ @Override public void setEnableWeather(boolean weather) { - 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; + this.setPropertyValueUnchecked("allowWeather", weather); } /** @@ -954,7 +1093,7 @@ public class MVWorld implements MultiverseWorld { */ @Override public boolean isWeatherEnabled() { - return this.getKnownProperty("weather", Boolean.class).getValue(); + return this.allowWeather; } /** @@ -962,15 +1101,15 @@ public class MVWorld implements MultiverseWorld { */ @Override public boolean isKeepingSpawnInMemory() { - return this.getKnownProperty("memory", Boolean.class).getValue(); + return this.keepSpawnInMemory.get(); } /** * {@inheritDoc} */ @Override - public void setHunger(boolean hunger) { - this.setKnownProperty("hunger", hunger + "", null); + public void setKeepSpawnInMemory(boolean value) { + this.setPropertyValueUnchecked("keepSpawnInMemory", value); } /** @@ -978,69 +1117,15 @@ public class MVWorld implements MultiverseWorld { */ @Override public boolean getHunger() { - return this.getKnownProperty("hunger", Boolean.class).getValue(); + return this.hunger; } /** * {@inheritDoc} */ @Override - public void setSpawnLocation(Location l) { - this.getCBWorld().setSpawnLocation(l.getBlockX(), l.getBlockY(), l.getBlockZ()); - this.getKnownProperty("spawn", Location.class).setValue(l); - 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(); - - // Set the worldspawn to our configspawn - w.setSpawnLocation(configLocation.getBlockX(), configLocation.getBlockY(), configLocation.getBlockZ()); - SafeTTeleporter teleporter = this.plugin.getSafeTTeleporter(); - BlockSafety bs = this.plugin.getBlockSafety(); - // Verify that location was safe - if (!bs.playerCanSpawnHereSafely(configLocation)) { - if (!this.getAdjustSpawn()) { - this.plugin.log(Level.FINE, "Spawn location from world.dat file was unsafe!!"); - this.plugin.log(Level.FINE, "NOT adjusting spawn for '" + this.getAlias() + "' because you told me not to."); - this.plugin.log(Level.FINE, "To turn on spawn adjustment for this world simply type:"); - this.plugin.log(Level.FINE, "/mvm set adjustspawn true " + this.getAlias()); - return configLocation; - } - // 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: " + plugin.getLocationManipulation().strCoordsRaw(spawnLocation)); - 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(); - if (newSpawn != null) { - this.setSpawnLocation(newSpawn); - configLocation = this.getSpawnLocation(); - this.plugin.log(Level.INFO, "New Spawn for '" + this.getName() - + "' is Located at: " + plugin.getLocationManipulation().locationToString(configLocation)); - } else { - // If it's a standard end world, let's check in a better place: - Location newerSpawn; - newerSpawn = bs.getTopBlock(new Location(w, 0, 0, 0)); - if (newerSpawn != null) { - this.setSpawnLocation(newerSpawn); - configLocation = this.getSpawnLocation(); - this.plugin.log(Level.INFO, "New Spawn for '" + this.getName() - + "' is Located at: " + plugin.getLocationManipulation().locationToString(configLocation)); - } else { - this.plugin.log(Level.SEVERE, "New safe spawn NOT found!!!"); - } - - - } - } - return configLocation; + public void setHunger(boolean hunger) { + this.setPropertyValueUnchecked("hunger", hunger); } /** @@ -1048,7 +1133,15 @@ public class MVWorld implements MultiverseWorld { */ @Override public Location getSpawnLocation() { - return this.getKnownProperty("spawn", Location.class).getValue(); + return this.spawn.get(); + } + + /** + * {@inheritDoc} + */ + @Override + public void setSpawnLocation(Location l) { + this.setPropertyValueUnchecked("spawn", l); } /** @@ -1056,20 +1149,23 @@ public class MVWorld implements MultiverseWorld { */ @Override public Difficulty getDifficulty() { - return this.getCBWorld().getDifficulty(); + return this.difficulty.get(); } /** * {@inheritDoc} + * + * @deprecated This is deprecated. */ @Override + @Deprecated public boolean setDifficulty(String difficulty) { - if (this.setKnownProperty("diff", difficulty, null)) { - // Set the difficulty - this.getCBWorld().setDifficulty(this.getKnownProperty("diff", Difficulty.class).getValue()); - return true; - } - return false; + return this.setPropertyUnchecked("difficulty", difficulty); + } + + @Override + public boolean setDifficulty(Difficulty difficulty) { + return this.setPropertyValueUnchecked("difficulty", difficulty); } /** @@ -1077,7 +1173,7 @@ public class MVWorld implements MultiverseWorld { */ @Override public boolean getAutoHeal() { - return this.getKnownProperty("autoheal", Boolean.class).getValue(); + return this.autoHeal; } /** @@ -1085,7 +1181,7 @@ public class MVWorld implements MultiverseWorld { */ @Override public void setAutoHeal(boolean heal) { - this.setKnownProperty("autoheal", heal + "", null); + this.setPropertyValueUnchecked("autoHeal", heal); } /** @@ -1093,7 +1189,7 @@ public class MVWorld implements MultiverseWorld { */ @Override public void setAdjustSpawn(boolean adjust) { - this.setKnownProperty("adjustspawn", adjust + "", null); + this.setPropertyValueUnchecked("adjustSpawn", adjust); } /** @@ -1101,15 +1197,15 @@ public class MVWorld implements MultiverseWorld { */ @Override public boolean getAdjustSpawn() { - return this.getKnownProperty("adjustspawn", Boolean.class).getValue(); + return this.adjustSpawn; } /** * {@inheritDoc} */ @Override - public void setAutoLoad(boolean autoLoad) { - this.setKnownProperty("autoload", autoLoad + "", null); + public void setAutoLoad(boolean load) { + this.setPropertyValueUnchecked("autoLoad", load); } /** @@ -1117,7 +1213,7 @@ public class MVWorld implements MultiverseWorld { */ @Override public boolean getAutoLoad() { - return this.getKnownProperty("autoload", Boolean.class).getValue(); + return this.autoLoad; } /** @@ -1125,7 +1221,7 @@ public class MVWorld implements MultiverseWorld { */ @Override public void setBedRespawn(boolean respawn) { - this.setKnownProperty("bedrespawn", respawn + "", null); + this.setPropertyValueUnchecked("bedRespawn", respawn); } /** @@ -1133,7 +1229,7 @@ public class MVWorld implements MultiverseWorld { */ @Override public boolean getBedRespawn() { - return this.getKnownProperty("bedrespawn", Boolean.class).getValue(); + return this.bedRespawn; } /** @@ -1141,13 +1237,14 @@ public class MVWorld implements MultiverseWorld { */ @Override public String getAllPropertyNames() { - ChatColor color = ChatColor.AQUA; - String result = ""; - for (String propertyNames : this.propertyList.keySet()) { - result += color + propertyNames + " "; - color = (color == ChatColor.AQUA) ? ChatColor.GOLD : ChatColor.AQUA; + ChatColor myColor = ChatColor.AQUA; + StringBuilder result = new StringBuilder(); + Map serialized = this.serialize(); + for (String key : serialized.keySet()) { + result.append(myColor).append(key).append(' '); + myColor = (myColor == ChatColor.AQUA) ? ChatColor.GOLD : ChatColor.AQUA; } - return result; + return result.toString(); } /** @@ -1155,32 +1252,15 @@ public class MVWorld implements MultiverseWorld { */ @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); + return this.getPropertyUnchecked("time"); } /** * {@inheritDoc} */ @Override - public WorldType getWorldType() { - return this.type; - } - - /** - * {@inheritDoc} - */ - @Override - public void allowPortalMaking(AllowedPortalType type) { - this.setKnownProperty("portalform", type.toString(), null); + public boolean setTime(String timeAsString) { + return this.setPropertyUnchecked("time", timeAsString); } /** @@ -1188,72 +1268,16 @@ public class MVWorld implements MultiverseWorld { */ @Override public AllowedPortalType getAllowedPortals() { - return this.getKnownProperty("portalform", AllowedPortalType.class).getValue(); - } - - /** - * 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()); + return portalForm; } /** * {@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; + public void allowPortalMaking(AllowedPortalType portalType) { + this.setPropertyValueUnchecked("portalForm", portalType); } - // END CHECKSTYLE-SUPPRESSION: MagicNumberCheck @Override public String toString() { diff --git a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java index 2ad337c3..b3d58a46 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCore.java @@ -171,6 +171,8 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core { public void onLoad() { // Register our config SerializationConfig.registerAll(MultiverseCoreConfiguration.class); + // Register our world + SerializationConfig.registerAll(MVWorld.class); // Create our DataFolder getDataFolder().mkdirs(); // Setup our Debug Log @@ -422,6 +424,7 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core { */ @Override public void onDisable() { + this.saveMVConfigs(); debugLog.close(); this.banker = null; this.bank = null; diff --git a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCoreConfiguration.java b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCoreConfiguration.java index 25e95cfc..0595609d 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MultiverseCoreConfiguration.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MultiverseCoreConfiguration.java @@ -4,6 +4,7 @@ import java.util.Map; import com.onarandombox.MultiverseCore.api.MultiverseCoreConfig; +import me.main__.util.SerializationConfig.NoSuchPropertyException; import me.main__.util.SerializationConfig.Property; import me.main__.util.SerializationConfig.SerializationConfig; @@ -80,6 +81,18 @@ public class MultiverseCoreConfiguration extends SerializationConfig implements // END CHECKSTYLE-SUPPRESSION: MagicNumberCheck } + /** + * {@inheritDoc} + */ + @Override + public boolean setConfigProperty(String property, String value) { + try { + return this.setProperty(property, value, true); + } catch (NoSuchPropertyException e) { + return false; + } + } + // And here we go: /** diff --git a/src/main/java/com/onarandombox/MultiverseCore/api/MultiverseCoreConfig.java b/src/main/java/com/onarandombox/MultiverseCore/api/MultiverseCoreConfig.java index 25f6fad4..a694f0b6 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/api/MultiverseCoreConfig.java +++ b/src/main/java/com/onarandombox/MultiverseCore/api/MultiverseCoreConfig.java @@ -12,7 +12,7 @@ public interface MultiverseCoreConfig extends ConfigurationSerializable { * @param value The value. * @return True on success, false if the operation failed. */ - boolean setProperty(String property, String value); + boolean setConfigProperty(String property, String value); /** * Sets portalCooldown. diff --git a/src/main/java/com/onarandombox/MultiverseCore/api/MultiverseWorld.java b/src/main/java/com/onarandombox/MultiverseCore/api/MultiverseWorld.java index 5bd1eb11..cefbb78a 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/api/MultiverseWorld.java +++ b/src/main/java/com/onarandombox/MultiverseCore/api/MultiverseWorld.java @@ -7,7 +7,6 @@ package com.onarandombox.MultiverseCore.api; -import com.onarandombox.MultiverseCore.configuration.MVConfigProperty; import com.onarandombox.MultiverseCore.enums.AllowedPortalType; import com.onarandombox.MultiverseCore.exceptions.PropertyDoesNotExistException; @@ -26,7 +25,6 @@ import java.util.List; * The API for a Multiverse Handled World. */ public interface MultiverseWorld { - /** * Returns the Bukkit world object that this world describes. * @@ -35,79 +33,24 @@ public interface MultiverseWorld { World getCBWorld(); /** - * Adds the property to the given value. - * It will throw a PropertyDoesNotExistException if the property is not found. + * Gets the name of this world. The name cannot be changed. + *

+ * Note for plugin developers: Usually {@link #getAlias()} + * is what you want to use instead of this method. * - * @param property The name of a world property to set. - * @param value A value in string representation, it will be parsed to the correct type. - * @param sender The sender who wants this value to be set. - * @return True if the value was set, false if not. - * @throws PropertyDoesNotExistException Thrown if the property was not found in the world. + * @return The name of the world as a String. */ - boolean setProperty(String property, String value, CommandSender sender) throws PropertyDoesNotExistException; + String getName(); /** - * Gets the actual MVConfigProperty from this world. - * It will throw a PropertyDoesNotExistException if the property is not found. + * Gets the type of this world. As of 1.1-R1 this will be: + * FLAT or NORMAL + *

+ * This is *not* the generator. * - * @param property The name of a world property to get. - * @return A valid MVWorldProperty. - * @throws PropertyDoesNotExistException Thrown if the property was not found in the world. - * @deprecated Use {@link #getProperty(String, Class)} instead + * @return The Type of this world. */ - @Deprecated - MVConfigProperty getProperty(String property) throws PropertyDoesNotExistException; - - /** - * Gets the string representation of a property. - * It will throw a PropertyDoesNotExistException if the property is not found. - * - * @param property The name of a world property to get. - * @return A valid MVWorldProperty. - * @throws PropertyDoesNotExistException Thrown if the property was not found in the world. - */ - String getPropertyValue(String property) throws PropertyDoesNotExistException; - - /** - * Gets the actual MVConfigProperty from this world. - * It will throw a PropertyDoesNotExistException if the property is not found. - * - * @param property The name of a world property to get. - * @param expected The type of the expected property. Use Object.class if this doesn't matter for you. - * @param The type of the expected property. - * - * @return A valid MVWorldProperty. - * - * @throws PropertyDoesNotExistException Thrown if the property was not found in the world. - */ - MVConfigProperty getProperty(String property, Class expected) throws PropertyDoesNotExistException; - - /** - * Removes all values from the given property. The property must be a {@link com.onarandombox.MultiverseCore.enums.AddProperties}. - * - * @param property The name of a {@link com.onarandombox.MultiverseCore.enums.AddProperties} to clear. - * @return True if it was cleared, false if not. - */ - boolean clearVariable(String property); - - /** - * Adds a value to the given property. The property must be a {@link com.onarandombox.MultiverseCore.enums.AddProperties}. - * - * @param property The name of a {@link com.onarandombox.MultiverseCore.enums.AddProperties} to add a value to. - * @param value A value in string representation, it will be parsed to the correct type. - * @return True if the value was added, false if not. - */ - boolean addToVariable(String property, String value); - - /** - * Removes a value from the given property. The property must be a {@link com.onarandombox.MultiverseCore.enums.AddProperties}. - * - * @param property The name of a {@link com.onarandombox.MultiverseCore.enums.AddProperties} to remove a value - * from. - * @param value A value in string representation, it will be parsed to the correct type. - * @return True if the value was removed, false if not. - */ - boolean removeFromVariable(String property, String value); + WorldType getWorldType(); /** * Gets the environment of this world. @@ -125,6 +68,37 @@ public interface MultiverseWorld { */ void setEnvironment(World.Environment environment); + /** + * Gets the difficulty of this world. + * + * @return The difficulty of this world. + */ + Difficulty getDifficulty(); + + /** + * Sets the difficulty of this world and returns true if success. + * Valid string values are either an integer of difficulty(0-3) or + * the name that resides in the Bukkit enum, ex. {@code PEACEFUL} + * + * @param difficulty The difficulty to set the world to as a string. + * @return True if success, false if the provided string + * could not be translated to a difficulty. + * @deprecated Use {@link #setDifficulty(Difficulty)} or, if you have to + * pass a string, use {@link #setPropertyValue(String, String)} instead. + */ + @Deprecated + boolean setDifficulty(String difficulty); + + /** + * Sets the difficulty of this world and returns {@code true} on success. + * Valid string values are either an integer of difficulty(0-3) or + * the name that resides in the Bukkit enum, ex. PEACEFUL + * + * @param difficulty The new difficulty. + * @return True if success, false if the operation failed... for whatever reason. + */ + boolean setDifficulty(Difficulty difficulty); + /** * Gets the world seed of this world. * @@ -137,15 +111,111 @@ public interface MultiverseWorld { * * @param seed A Long that is the seed. */ - void setSeed(Long seed); + void setSeed(long seed); /** - * Gets the name of this world. This cannot be changed. - * - * @return The name of the world as a String. + * Gets the help-message for a property. + * @param property The name of the property. + * @return The help-message. + * @throws PropertyDoesNotExistException Thrown if the property was not found. */ - String getName(); + String getPropertyHelp(String property) throws PropertyDoesNotExistException; + /** + * Gets a property as {@link String}. + * + * @param property The name of a world property to get. + * @return The string-representation of that property. + * @throws PropertyDoesNotExistException Thrown if the property was not found in the world. + */ + String getPropertyValue(String property) throws PropertyDoesNotExistException; + + /** + * Sets a property to a given value. + * + * @param property The name of a world property to set. + * @param value A value in string representation, it will be parsed to the correct type. + * @return True if the value was set, false if not. + * @throws PropertyDoesNotExistException Thrown if the property was not found in the world. + */ + boolean setPropertyValue(String property, String value) throws PropertyDoesNotExistException; + + /** + * Gets the actual MVConfigProperty from this world. + * It will throw a PropertyDoesNotExistException if the property is not found. + * + * @param property The name of a world property to get. + * @param expected The type of the expected property. Use Object.class if this doesn't matter for you. + * @param The type of the expected property. + * + * @return A valid MVWorldProperty. + * + * @throws PropertyDoesNotExistException Thrown if the property was not found in the world. + * @deprecated We don't use {@link com.onarandombox.MultiverseCore.configuration.MVConfigProperty} any longer! + */ + @Deprecated + com.onarandombox.MultiverseCore.configuration.MVConfigProperty getProperty(String property, Class expected) throws PropertyDoesNotExistException; + + // old config + /** + * Adds the property to the given value. + * It will throw a PropertyDoesNotExistException if the property is not found. + * + * @param property The name of a world property to set. + * @param value A value in string representation, it will be parsed to the correct type. + * @param sender The sender who wants this value to be set. + * @return True if the value was set, false if not. + * @throws PropertyDoesNotExistException Thrown if the property was not found in the world. + * @deprecated Use {@link #setPropertyValue(String, String)} instead. + */ + @Deprecated + boolean setProperty(String property, String value, CommandSender sender) throws PropertyDoesNotExistException; + + /** + * Adds a value to the given property. The property must be a {@link com.onarandombox.MultiverseCore.enums.AddProperties}. + * + * @param property The name of a {@link com.onarandombox.MultiverseCore.enums.AddProperties} to add a value to. + * @param value A value in string representation, it will be parsed to the correct type. + * @return True if the value was added, false if not. + * @deprecated We changed the entire world-config-system. This is not compatible any more. + */ + @Deprecated + boolean addToVariable(String property, String value); + + /** + * Removes a value from the given property. The property must be a {@link com.onarandombox.MultiverseCore.enums.AddProperties}. + * + * @param property The name of a {@link com.onarandombox.MultiverseCore.enums.AddProperties} to remove a value + * from. + * @param value A value in string representation, it will be parsed to the correct type. + * @return True if the value was removed, false if not. + * @deprecated We changed the entire world-config-system. This is not compatible any more. + */ + @Deprecated + boolean removeFromVariable(String property, String value); + + /** + * Removes all values from the given property. The property must be a {@link com.onarandombox.MultiverseCore.enums.AddProperties}. + * + * @param property The name of a {@link com.onarandombox.MultiverseCore.enums.AddProperties} to clear. + * @return True if it was cleared, false if not. + * @deprecated We changed the entire world-config-system. This is not compatible any more. + */ + @Deprecated + boolean clearVariable(String property); + + /** + * Clears a list property (sets it to []). + * + * @param property The property to clear. + * @return True if success, false if fail. + * @deprecated We changed the entire world-config-system. This is not compatible any more. + */ + @Deprecated + boolean clearList(String property); + // end of old config stuff + + // permission stuff /** * Gets the lowercased name of the world. This method is required, since the permissables * lowercase all permissions when recalculating. @@ -158,6 +228,21 @@ public interface MultiverseWorld { */ String getPermissibleName(); + /** + * Gets the permission required to enter this world. + * + * @return The permission required to be exempt from charges to/from this world. + */ + Permission getAccessPermission(); + + /** + * Gets the permission required to be exempt when entering. + * + * @return The permission required to be exempt when entering. + */ + Permission getExemptPermission(); + // end of permission stuff + /** * Gets the alias of this world. *

@@ -174,6 +259,13 @@ public interface MultiverseWorld { */ void setAlias(String alias); + /** + * Gets the color that this world's name/alias will display as. + * + * @return The color of this world. + */ + ChatColor getColor(); + /** * Sets the color that this world's name/alias will display as. * @@ -182,19 +274,15 @@ public interface MultiverseWorld { */ boolean setColor(String color); - /** - * Gets the color that this world's name/alias will display as. - * - * @return The color of this world. - */ - ChatColor getColor(); - /** * Tells you if someone entered a valid color. * * @param color A string that may translate to a color. * @return True if it is a color, false if not. + * + * @deprecated This has been moved: {@link com.onarandombox.MultiverseCore.enums.EnglishChatColor#isValidAliasColor(String)} */ + @Deprecated boolean isValidAliasColor(String color); /** @@ -204,6 +292,7 @@ public interface MultiverseWorld { */ String getColoredWorldString(); + // animals&monster stuff /** * Gets whether or not animals are allowed to spawn in this world. * @@ -211,6 +300,22 @@ public interface MultiverseWorld { */ boolean canAnimalsSpawn(); + /** + * Sets whether or not animals can spawn. + * If there are values in {@link #getAnimalList()} and this is false, + * those animals become the exceptions, and will spawn + * + * @param allowAnimalSpawn True to allow spawning of monsters, false to prevent. + */ + void setAllowAnimalSpawn(boolean allowAnimalSpawn); + + /** + * Returns a list of animals. This list always negates the {@link #canAnimalsSpawn()} result. + * + * @return A list of animals that will spawn if {@link #canAnimalsSpawn()} is false. + */ + List getAnimalList(); + /** * Gets whether or not monsters are allowed to spawn in this world. * @@ -219,7 +324,31 @@ public interface MultiverseWorld { boolean canMonstersSpawn(); /** - * Turn pvp on or off. This setting is used to set the world's PVP mode, and thus relies on fakePVP + * Sets whether or not monsters can spawn. + * If there are values in {@link #getMonsterList()} and this is false, + * those monsters become the exceptions, and will spawn + * + * @param allowMonsterSpawn True to allow spawning of monsters, false to prevent. + */ + void setAllowMonsterSpawn(boolean allowMonsterSpawn); + + /** + * Returns a list of monsters. This list always negates the {@link #canMonstersSpawn()} result. + * + * @return A list of monsters that will spawn if {@link #canMonstersSpawn()} is false. + */ + List getMonsterList(); + // end of animal&monster stuff + + /** + * Gets whether or not PVP is enabled in this world in some form (fake or not). + * + * @return True if players can take damage from other players. + */ + boolean isPVPEnabled(); + + /** + * Turn pvp on or off. This setting is used to set the world's PVP mode. * * @param pvpMode True to enable PVP damage, false to disable it. */ @@ -234,13 +363,6 @@ public interface MultiverseWorld { @Deprecated boolean getFakePVP(); - /** - * Gets whether or not PVP is enabled in this world in some form (fake or not). - * - * @return True if players can take damage from other players. - */ - boolean isPVPEnabled(); - /** * Gets whether or not this world will display in chat, mvw and mvl regardless if a user has the * access permissions to go to this world. @@ -257,6 +379,13 @@ public interface MultiverseWorld { */ void setHidden(boolean hidden); + /** + * Gets whether weather is enabled in this world. + * + * @return True if weather events will occur, false if not. + */ + boolean isWeatherEnabled(); + /** * Sets whether or not there will be weather events in a given world. * If set to false, Multiverse will disable the weather in the world immediately. @@ -266,11 +395,11 @@ public interface MultiverseWorld { void setEnableWeather(boolean enableWeather); /** - * Gets whether weather is enabled in this world. + * Gets whether or not CraftBukkit is keeping the chunks for this world in memory. * - * @return True if weather events will occur, false if not. + * @return True if CraftBukkit is keeping spawn chunks in memory. */ - boolean isWeatherEnabled(); + boolean isKeepingSpawnInMemory(); /** * If true, tells Craftbukkit to keep a worlds spawn chunks loaded in memory (default: true) @@ -282,29 +411,11 @@ public interface MultiverseWorld { void setKeepSpawnInMemory(boolean keepSpawnInMemory); /** - * Gets whether or not CraftBukkit is keeping the chunks for this world in memory. + * Gets the spawn location of this world. * - * @return True if CraftBukkit is keeping spawn chunks in memory. + * @return The spawn location of this world. */ - boolean isKeepingSpawnInMemory(); - - /** - * Sets the difficulty of this world and returns true if success. - * Valid string values are either an integer of difficulty(0-3) or - * the name that resides in the Bukkit enum, ex. PEACEFUL - * - * @param difficulty The difficulty to set the world to as a string. - * @return True if success, false if the provided string - * could not be translated to a difficulty. - */ - boolean setDifficulty(String difficulty); - - /** - * Gets the difficulty of this world. - * - * @return The difficulty of this world. - */ - Difficulty getDifficulty(); + Location getSpawnLocation(); /** * Sets the spawn location for a world. @@ -314,11 +425,11 @@ public interface MultiverseWorld { void setSpawnLocation(Location spawnLocation); /** - * Gets the spawn location of this world. + * Gets whether or not the hunger level of players will go down in a world. * - * @return The spawn location of this world. + * @return True if it will go down, false if it will remain steady. */ - Location getSpawnLocation(); + boolean getHunger(); /** * Sets whether or not the hunger level of players will go down in a world. @@ -328,22 +439,6 @@ public interface MultiverseWorld { */ void setHunger(boolean hungerEnabled); - /** - * Gets whether or not the hunger level of players will go down in a world. - * - * @return True if it will go down, false if it will remain steady. - */ - boolean getHunger(); - - /** - * Sets the game mode of this world. - * - * @param gameMode A valid game mode string (either - * an int ex. 0 or a string ex. creative). - * @return True if the game mode was successfully changed, false if not. - */ - boolean setGameMode(String gameMode); - /** * Gets the GameMode of this world. * @@ -352,18 +447,31 @@ public interface MultiverseWorld { GameMode getGameMode(); /** - * Gets the permission required to enter this world. + * Sets the game mode of this world. * - * @return The permission required to be exempt from charges to/from this world. + * @param gameMode A valid game mode string (either + * an int ex. 0 or a string ex. creative). + * @return True if the game mode was successfully changed, false if not. + * @deprecated Use {@link #setGameMode(GameMode)} instead. If you have to + * pass a string, use {@link #setPropertyValue(String, String)}. */ - Permission getAccessPermission(); + @Deprecated + boolean setGameMode(String gameMode); /** - * Gets the permission required to be exempt when entering. + * Sets the game mode of this world. * - * @return The permission required to be exempt when entering. + * @param gameMode The new {@link GameMode}. + * @return True if the game mode was successfully changed, false if not. */ - Permission getExemptPermission(); + boolean setGameMode(GameMode gameMode); + + /** + * Gets the amount of currency it requires to enter this world. + * + * @return The amount it costs to enter this world. + */ + double getPrice(); /** * Sets the price for entry to this world. @@ -375,11 +483,11 @@ public interface MultiverseWorld { void setPrice(double price); /** - * Gets the amount of currency it requires to enter this world. + * Gets the Type of currency that will be used when users enter this world. * - * @return The amount it costs to enter this world. + * @return The Type of currency that will be used when users enter this world. */ - double getPrice(); + int getCurrency(); /** * Sets the type of item that will be required given the price is not 0. @@ -390,11 +498,11 @@ public interface MultiverseWorld { void setCurrency(int item); /** - * Gets the Type of currency that will be used when users enter this world. + * Gets the world players will respawn in if they die in this one. * - * @return The Type of currency that will be used when users enter this world. + * @return A world that exists on the server. */ - int getCurrency(); + World getRespawnToWorld(); /** * Sets the world players will respawn in if they die in this one. @@ -406,11 +514,12 @@ public interface MultiverseWorld { boolean setRespawnToWorld(String respawnWorld); /** - * Gets the world players will respawn in if they die in this one. + * Gets the scaling value of this world.Really only has an effect if you use + * Multiverse-NetherPortals. * - * @return A world that exists on the server. + * @return This world's non-negative, non-zero scale. */ - World getRespawnToWorld(); + double getScaling(); /** * Sets the scale of this world. Really only has an effect if you use @@ -422,60 +531,11 @@ public interface MultiverseWorld { boolean setScaling(double scaling); /** - * Gets the scaling value of this world.Really only has an effect if you use - * Multiverse-NetherPortals. + * Gets whether or not a world will auto-heal players if the difficulty is on peaceful. * - * @return This world's non-negative, non-zero scale. + * @return True if the world should heal (default), false if not. */ - double getScaling(); - - /** - * Gets a list of all the worlds that players CANNOT travel to from this world, - * regardless of their access permissions. - * - * @return A List of world names. - */ - List getWorldBlacklist(); - - /** - * Returns a list of animals. This list always negates the {@link #canAnimalsSpawn()} result. - * - * @return A list of animals that will spawn if {@link #canAnimalsSpawn()} is false. - */ - List getAnimalList(); - - /** - * Sets whether or not animals can spawn. - * If there are values in {@link #getAnimalList()} and this is false, - * those animals become the exceptions, and will spawn - * - * @param allowAnimalSpawn True to allow spawning of monsters, false to prevent. - */ - void setAllowAnimalSpawn(boolean allowAnimalSpawn); - - /** - * Returns a list of monsters. This list always negates the {@link #canMonstersSpawn()} ()} result. - * - * @return A list of monsters that will spawn if {@link #canMonstersSpawn()} is false. - */ - List getMonsterList(); - - /** - * Sets whether or not monsters can spawn. - * If there are values in {@link #getMonsterList()} and this is false, - * those monsters become the exceptions, and will spawn - * - * @param allowMonsterSpawn True to allow spawning of monsters, false to prevent. - */ - void setAllowMonsterSpawn(boolean allowMonsterSpawn); - - /** - * Clears a list property (sets it to []). - * - * @param property The property to clear. - * @return True if success, false if fail. - */ - boolean clearList(String property); + boolean getAutoHeal(); /** * Sets whether or not a world will auto-heal players if the difficulty is on peaceful. @@ -485,11 +545,11 @@ public interface MultiverseWorld { void setAutoHeal(boolean heal); /** - * Gets whether or not a world will auto-heal players if the difficulty is on peaceful. + * Gets whether or not Multiverse should auto-adjust the spawn for this world. * - * @return True if the world should heal (default), false if not. + * @return True if Multiverse should adjust the spawn, false if not. */ - boolean getAutoHeal(); + boolean getAdjustSpawn(); /** * Sets whether or not Multiverse should auto-adjust the spawn for this world. @@ -499,11 +559,11 @@ public interface MultiverseWorld { void setAdjustSpawn(boolean adjust); /** - * Gets whether or not Multiverse should auto-adjust the spawn for this world. + * Gets whether or not Multiverse should auto-load this world. * - * @return True if Multiverse should adjust the spawn, false if not. + * @return True if Multiverse should auto-load this world. */ - boolean getAdjustSpawn(); + boolean getAutoLoad(); /** * Sets whether or not Multiverse should auto-load this world. @@ -515,11 +575,12 @@ public interface MultiverseWorld { void setAutoLoad(boolean autoLoad); /** - * Gets whether or not Multiverse should auto-load this world. + * Gets whether or not a player who dies in this world will respawn in their + * bed or follow the normal respawn pattern. * - * @return True if Multiverse should auto-load this world. + * @return True if players dying in this world should respawn at their bed. */ - boolean getAutoLoad(); + boolean getBedRespawn(); /** * Sets whether or not a player who dies in this world will respawn in their @@ -532,19 +593,10 @@ public interface MultiverseWorld { void setBedRespawn(boolean autoLoad); /** - * Gets whether or not a player who dies in this world will respawn in their - * bed or follow the normal respawn pattern. - * - * @return True if players dying in this world should respawn at their bed. + * Same as {@link #getTime()}, but returns a string. + * @return The time as a short string: 12:34pm */ - boolean getBedRespawn(); - - /** - * Gets all the names of all properties that can be SET. - * - * @return All property names, with alternating colors. - */ - String getAllPropertyNames(); + String getTime(); /** * Sets the current time in a world. @@ -559,22 +611,6 @@ public interface MultiverseWorld { */ boolean setTime(String timeAsString); - /** - * Same as {@link #getTime()}, but returns a string. - * @return The time as a short string: 12:34pm - */ - String getTime(); - - /** - * Gets the type of this world. As of 1.1-R1 this will be: - * FLAT or NORMAL - *

- * This is *not* the generator. - * - * @return The Type of this world. - */ - WorldType getWorldType(); - /** * Sets The types of portals that are allowed in this world. * @@ -588,4 +624,20 @@ public interface MultiverseWorld { * @return The type of portals that are allowed. */ AllowedPortalType getAllowedPortals(); + + // properties that are not "getter+setter" style + /** + * Gets a list of all the worlds that players CANNOT travel to from this world, + * regardless of their access permissions. + * + * @return A List of world names. + */ + List getWorldBlacklist(); + + /** + * Gets all the names of all properties that can be SET. + * + * @return All property names, with alternating colors. + */ + String getAllPropertyNames(); } diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/ConfigCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/ConfigCommand.java index 6290183a..55424a94 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/ConfigCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/ConfigCommand.java @@ -51,7 +51,7 @@ public class ConfigCommand extends MultiverseCommand { sender.sendMessage(message); return; } - if (!this.plugin.getMVConfig().setProperty(args.get(0).toLowerCase(), args.get(1))) { + if (!this.plugin.getMVConfig().setConfigProperty(args.get(0).toLowerCase(), args.get(1))) { sender.sendMessage(String.format("%sSetting '%s' to '%s' failed!", ChatColor.RED, args.get(0).toLowerCase(), args.get(1))); return; } diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/ModifyAddCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/ModifyAddCommand.java index abd3e135..40425de4 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/ModifyAddCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/ModifyAddCommand.java @@ -81,6 +81,7 @@ public class ModifyAddCommand extends MultiverseCommand { return; } + // TODO fix this if (world.addToVariable(property, value)) { sender.sendMessage(ChatColor.GREEN + "Success! " + ChatColor.AQUA + value + ChatColor.WHITE + " was " + ChatColor.GREEN + "added to " + ChatColor.GREEN + property); diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/ModifyClearCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/ModifyClearCommand.java index 78075432..d30b66f8 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/ModifyClearCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/ModifyClearCommand.java @@ -75,6 +75,7 @@ public class ModifyClearCommand extends MultiverseCommand { sender.sendMessage("Please visit our Github Wiki for more information: http://goo.gl/cgB2B"); return; } + // TODO fix this 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 " diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/ModifyRemoveCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/ModifyRemoveCommand.java index 57b4a262..f61efeff 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/ModifyRemoveCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/ModifyRemoveCommand.java @@ -81,6 +81,7 @@ public class ModifyRemoveCommand extends MultiverseCommand { sender.sendMessage("Please visit our Github Wiki for more information: http://goo.gl/4W8cY"); return; } + // TODO fix this if (world.removeFromVariable(property, value)) { sender.sendMessage(ChatColor.GREEN + "Success! " + ChatColor.AQUA + value + ChatColor.WHITE + " was " + ChatColor.RED + "removed from " + ChatColor.GREEN + property); diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/ModifySetCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/ModifySetCommand.java index 7c753ce4..5df8b93e 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/commands/ModifySetCommand.java +++ b/src/main/java/com/onarandombox/MultiverseCore/commands/ModifySetCommand.java @@ -102,22 +102,21 @@ public class ModifySetCommand extends MultiverseCommand { return; } - if ((property.equalsIgnoreCase("aliascolor") || property.equalsIgnoreCase("color")) && !world.isValidAliasColor(value)) { + if ((property.equalsIgnoreCase("aliascolor") || property.equalsIgnoreCase("color")) && !EnglishChatColor.isValidAliasColor(value)) { sender.sendMessage(value + " is not a valid color. Please pick one of the following:"); sender.sendMessage(EnglishChatColor.getAllColors()); return; } try { - if (world.setProperty(property, value, sender)) { + if (world.setPropertyValue(property, 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()); + sender.sendMessage(ChatColor.RED + world.getPropertyHelp(property)); } } catch (PropertyDoesNotExistException e) { sender.sendMessage(ChatColor.RED + "Sorry, You can't set: '" + ChatColor.GRAY + property + ChatColor.RED + "'"); - // TODO: Display the list - sender.sendMessage(ChatColor.GOLD + "For a full list of thingys, see our wiki."); + sender.sendMessage("Valid world-properties: " + world.getAllPropertyNames()); } } } diff --git a/src/main/java/com/onarandombox/MultiverseCore/configuration/ActiveStringConfigProperty.java b/src/main/java/com/onarandombox/MultiverseCore/configuration/ActiveStringConfigProperty.java deleted file mode 100644 index 078ba1b5..00000000 --- a/src/main/java/com/onarandombox/MultiverseCore/configuration/ActiveStringConfigProperty.java +++ /dev/null @@ -1,115 +0,0 @@ -/****************************************************************************** - * 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 { - 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; - } -} diff --git a/src/main/java/com/onarandombox/MultiverseCore/configuration/BooleanConfigProperty.java b/src/main/java/com/onarandombox/MultiverseCore/configuration/BooleanConfigProperty.java deleted file mode 100644 index 375a7872..00000000 --- a/src/main/java/com/onarandombox/MultiverseCore/configuration/BooleanConfigProperty.java +++ /dev/null @@ -1,135 +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.configuration; - -import org.bukkit.configuration.ConfigurationSection; - -/** - * A {@link Boolean} config-property. - */ -public class BooleanConfigProperty implements MVActiveConfigProperty { - 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); - } - - public BooleanConfigProperty(ConfigurationSection section, String name, Boolean defaultValue, String configNode, String help) { - this.name = name; - this.configNode = configNode; - this.section = section; - this.help = help; - this.value = defaultValue; - 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) { - return false; - } - this.value = value; - this.section.set(configNode, this.value); - return true; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean parseValue(String value) { - if (value == null) { - return false; - } - if (value.toLowerCase().equals("true") || value.toLowerCase().equals("false")) { - this.setValue(Boolean.parseBoolean(value)); - return true; - } - 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 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; - } -} diff --git a/src/main/java/com/onarandombox/MultiverseCore/configuration/ColorConfigProperty.java b/src/main/java/com/onarandombox/MultiverseCore/configuration/ColorConfigProperty.java deleted file mode 100644 index 1149b815..00000000 --- a/src/main/java/com/onarandombox/MultiverseCore/configuration/ColorConfigProperty.java +++ /dev/null @@ -1,98 +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.configuration; - -import com.onarandombox.MultiverseCore.enums.EnglishChatColor; -import org.bukkit.configuration.ConfigurationSection; - -/** - * A {@link EnglishChatColor} config-property. - */ -public class ColorConfigProperty implements MVConfigProperty { - private String name; - private EnglishChatColor value; - private String configNode; - private ConfigurationSection section; - private String help; - - public ColorConfigProperty(ConfigurationSection section, String name, EnglishChatColor defaultValue, String help) { - this(section, name, defaultValue, name, help); - } - - public ColorConfigProperty(ConfigurationSection section, String name, EnglishChatColor defaultValue, String configNode, String help) { - this.name = name; - this.configNode = configNode; - this.section = section; - this.help = help; - this.value = defaultValue; - 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) { - return false; - } - this.value = value; - this.section.set(configNode, this.value.getText()); - return true; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean parseValue(String value) { - EnglishChatColor color = EnglishChatColor.fromString(value); - if (color == null) { - return false; - } - this.setValue(color); - 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(); - } -} diff --git a/src/main/java/com/onarandombox/MultiverseCore/configuration/ConfigPropertyFactory.java b/src/main/java/com/onarandombox/MultiverseCore/configuration/ConfigPropertyFactory.java deleted file mode 100644 index cb409484..00000000 --- a/src/main/java/com/onarandombox/MultiverseCore/configuration/ConfigPropertyFactory.java +++ /dev/null @@ -1,306 +0,0 @@ -/****************************************************************************** - * 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; - -import com.onarandombox.MultiverseCore.enums.AllowedPortalType; -import com.onarandombox.MultiverseCore.enums.EnglishChatColor; -import org.bukkit.Difficulty; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.configuration.ConfigurationSection; - -/** A factory to create config properties for a given world. */ -public class ConfigPropertyFactory { - private ConfigurationSection section; - - public ConfigPropertyFactory(ConfigurationSection section) { - this.section = section; - } - - // 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); - } - - // Location - /** - * Constructs a new LocationConfigProperty. - * - * @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); - } - - // 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 PortalTypeConfigProperty getNewProperty(String name, AllowedPortalType defaultValue, String help) { - return new PortalTypeConfigProperty(this.section, name, defaultValue, help); - } - - /** - * 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); - } -} diff --git a/src/main/java/com/onarandombox/MultiverseCore/configuration/DifficultyConfigProperty.java b/src/main/java/com/onarandombox/MultiverseCore/configuration/DifficultyConfigProperty.java deleted file mode 100644 index 42b692c6..00000000 --- a/src/main/java/com/onarandombox/MultiverseCore/configuration/DifficultyConfigProperty.java +++ /dev/null @@ -1,129 +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.configuration; - -import org.bukkit.Difficulty; -import org.bukkit.configuration.ConfigurationSection; - -/** - * A {@link Difficulty} config-property. - */ -public class DifficultyConfigProperty implements MVActiveConfigProperty { - private String name; - private Difficulty value; - private String configNode; - private ConfigurationSection section; - private String help; - - public DifficultyConfigProperty(ConfigurationSection section, String name, Difficulty defaultValue, String help) { - this(section, name, defaultValue, name, help); - } - - public DifficultyConfigProperty(ConfigurationSection section, String name, Difficulty defaultValue, String configNode, String help) { - this.name = name; - this.configNode = configNode; - this.section = section; - this.help = help; - this.value = defaultValue; - 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) { - return false; - } - this.value = value; - this.section.set(configNode, this.value.toString()); - return true; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean parseValue(String value) { - try { - return this.setValue(Difficulty.getByValue(Integer.parseInt(value))); - } catch (NumberFormatException nfe) { - try { - return this.setValue(Difficulty.valueOf(value.toUpperCase())); - } catch (Exception e) { - 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 getMethod() { - return "setActualDifficulty"; - } - - /** - * 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; - } -} diff --git a/src/main/java/com/onarandombox/MultiverseCore/configuration/DoubleConfigProperty.java b/src/main/java/com/onarandombox/MultiverseCore/configuration/DoubleConfigProperty.java deleted file mode 100644 index bd6af823..00000000 --- a/src/main/java/com/onarandombox/MultiverseCore/configuration/DoubleConfigProperty.java +++ /dev/null @@ -1,133 +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.configuration; - -import org.bukkit.configuration.ConfigurationSection; - -/** - * A {@link Double} config-property. - */ -public class DoubleConfigProperty implements MVActiveConfigProperty { - 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); - } - - public DoubleConfigProperty(ConfigurationSection section, String name, Double defaultValue, String configNode, String help) { - this.name = name; - this.configNode = configNode; - this.section = section; - this.help = help; - this.value = defaultValue; - 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) { - return false; - } - this.value = value; - this.section.set(configNode, this.value); - return true; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean parseValue(String value) { - try { - this.setValue(Double.parseDouble(value)); - return true; - } catch (NumberFormatException e) { - 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 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; - } -} diff --git a/src/main/java/com/onarandombox/MultiverseCore/configuration/GameModeConfigProperty.java b/src/main/java/com/onarandombox/MultiverseCore/configuration/GameModeConfigProperty.java deleted file mode 100644 index 2812982c..00000000 --- a/src/main/java/com/onarandombox/MultiverseCore/configuration/GameModeConfigProperty.java +++ /dev/null @@ -1,129 +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.configuration; - -import org.bukkit.GameMode; -import org.bukkit.configuration.ConfigurationSection; - -/** - * A {@link GameMode} config-property. - */ -public class GameModeConfigProperty implements MVActiveConfigProperty { - private String name; - private GameMode value; - private String configNode; - private ConfigurationSection section; - private String help; - - public GameModeConfigProperty(ConfigurationSection section, String name, GameMode defaultValue, String help) { - this(section, name, defaultValue, name, help); - } - - public GameModeConfigProperty(ConfigurationSection section, String name, GameMode defaultValue, String configNode, String help) { - this.name = name; - this.configNode = configNode; - this.section = section; - this.help = help; - this.value = defaultValue; - 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) { - return false; - } - this.value = value; - this.section.set(configNode, this.value.toString()); - return true; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean parseValue(String value) { - try { - return this.setValue(GameMode.getByValue(Integer.parseInt(value))); - } catch (NumberFormatException nfe) { - try { - return this.setValue(GameMode.valueOf(value.toUpperCase())); - } catch (Exception e) { - 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 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; - } -} diff --git a/src/main/java/com/onarandombox/MultiverseCore/configuration/IntegerConfigProperty.java b/src/main/java/com/onarandombox/MultiverseCore/configuration/IntegerConfigProperty.java deleted file mode 100644 index 27961a24..00000000 --- a/src/main/java/com/onarandombox/MultiverseCore/configuration/IntegerConfigProperty.java +++ /dev/null @@ -1,97 +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.configuration; - -import org.bukkit.configuration.ConfigurationSection; - -/** - * A {@link Integer} config-property. - */ -public class IntegerConfigProperty implements MVConfigProperty { - private String name; - private Integer value; - private String configNode; - private ConfigurationSection section; - private String help; - - public IntegerConfigProperty(ConfigurationSection section, String name, Integer defaultValue, String help) { - this(section, name, defaultValue, name, help); - } - - public IntegerConfigProperty(ConfigurationSection section, String name, Integer defaultValue, String configNode, String help) { - this.name = name; - this.configNode = configNode; - this.section = section; - this.help = help; - this.value = defaultValue; - 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) { - return false; - } - this.value = value; - this.section.set(configNode, this.value); - return true; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean parseValue(String value) { - try { - this.setValue(Integer.parseInt(value)); - return true; - } catch (NumberFormatException e) { - 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(); - } -} diff --git a/src/main/java/com/onarandombox/MultiverseCore/configuration/LocationConfigProperty.java b/src/main/java/com/onarandombox/MultiverseCore/configuration/LocationConfigProperty.java deleted file mode 100644 index 9a7096f7..00000000 --- a/src/main/java/com/onarandombox/MultiverseCore/configuration/LocationConfigProperty.java +++ /dev/null @@ -1,154 +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.configuration; - -import com.onarandombox.MultiverseCore.utils.LocationManipulation; -import org.bukkit.Location; -import org.bukkit.configuration.ConfigurationSection; - -/** - * A {@link Location} config-property. - */ -public class LocationConfigProperty implements MVActiveConfigProperty { - 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); - } - - public LocationConfigProperty(ConfigurationSection section, String name, Location defaultValue, String configNode, String help) { - this.name = name; - this.configNode = configNode; - this.section = section; - this.help = help; - this.value = defaultValue; - 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) { - // TODO: oh my god, what should we do here? - Location parsed = LocationManipulation.stringToLocation(value); - return this.setValue(parsed); - } - - /** - * {@inheritDoc} - */ - @Override - public String getConfigNode() { - return this.configNode; - } - - /** - * {@inheritDoc} - */ - @Override - public String getHelp() { - return this.help; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean setValue(Location value) { - if (value == null) { - return false; - } - this.value = value; - this.section.set(configNode + ".x", this.value.getX()); - this.section.set(configNode + ".y", this.value.getY()); - this.section.set(configNode + ".z", this.value.getZ()); - this.section.set(configNode + ".pitch", this.value.getPitch()); - this.section.set(configNode + ".yaw", this.value.getYaw()); - this.section.set(configNode + ".world", this.value.getWorld().getName()); - - return true; - } - - private Location getLocationFromConfig(Location defaultValue) { - double x = this.section.getDouble(this.configNode + ".x", defaultValue.getX()); - double y = this.section.getDouble(this.configNode + ".y", defaultValue.getY()); - double z = this.section.getDouble(this.configNode + ".z", defaultValue.getZ()); - double pitch = this.section.getDouble(this.configNode + ".pitch", defaultValue.getPitch()); - double yaw = this.section.getDouble(this.configNode + ".yaw", defaultValue.getYaw()); - String w = this.section.getString(this.configNode + ".world", defaultValue.getWorld().getName()); - Location found = LocationManipulation.stringToLocation(w + ":" + x + "," + y + "," + z + ":" + yaw + ":" + pitch); - // TODO: oh my god, what should we do here? - if (found != null) { - return found; - } - return defaultValue; - } - - @Override - public String toString() { - // TODO: oh my god, what should we do here? - 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; - } -} diff --git a/src/main/java/com/onarandombox/MultiverseCore/configuration/MVActiveConfigProperty.java b/src/main/java/com/onarandombox/MultiverseCore/configuration/MVActiveConfigProperty.java index 08d071ed..403d0026 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/configuration/MVActiveConfigProperty.java +++ b/src/main/java/com/onarandombox/MultiverseCore/configuration/MVActiveConfigProperty.java @@ -10,8 +10,10 @@ package com.onarandombox.MultiverseCore.configuration; /** * An "active" {@link MVConfigProperty} that uses the specified method to be "actually" set. * @param The type of the config-property. + * @deprecated This is deprecated. * @see MVConfigProperty */ +@Deprecated public interface MVActiveConfigProperty extends MVConfigProperty { /** * Gets the method that will be executed. diff --git a/src/main/java/com/onarandombox/MultiverseCore/configuration/MVConfigProperty.java b/src/main/java/com/onarandombox/MultiverseCore/configuration/MVConfigProperty.java index ccb5924d..537a46b5 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/configuration/MVConfigProperty.java +++ b/src/main/java/com/onarandombox/MultiverseCore/configuration/MVConfigProperty.java @@ -11,7 +11,9 @@ package com.onarandombox.MultiverseCore.configuration; * A generic config-property. * * @param The type of the config-property. + * @deprecated This is deprecated. */ +@Deprecated public interface MVConfigProperty { /** * Gets the name of this property. diff --git a/src/main/java/com/onarandombox/MultiverseCore/configuration/PortalTypeConfigProperty.java b/src/main/java/com/onarandombox/MultiverseCore/configuration/PortalTypeConfigProperty.java deleted file mode 100644 index 685a8101..00000000 --- a/src/main/java/com/onarandombox/MultiverseCore/configuration/PortalTypeConfigProperty.java +++ /dev/null @@ -1,97 +0,0 @@ -/****************************************************************************** - * 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; - -import com.onarandombox.MultiverseCore.enums.AllowedPortalType; -import org.bukkit.configuration.ConfigurationSection; - -/** - * A {@link AllowedPortalType} config-property. - */ -public class PortalTypeConfigProperty implements MVConfigProperty { - private String name; - private AllowedPortalType value; - private String configNode; - private ConfigurationSection section; - private String help; - - public PortalTypeConfigProperty(ConfigurationSection section, String name, AllowedPortalType defaultValue, String help) { - this(section, name, defaultValue, name, help); - } - - public PortalTypeConfigProperty(ConfigurationSection section, String name, AllowedPortalType defaultValue, String configNode, String help) { - this.name = name; - this.configNode = configNode; - this.section = section; - this.help = help; - this.value = defaultValue; - this.parseValue(this.section.getString(this.configNode, defaultValue.toString())); - } - - /** - * {@inheritDoc} - */ - @Override - public String getName() { - return this.name; - } - - /** - * {@inheritDoc} - */ - @Override - public AllowedPortalType getValue() { - return this.value; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean setValue(AllowedPortalType value) { - if (value == null) { - return false; - } - this.value = value; - this.section.set(configNode, this.value.toString()); - return true; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean parseValue(String value) { - try { - return this.setValue(AllowedPortalType.valueOf(value.toUpperCase())); - } catch (Exception e) { - 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(); - } -} diff --git a/src/main/java/com/onarandombox/MultiverseCore/configuration/SpawnLocation.java b/src/main/java/com/onarandombox/MultiverseCore/configuration/SpawnLocation.java new file mode 100644 index 00000000..a09391c1 --- /dev/null +++ b/src/main/java/com/onarandombox/MultiverseCore/configuration/SpawnLocation.java @@ -0,0 +1,98 @@ +package com.onarandombox.MultiverseCore.configuration; + +import java.lang.ref.Reference; +import java.lang.ref.WeakReference; +import java.util.HashMap; +import java.util.Map; + +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.configuration.serialization.SerializableAs; + +/** + * Just like a regular {@link Location}, however {@code world} is usually {@code null} + * or just a weak reference and it implements {@link ConfigurationSerializable}. + */ +@SerializableAs("MVSpawnLocation") +public class SpawnLocation extends Location implements ConfigurationSerializable { + private Reference worldRef; + + public SpawnLocation(double x, double y, double z) { + super(null, x, y, z); + } + + public SpawnLocation(double x, double y, double z, float yaw, float pitch) { + super(null, x, y, z, yaw, pitch); + } + + public SpawnLocation(Location loc) { + this(loc.getX(), loc.getY(), loc.getZ(), loc.getYaw(), loc.getPitch()); + } + + /** + * {@inheritDoc} + */ + @Override + public World getWorld() { + return (this.worldRef != null) ? this.worldRef.get() : null; + } + + /** + * {@inheritDoc} + */ + @Override + public void setWorld(World world) { + this.worldRef = new WeakReference(world); + } + + /** + * {@inheritDoc} + */ + @Override + public Chunk getChunk() { + if ((this.worldRef != null) && (this.worldRef.get() != null)) + return this.worldRef.get().getChunkAt(this); + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public Block getBlock() { + if ((this.worldRef != null) && (this.worldRef.get() != null)) + return this.worldRef.get().getBlockAt(this); + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public Map serialize() { + Map serialized = new HashMap(5); // SUPPRESS CHECKSTYLE: MagicNumberCheck + serialized.put("x", this.getX()); + serialized.put("y", this.getY()); + serialized.put("z", this.getZ()); + serialized.put("pitch", this.getPitch()); + serialized.put("yaw", this.getYaw()); + return serialized; + } + + /** + * Let Bukkit be able to deserialize this. + * @param args The map. + * @return The deserialized object. + */ + public static SpawnLocation deserialize(Map args) { + double x = ((Number) args.get("x")).doubleValue(); + double y = ((Number) args.get("y")).doubleValue(); + double z = ((Number) args.get("z")).doubleValue(); + float pitch = ((Number) args.get("pitch")).floatValue(); + float yaw = ((Number) args.get("yaw")).floatValue(); + return new SpawnLocation(x, y, z, yaw, pitch); + } +} diff --git a/src/main/java/com/onarandombox/MultiverseCore/configuration/SpawnSettings.java b/src/main/java/com/onarandombox/MultiverseCore/configuration/SpawnSettings.java new file mode 100644 index 00000000..04f2cb71 --- /dev/null +++ b/src/main/java/com/onarandombox/MultiverseCore/configuration/SpawnSettings.java @@ -0,0 +1,50 @@ +package com.onarandombox.MultiverseCore.configuration; + +import java.util.Map; + +import me.main__.util.SerializationConfig.Property; +import me.main__.util.SerializationConfig.SerializationConfig; + +import org.bukkit.configuration.serialization.SerializableAs; + +/** + * Spawning-Settings. + */ +@SerializableAs("MVSpawnSettings") +public class SpawnSettings extends SerializationConfig { + @Property + private SubSpawnSettings animals; + @Property + private SubSpawnSettings monsters; + + public SpawnSettings() { + super(); + } + + public SpawnSettings(Map values) { + super(values); + } + + /** + * {@inheritDoc} + */ + @Override + public void setDefaults() { + animals = new SubSpawnSettings(); + monsters = new SubSpawnSettings(); + } + + /** + * @return the animal-settings + */ + public SubSpawnSettings getAnimalSettings() { + return animals; + } + + /** + * @return the monster-settings + */ + public SubSpawnSettings getMonsterSettings() { + return monsters; + } +} diff --git a/src/main/java/com/onarandombox/MultiverseCore/configuration/StringConfigProperty.java b/src/main/java/com/onarandombox/MultiverseCore/configuration/StringConfigProperty.java deleted file mode 100644 index 948034ce..00000000 --- a/src/main/java/com/onarandombox/MultiverseCore/configuration/StringConfigProperty.java +++ /dev/null @@ -1,96 +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.configuration; - -import org.bukkit.configuration.ConfigurationSection; - -/** - * A {@link String} config-property. - */ -public class StringConfigProperty implements MVConfigProperty { - private String name; - private String value; - private String configNode; - private ConfigurationSection section; - private String help; - - public StringConfigProperty(ConfigurationSection section, String name, String defaultValue, String help) { - this(section, name, defaultValue, defaultValue, help); - } - - public StringConfigProperty(ConfigurationSection section, String name, String defaultValue, String configNode, String help) { - this.name = name; - this.configNode = configNode; - this.section = section; - this.help = help; - this.value = defaultValue; - 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) { - return false; - } - this.setValue(value); - return true; - } - - /** - * {@inheritDoc} - */ - @Override - public String getConfigNode() { - return this.configNode; - } - - /** - * {@inheritDoc} - */ - @Override - public String getHelp() { - return this.help; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean setValue(String value) { - if (value == null) { - return false; - } - this.value = value; - this.section.set(configNode, this.value); - return true; - } - - @Override - public String toString() { - return value; - } -} diff --git a/src/main/java/com/onarandombox/MultiverseCore/configuration/SubSpawnSettings.java b/src/main/java/com/onarandombox/MultiverseCore/configuration/SubSpawnSettings.java new file mode 100644 index 00000000..d66bd133 --- /dev/null +++ b/src/main/java/com/onarandombox/MultiverseCore/configuration/SubSpawnSettings.java @@ -0,0 +1,59 @@ +package com.onarandombox.MultiverseCore.configuration; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import me.main__.util.SerializationConfig.Property; +import me.main__.util.SerializationConfig.SerializationConfig; + +import org.bukkit.configuration.serialization.SerializableAs; + +/** + * SpawnSubSettings. + */ +@SerializableAs("MVSpawnSubSettings") +public class SubSpawnSettings extends SerializationConfig { + @Property + private boolean spawn; + @Property + private List exceptions; + + public SubSpawnSettings() { + super(); + } + + public SubSpawnSettings(Map values) { + super(values); + } + + /** + * {@inheritDoc} + */ + @Override + public void setDefaults() { + spawn = true; + exceptions = new ArrayList(); + } + + /** + * @return spawn + */ + public boolean doSpawn() { + return spawn; + } + + /** + * @param spawn The new value. + */ + public void setSpawn(boolean spawn) { + this.spawn = spawn; + } + + /** + * @return the exceptions + */ + public List getExceptions() { + return exceptions; + } +} diff --git a/src/main/java/com/onarandombox/MultiverseCore/configuration/WorldPropertyValidator.java b/src/main/java/com/onarandombox/MultiverseCore/configuration/WorldPropertyValidator.java new file mode 100644 index 00000000..b051eabd --- /dev/null +++ b/src/main/java/com/onarandombox/MultiverseCore/configuration/WorldPropertyValidator.java @@ -0,0 +1,27 @@ +package com.onarandombox.MultiverseCore.configuration; + +import org.bukkit.Bukkit; + +import com.onarandombox.MultiverseCore.MVWorld; +import com.onarandombox.MultiverseCore.event.MVWorldPropertyChangeEvent; + +import me.main__.util.SerializationConfig.ChangeDeniedException; +import me.main__.util.SerializationConfig.ObjectUsingValidator; + +/** + * Validates world-property-changes. + * @param The type of the property that should be validated. + */ +public class WorldPropertyValidator extends ObjectUsingValidator { + /** + * {@inheritDoc} + */ + @Override + public T validateChange(String property, T newValue, T oldValue, MVWorld object) throws ChangeDeniedException { + MVWorldPropertyChangeEvent event = new MVWorldPropertyChangeEvent(object, null, property, newValue); + Bukkit.getPluginManager().callEvent(event); + if (event.isCancelled()) + throw new ChangeDeniedException(); + return event.getTheNewValue(); + } +} diff --git a/src/main/java/com/onarandombox/MultiverseCore/enums/EnglishChatColor.java b/src/main/java/com/onarandombox/MultiverseCore/enums/EnglishChatColor.java index 4f3d015a..007f2024 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/enums/EnglishChatColor.java +++ b/src/main/java/com/onarandombox/MultiverseCore/enums/EnglishChatColor.java @@ -99,4 +99,13 @@ public enum EnglishChatColor { } return null; } + + /** + * Looks if the given-color name is a valid color. + * @param aliasColor A color-name. + * @return True if the name is a valid color, false if it isn't. + */ + public static boolean isValidAliasColor(String aliasColor) { + return (EnglishChatColor.fromString(aliasColor) != null); + } } diff --git a/src/main/java/com/onarandombox/MultiverseCore/event/MVWorldPropertyChangeEvent.java b/src/main/java/com/onarandombox/MultiverseCore/event/MVWorldPropertyChangeEvent.java index 1cdd6404..d85e104a 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/event/MVWorldPropertyChangeEvent.java +++ b/src/main/java/com/onarandombox/MultiverseCore/event/MVWorldPropertyChangeEvent.java @@ -19,16 +19,18 @@ import org.bukkit.event.HandlerList; * If it is cancelled, no change will happen. *

* 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() + * To get the name of the property that was changed, use {@link #getPropertyName()}. + * To get the new value, use {@link #getTheNewValue()}. To change it, use {@link #setTheNewValue(Object)}. + * @param The type of the property that was set. */ -public class MVWorldPropertyChangeEvent extends Event implements Cancellable { +public class MVWorldPropertyChangeEvent extends Event implements Cancellable { private MultiverseWorld world; private CommandSender changer; private boolean isCancelled = false; - private String value; private String name; + private T value; - public MVWorldPropertyChangeEvent(MultiverseWorld world, CommandSender changer, String name, String value) { + public MVWorldPropertyChangeEvent(MultiverseWorld world, CommandSender changer, String name, T value) { this.world = world; this.changer = changer; this.name = name; @@ -64,16 +66,38 @@ public class MVWorldPropertyChangeEvent extends Event implements Cancellable { /** * Gets the new value. * @return The new value. + * @deprecated Use {@link #getTheNewValue()} instead. */ + @Deprecated public String getNewValue() { + return this.value.toString(); + } + + /** + * Gets the new value. + * @return The new value. + */ + public T getTheNewValue() { return this.value; } /** * Sets the new value. + *

+ * This method is only a stub, it'll always throw an {@link UnsupportedOperationException}! * @param value The new new value. + * @deprecated Use {@link #setTheNewValue(Object)} instead. */ + @Deprecated public void setNewValue(String value) { + throw new UnsupportedOperationException(); + } + + /** + * Sets the new value. + * @param value The new value. + */ + public void setTheNewValue(T value) { this.value = value; } @@ -88,6 +112,8 @@ public class MVWorldPropertyChangeEvent extends Event implements Cancellable { /** * Gets the person (or console) who was responsible for the change. + *

+ * This may be null! * * @return The person (or console) who was responsible for the change. */ diff --git a/src/main/java/com/onarandombox/MultiverseCore/exceptions/PropertyDoesNotExistException.java b/src/main/java/com/onarandombox/MultiverseCore/exceptions/PropertyDoesNotExistException.java index fc367342..95a24169 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/exceptions/PropertyDoesNotExistException.java +++ b/src/main/java/com/onarandombox/MultiverseCore/exceptions/PropertyDoesNotExistException.java @@ -14,4 +14,8 @@ public class PropertyDoesNotExistException extends Exception { public PropertyDoesNotExistException(String name) { super(name); } + + public PropertyDoesNotExistException(String name, Throwable cause) { + super(name, cause); + } } diff --git a/src/main/java/com/onarandombox/MultiverseCore/utils/WorldManager.java b/src/main/java/com/onarandombox/MultiverseCore/utils/WorldManager.java index 388a694d..840588ab 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/utils/WorldManager.java +++ b/src/main/java/com/onarandombox/MultiverseCore/utils/WorldManager.java @@ -13,7 +13,6 @@ import com.onarandombox.MultiverseCore.api.MVWorldManager; import com.onarandombox.MultiverseCore.api.MultiverseWorld; import com.onarandombox.MultiverseCore.api.SafeTTeleporter; import com.onarandombox.MultiverseCore.api.WorldPurger; -import com.onarandombox.MultiverseCore.commands.EnvironmentCommand; import com.onarandombox.MultiverseCore.event.MVWorldDeleteEvent; import org.bukkit.World; import org.bukkit.World.Environment; @@ -44,16 +43,16 @@ import java.util.logging.Level; public class WorldManager implements MVWorldManager { private MultiverseCore plugin; private WorldPurger worldPurger; + private Map worldsFromTheConfig; private Map worlds; - private List unloadedWorlds; private FileConfiguration configWorlds = null; private Map defaultGens; private String firstSpawn; public WorldManager(MultiverseCore core) { this.plugin = core; + this.worldsFromTheConfig = new HashMap(); this.worlds = new HashMap(); - this.unloadedWorlds = new ArrayList(); this.worldPurger = new SimpleWorldPurger(plugin); } @@ -118,7 +117,10 @@ public class WorldManager implements MVWorldManager { c.generateStructures(generateStructures); } - World world; + // Important: doLoad() needs the MVWorld-object in worldsFromTheConfig + if (!worldsFromTheConfig.containsKey(name)) + worldsFromTheConfig.put(name, new MVWorld(useSpawnAdjust)); + StringBuilder builder = new StringBuilder(); builder.append("Loading World & Settings - '").append(name).append("'"); builder.append(" - Env: ").append(env); @@ -131,27 +133,12 @@ public class WorldManager implements MVWorldManager { } this.plugin.log(Level.INFO, builder.toString()); - try { - world = c.createWorld(); - } catch (Exception e) { - this.plugin.log(Level.SEVERE, "The world '" + name + "' could NOT be loaded because it contains errors!"); - this.plugin.log(Level.SEVERE, "Try using Chukster to repair your world! '" + name + "'"); - this.plugin.log(Level.SEVERE, "http://forums.bukkit.org/threads/admin-chunkster.8186/"); - return false; - } - - if (world == null) { + if (!doLoad(c)) { this.plugin.log(Level.SEVERE, "Failed to Create/Load the world '" + name + "'"); return false; } - MultiverseWorld mvworld = new MVWorld(world, this.configWorlds, this.plugin, - this.plugin.getServer().getWorld(name).getSeed(), generator, useSpawnAdjust); - this.worldPurger.purgeWorld(mvworld); - this.worlds.put(name, mvworld); - if (this.unloadedWorlds.contains(name)) { - this.unloadedWorlds.remove(name); - } + this.saveWorldsConfig(); return true; } @@ -185,9 +172,9 @@ public class WorldManager implements MVWorldManager { this.configWorlds.set("worlds." + name, null); this.saveWorldsConfig(); - // Remove it from the list of unloaded worlds. - if (this.unloadedWorlds.contains(name)) { - this.unloadedWorlds.remove(name); + // Remove it from the list of worlds. + if (this.worldsFromTheConfig.containsKey(name)) { + this.worldsFromTheConfig.remove(name); } return true; } else { @@ -236,15 +223,14 @@ public class WorldManager implements MVWorldManager { if (this.unloadWorldFromBukkit(name, true)) { this.worlds.remove(name); this.plugin.log(Level.INFO, "World '" + name + "' was unloaded from memory."); - this.unloadedWorlds.add(name); return true; } else { this.plugin.log(Level.WARNING, "World '" + name + "' could not be unloaded. Is it a default world?"); } } else if (this.plugin.getServer().getWorld(name) != null) { this.plugin.log(Level.WARNING, "Hmm Multiverse does not know about this world but it's loaded in memory."); - this.plugin.log(Level.WARNING, "To unload it using multiverse, use:"); - this.plugin.log(Level.WARNING, "/mv import " + name + " " + this.plugin.getServer().getWorld(name).getEnvironment().toString()); + this.plugin.log(Level.WARNING, "To let Multiverse know about it, use:"); + this.plugin.log(Level.WARNING, String.format("/mv import %s %s", name, this.plugin.getServer().getWorld(name).getEnvironment().toString())); } else { this.plugin.log(Level.INFO, "Multiverse does not know about " + name + " and it's not loaded by Bukkit."); } @@ -258,36 +244,48 @@ public class WorldManager implements MVWorldManager { public boolean loadWorld(String name) { // Check if the World is already loaded if (this.worlds.containsKey(name)) { - // Ensure it's not unloaded, since it IS loaded. - if (this.unloadedWorlds.contains(name)) { - this.unloadedWorlds.remove(name); - } return true; } - // Grab all the Worlds from the Config. - Set worldKeys = this.configWorlds.getConfigurationSection("worlds").getKeys(false); - - // Check that the list is not null and that the config contains the world - if ((worldKeys != null) && (worldKeys.contains(name))) { - // Grab the initial values from the config file. - String environment = this.configWorlds.getString("worlds." + name + ".environment", "NORMAL"); // Grab the Environment as a String. - String type = this.configWorlds.getString("worlds." + name + ".type", "NORMAL"); - String seedString = this.configWorlds.getString("worlds." + name + ".seed", ""); - String generatorString = this.configWorlds.getString("worlds." + name + ".generator"); - boolean generateStructures = this.configWorlds.getBoolean("worlds." + name + ".generatestructures", true); - - this.addWorld(name, EnvironmentCommand.getEnvFromString(environment), seedString, - EnvironmentCommand.getWorldTypeFromString(type), generateStructures, generatorString); - if (this.unloadedWorlds.contains(name)) { - this.unloadedWorlds.remove(name); - } - return true; + // Check that the world is in the config + if (worldsFromTheConfig.containsKey(name)) { + return doLoad(name); } else { return false; } } + private void brokenWorld(String name) { + this.plugin.log(Level.SEVERE, "The world '" + name + "' could NOT be loaded because it contains errors!"); + this.plugin.log(Level.SEVERE, "Try using Chukster to repair your world! '" + name + "'"); + this.plugin.log(Level.SEVERE, "http://forums.bukkit.org/threads/admin-chunkster.8186/"); + } + + private boolean doLoad(String name) { + return doLoad(WorldCreator.name(name)); + } + + private boolean doLoad(WorldCreator creator) { + String worldName = creator.name(); + if (!worldsFromTheConfig.containsKey(worldName)) + throw new IllegalArgumentException("That world doesn't exist!"); + if (worlds.containsKey(worldName)) + throw new IllegalArgumentException("That world is already loaded!"); + MVWorld mvworld = worldsFromTheConfig.get(worldName); + World cbworld; + try { + cbworld = WorldCreator.name(worldName).createWorld(); + } catch (Exception e) { + e.printStackTrace(); + brokenWorld(worldName); + return false; + } + mvworld.init(cbworld, plugin); + this.worldPurger.purgeWorld(mvworld); + this.worlds.put(worldName, mvworld); + return true; + } + /** * {@inheritDoc} */ @@ -459,18 +457,14 @@ public class WorldManager implements MVWorldManager { public void loadDefaultWorlds() { this.ensureConfigIsPrepared(); List myWorlds = this.plugin.getServer().getWorlds(); - Set worldStrings = this.configWorlds.getConfigurationSection("worlds").getKeys(false); for (World w : myWorlds) { String name = w.getName(); - if (!worldStrings.contains(name)) { + if (!worldsFromTheConfig.containsKey(name)) { + String generator = null; if (this.defaultGens.containsKey(name)) { - this.addWorld(name, w.getEnvironment(), w.getSeed() + "", w.getWorldType(), - w.canGenerateStructures(), this.defaultGens.get(name)); - } else { - this.addWorld(name, w.getEnvironment(), w.getSeed() + "", w.getWorldType(), - w.canGenerateStructures(), null); + generator = this.defaultGens.get(name); } - + this.addWorld(name, w.getEnvironment(), String.valueOf(w.getSeed()), w.getWorldType(), w.canGenerateStructures(), generator); } } } @@ -478,11 +472,6 @@ public class WorldManager implements MVWorldManager { private void ensureConfigIsPrepared() { if (this.configWorlds.getConfigurationSection("worlds") == null) { this.configWorlds.createSection("worlds"); - try { - this.configWorlds.save(new File(this.plugin.getDataFolder(), "worlds.yml")); - } catch (IOException e) { - this.plugin.log(Level.SEVERE, "Failed to save worlds.yml. Please check your file permissions."); - } } } @@ -495,13 +484,10 @@ public class WorldManager implements MVWorldManager { int count = 0; this.ensureConfigIsPrepared(); this.ensureSecondNamespaceIsPrepared(); - // Grab all the Worlds from the Config. - Set worldKeys = this.configWorlds.getConfigurationSection("worlds").getKeys(false); // Force the worlds to be loaded, ie don't just load new worlds. if (forceLoad) { // Remove all world permissions. - Permission allAccess = this.plugin.getServer().getPluginManager().getPermission("multiverse.access.*"); Permission allExempt = this.plugin.getServer().getPluginManager().getPermission("multiverse.exempt.*"); for (MultiverseWorld w : this.worlds.values()) { @@ -523,45 +509,19 @@ public class WorldManager implements MVWorldManager { this.worlds.clear(); } - // Check that the list is not null. - if (worldKeys != null) { - for (String worldKey : worldKeys) { - // Check if the World is already loaded within the Plugin. - if (this.worlds.containsKey(worldKey)) { - continue; - } + for (Map.Entry entry : worldsFromTheConfig.entrySet()) { + if (worlds.containsKey(entry.getKey())) + continue; + if (!entry.getValue().getAutoLoad()) + continue; - // If autoload was set to false, don't load this one. - if (!this.configWorlds.getBoolean("worlds." + worldKey + ".autoload", true)) { - if (!this.unloadedWorlds.contains(worldKey)) { - this.unloadedWorlds.add(worldKey); - } - continue; - } - // Grab the initial values from the config file. - String environment = this.configWorlds.getString("worlds." + worldKey + ".environment", "NORMAL"); - String type = this.configWorlds.getString("worlds." + worldKey + ".type", "NORMAL"); - String seedString = this.configWorlds.getString("worlds." + worldKey + ".seed", null); - boolean generateStructures = this.configWorlds.getBoolean("worlds." + worldKey + ".generatestructures", true); - if (seedString == null) { - seedString = this.configWorlds.getLong("worlds." + worldKey + ".seed") + ""; - } - - String generatorString = this.configWorlds.getString("worlds." + worldKey + ".generator"); - if (environment.equalsIgnoreCase("skylands")) { - this.plugin.log(Level.WARNING, "Found SKYLANDS world. Not importing automatically, as it won't work atm :("); - continue; - } - addWorld(worldKey, EnvironmentCommand.getEnvFromString(environment), seedString, - EnvironmentCommand.getWorldTypeFromString(type), generateStructures, generatorString); - - // Increment the world count + if (doLoad(entry.getKey())) count++; - } } // Simple Output to the Console to show how many Worlds were loaded. this.plugin.log(Level.INFO, count + " - World(s) loaded."); + this.saveWorldsConfig(); } private void ensureSecondNamespaceIsPrepared() { @@ -591,14 +551,21 @@ public class WorldManager implements MVWorldManager { } /** - * Load the config from a file. - * - * @param file The file to load. - * @return A loaded configuration. + * {@inheritDoc} */ @Override public FileConfiguration loadWorldConfig(File file) { this.configWorlds = YamlConfiguration.loadConfiguration(file); + this.ensureConfigIsPrepared(); + // load world-objects + Set worldKeys = this.configWorlds.getConfigurationSection("worlds").getKeys(false); + if (worldKeys != null) { + for (String key : worldKeys) { + if (this.configWorlds.get("worlds." + key) instanceof MVWorld) { + this.worldsFromTheConfig.put(key, (MVWorld) this.configWorlds.get("worlds." + key)); + } + } + } return this.configWorlds; } @@ -608,6 +575,9 @@ public class WorldManager implements MVWorldManager { @Override public boolean saveWorldsConfig() { try { + for (Map.Entry entry : worlds.entrySet()) { + this.configWorlds.set("worlds." + entry.getKey(), entry.getValue()); + } this.configWorlds.save(new File(this.plugin.getDataFolder(), "worlds.yml")); return true; } catch (IOException e) { @@ -629,7 +599,9 @@ public class WorldManager implements MVWorldManager { */ @Override public List getUnloadedWorlds() { - return this.unloadedWorlds; + List allNames = new ArrayList(this.worldsFromTheConfig.keySet()); + allNames.removeAll(worlds.keySet()); + return allNames; } /** diff --git a/src/test/java/com/onarandombox/MultiverseCore/test/TestWorldProperties.java b/src/test/java/com/onarandombox/MultiverseCore/test/TestWorldProperties.java index 5dc074a6..4e4619a2 100644 --- a/src/test/java/com/onarandombox/MultiverseCore/test/TestWorldProperties.java +++ b/src/test/java/com/onarandombox/MultiverseCore/test/TestWorldProperties.java @@ -21,6 +21,7 @@ import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.HumanEntity; import org.bukkit.entity.Player; import org.bukkit.event.entity.EntityRegainHealthEvent; import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason; @@ -45,6 +46,7 @@ import org.powermock.modules.junit4.PowerMockRunner; import com.onarandombox.MultiverseCore.MultiverseCore; import com.onarandombox.MultiverseCore.api.MVWorldManager; import com.onarandombox.MultiverseCore.api.MultiverseWorld; +import com.onarandombox.MultiverseCore.configuration.SpawnLocation; import com.onarandombox.MultiverseCore.test.utils.TestInstanceCreator; import com.onarandombox.MultiverseCore.utils.WorldManager; @@ -145,7 +147,7 @@ public class TestWorldProperties { assertTrue(mvWorld.isKeepingSpawnInMemory()); assertTrue(mvWorld.getBedRespawn()); assertTrue(mvWorld.getAutoLoad()); - assertEquals(new Location(mvWorld.getCBWorld(), 0, 64, 0), mvWorld.getSpawnLocation()); + assertEquals(new SpawnLocation(0, 64, 0), mvWorld.getSpawnLocation()); /* ****************************************** * * Call some events and verify behavior @@ -242,7 +244,7 @@ public class TestWorldProperties { mvWorld.setAutoLoad(false); assertEquals(false, mvWorld.getAutoLoad()); mvWorld.setSpawnLocation(new Location(mvWorld.getCBWorld(), 1, 1, 1)); - assertEquals(new Location(mvWorld.getCBWorld(), 1, 1, 1), mvWorld.getSpawnLocation()); + assertEquals(new SpawnLocation(1, 1, 1), mvWorld.getSpawnLocation()); /* ****************************************** * * Call some events and verify behavior @@ -279,7 +281,7 @@ public class TestWorldProperties { core.getPlayerListener().playerJoin(playerJoinEvent); verify(mockPlayer, never()).teleport(any(Location.class)); core.getPlayerListener().playerJoin(playerNewJoinEvent); - verify(mockNewPlayer).teleport(new Location(mvWorld.getCBWorld(), 1, 1, 1)); + verify(mockNewPlayer).teleport(new SpawnLocation(1, 1, 1)); // call player respawn events core.getPlayerListener().playerRespawn(playerRespawnBed); diff --git a/src/test/java/com/onarandombox/MultiverseCore/test/TestWorldStuff.java b/src/test/java/com/onarandombox/MultiverseCore/test/TestWorldStuff.java index fc63b0e6..790fa787 100644 --- a/src/test/java/com/onarandombox/MultiverseCore/test/TestWorldStuff.java +++ b/src/test/java/com/onarandombox/MultiverseCore/test/TestWorldStuff.java @@ -235,13 +235,13 @@ public class TestWorldStuff { // Now fail one. plugin.onCommand(mockCommandSender, mockCommand, "", new String[]{ "modify", "set", "mode", "fish", "world" }); try { - verify(mockCommandSender).sendMessage(mainWorld.getProperty("mode", Object.class).getHelp()); + verify(mockCommandSender).sendMessage(ChatColor.RED + mainWorld.getPropertyHelp("mode")); } catch (PropertyDoesNotExistException e) { fail("Mode property did not exist."); } plugin.onCommand(mockCommandSender, mockCommand, "", new String[]{ "modify", "set", "blah", "fish", "world" }); - verify(mockCommandSender).sendMessage(ChatColor.RED + "Sorry, You can't set: '"+ChatColor.GRAY+ "blah" + ChatColor.RED + "'"); + verify(mockCommandSender).sendMessage(ChatColor.RED + "Sorry, You can't set: '" + ChatColor.GRAY + "blah" + ChatColor.RED + "'"); } private void createInitialWorlds(Plugin plugin, Command command) { diff --git a/src/test/java/com/onarandombox/MultiverseCore/test/utils/MockWorldFactory.java b/src/test/java/com/onarandombox/MultiverseCore/test/utils/MockWorldFactory.java index c0f22b03..2acc9f6b 100644 --- a/src/test/java/com/onarandombox/MultiverseCore/test/utils/MockWorldFactory.java +++ b/src/test/java/com/onarandombox/MultiverseCore/test/utils/MockWorldFactory.java @@ -14,6 +14,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.WeakHashMap; import org.bukkit.Location; import org.bukkit.Material; @@ -28,6 +29,9 @@ public class MockWorldFactory { private static final Map createdWorlds = new HashMap(); + private static final Map pvpStates = new WeakHashMap(); + private static final Map keepSpawnInMemoryStates = new WeakHashMap(); + private MockWorldFactory() { } @@ -38,10 +42,43 @@ public class MockWorldFactory { private static World basics(String world, World.Environment env, WorldType type) { World mockWorld = mock(World.class); when(mockWorld.getName()).thenReturn(world); + when(mockWorld.getPVP()).thenAnswer(new Answer() { + @Override + public Boolean answer(InvocationOnMock invocation) throws Throwable { + World w = (World) invocation.getMock(); + if (!pvpStates.containsKey(w)) + pvpStates.put(w, true); // default value + return pvpStates.get(w); + } + }); + doAnswer(new Answer() { + @Override + public Void answer(InvocationOnMock invocation) throws Throwable { + pvpStates.put((World) invocation.getMock(), (Boolean) invocation.getArguments()[0]); + return null; + } + }).when(mockWorld).setPVP(anyBoolean()); + when(mockWorld.getKeepSpawnInMemory()).thenAnswer(new Answer() { + @Override + public Boolean answer(InvocationOnMock invocation) throws Throwable { + World w = (World) invocation.getMock(); + if (!keepSpawnInMemoryStates.containsKey(w)) + keepSpawnInMemoryStates.put(w, true); // default value + return keepSpawnInMemoryStates.get(w); + } + }); + doAnswer(new Answer() { + @Override + public Void answer(InvocationOnMock invocation) throws Throwable { + keepSpawnInMemoryStates.put((World) invocation.getMock(), (Boolean) invocation.getArguments()[0]); + return null; + } + }).when(mockWorld).setKeepSpawnInMemory(anyBoolean()); when(mockWorld.getEnvironment()).thenReturn(env); when(mockWorld.getWorldType()).thenReturn(type); when(mockWorld.getSpawnLocation()).thenReturn(new Location(mockWorld, 0, 64, 0)); when(mockWorld.getWorldFolder()).thenAnswer(new Answer() { + @Override public File answer(InvocationOnMock invocation) throws Throwable { if (!(invocation.getMock() instanceof World)) return null; @@ -51,6 +88,7 @@ public class MockWorldFactory { } }); when(mockWorld.getBlockAt(any(Location.class))).thenAnswer(new Answer() { + @Override public Block answer(InvocationOnMock invocation) throws Throwable { Location loc; try { @@ -85,6 +123,7 @@ public class MockWorldFactory { when(mockWorld.getWorldType()).thenReturn(type); when(mockWorld.getSpawnLocation()).thenReturn(new Location(mockWorld, 0, 64, 0)); when(mockWorld.getWorldFolder()).thenAnswer(new Answer() { + @Override public File answer(InvocationOnMock invocation) throws Throwable { if (!(invocation.getMock() instanceof World)) return null; @@ -94,6 +133,7 @@ public class MockWorldFactory { } }); when(mockWorld.getBlockAt(any(Location.class))).thenAnswer(new Answer() { + @Override public Block answer(InvocationOnMock invocation) throws Throwable { Location loc; try { diff --git a/src/test/java/com/onarandombox/MultiverseCore/test/utils/TestInstanceCreator.java b/src/test/java/com/onarandombox/MultiverseCore/test/utils/TestInstanceCreator.java index 1f93233c..c7b91c38 100644 --- a/src/test/java/com/onarandombox/MultiverseCore/test/utils/TestInstanceCreator.java +++ b/src/test/java/com/onarandombox/MultiverseCore/test/utils/TestInstanceCreator.java @@ -103,6 +103,7 @@ public class TestInstanceCreator { // Give the server some worlds when(mockServer.getWorld(anyString())).thenAnswer(new Answer() { + @Override public World answer(InvocationOnMock invocation) throws Throwable { String arg; try { @@ -115,6 +116,7 @@ public class TestInstanceCreator { }); when(mockServer.getWorlds()).thenAnswer(new Answer>() { + @Override public List answer(InvocationOnMock invocation) throws Throwable { return MockWorldFactory.getWorlds(); } @@ -124,6 +126,7 @@ public class TestInstanceCreator { when(mockServer.createWorld(Matchers.isA(WorldCreator.class))).thenAnswer( new Answer() { + @Override public World answer(InvocationOnMock invocation) throws Throwable { WorldCreator arg; try { @@ -146,6 +149,7 @@ public class TestInstanceCreator { BukkitScheduler mockScheduler = mock(BukkitScheduler.class); when(mockScheduler.scheduleSyncDelayedTask(any(Plugin.class), any(Runnable.class), anyLong())). thenAnswer(new Answer() { + @Override public Integer answer(InvocationOnMock invocation) throws Throwable { Runnable arg; try { @@ -158,6 +162,7 @@ public class TestInstanceCreator { }}); when(mockScheduler.scheduleSyncDelayedTask(any(Plugin.class), any(Runnable.class))). thenAnswer(new Answer() { + @Override public Integer answer(InvocationOnMock invocation) throws Throwable { Runnable arg; try { @@ -204,6 +209,7 @@ public class TestInstanceCreator { commandSenderLogger.setParent(Util.logger); commandSender = mock(CommandSender.class); doAnswer(new Answer() { + @Override public Void answer(InvocationOnMock invocation) throws Throwable { commandSenderLogger.info(ChatColor.stripColor((String) invocation.getArguments()[0])); return null;