diff --git a/Bukkit/build.gradle b/Bukkit/build.gradle new file mode 100644 index 000000000..bf5ea7e95 --- /dev/null +++ b/Bukkit/build.gradle @@ -0,0 +1,26 @@ +apply plugin: 'eclipse' +apply plugin: 'idea' + +dependencies { + compile project(':Core') + compile 'org.bukkit:bukkit:1.8.8-R0.1-SNAPSHOT' + compile 'net.milkbowl.vault:VaultAPI:1.5' +} + +processResources { + from('src/main/resources') { + include 'plugin.yml' + expand( + name: project.parent.name, + version: project.parent.version + ) + } +} + +shadowJar { + dependencies { + include(dependency(':Core')) + } +} + +build.dependsOn(shadowJar) \ No newline at end of file diff --git a/src/main/java/com/intellectualcrafters/plot/api/PlotAPI.java b/Bukkit/src/main/java/com/intellectualcrafters/plot/api/PlotAPI.java similarity index 96% rename from src/main/java/com/intellectualcrafters/plot/api/PlotAPI.java rename to Bukkit/src/main/java/com/intellectualcrafters/plot/api/PlotAPI.java index 89849909e..8583e3dd3 100644 --- a/src/main/java/com/intellectualcrafters/plot/api/PlotAPI.java +++ b/Bukkit/src/main/java/com/intellectualcrafters/plot/api/PlotAPI.java @@ -1,758 +1,758 @@ -//////////////////////////////////////////////////////////////////////////////////////////////////// -// PlotSquared - A plot manager and world generator for the Bukkit API / -// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / -// / -// This program is free software; you can redistribute it and/or modify / -// it under the terms of the GNU General Public License as published by / -// the Free Software Foundation; either version 3 of the License, or / -// (at your option) any later version. / -// / -// This program is distributed in the hope that it will be useful, / -// but WITHOUT ANY WARRANTY; without even the implied warranty of / -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / -// GNU General Public License for more details. / -// / -// You should have received a copy of the GNU General Public License / -// along with this program; if not, write to the Free Software Foundation, / -// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / -// / -// You can contact us via: support@intellectualsites.com / -//////////////////////////////////////////////////////////////////////////////////////////////////// - -package com.intellectualcrafters.plot.api; - -import com.intellectualcrafters.configuration.file.YamlConfiguration; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.commands.MainCommand; -import com.intellectualcrafters.plot.commands.SubCommand; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.flag.AbstractFlag; -import com.intellectualcrafters.plot.flag.FlagManager; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotManager; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.ChunkManager; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.SchematicHandler; -import com.intellectualcrafters.plot.util.SetQueue; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.intellectualcrafters.plot.uuid.UUIDWrapper; -import com.plotsquared.bukkit.util.BukkitUtil; -import org.bukkit.Location; -import org.bukkit.OfflinePlayer; -import org.bukkit.World; -import org.bukkit.entity.Player; -import org.bukkit.plugin.java.JavaPlugin; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; -import java.util.UUID; - -/** - * PlotSquared API - * - - - * @version API 2.0 - * - */ - -public class PlotAPI { - - /** - * Permission that allows for admin access, this permission node will allow the player to use any part of the - * plugin, without limitations. - * @deprecated Use C.PERMISSION_ADMIN.s() instead - */ - @Deprecated - public static final String ADMIN_PERMISSION = C.PERMISSION_ADMIN.s(); - - /** - * @deprecated Use new PlotAPI() instead - */ - @Deprecated - public PlotAPI(final JavaPlugin plugin) {} - - /** - * @see PS - * - * @deprecated Use this class if you just want to do a few simple things.
- * - It will remain stable for future versions of the plugin - * - The PlotPlayer and Plot class should be considered relatively safe - * - For more advanced/intensive tasks you should consider using other classes - * - * - */ - @Deprecated - public PlotAPI() {} - - /** - * Get all plots - * - * @return all plots - * - * @see PS#getPlots() - */ - public Set getAllPlots() { - return PS.get().getPlots(); - } - - /** - * Return all plots for a player - * - * @param player Player, whose plots to search for - * - * @return all plots that a player owns - */ - public Set getPlayerPlots(final Player player) { - return PS.get().getPlots(BukkitUtil.getPlayer(player)); - } - - /** - * Add a plot world - * - * @param plotArea Plot World Object - * @see PS#addPlotArea(PlotArea) - */ - public void addPlotArea(final PlotArea plotArea) { - PS.get().addPlotArea(plotArea); - } - - /** - * @return main configuration - * - * @see PS#config - */ - public YamlConfiguration getConfig() { - return PS.get().config; - } - - /** - * @return storage configuration - * - * @see PS#storage - */ - public YamlConfiguration getStorage() { - return PS.get().storage; - } - - /** - * Get the main class for this plugin
- Contains a lot of fields and methods - not very well organized
- * Only use this if you really need it - * - * @return PlotSquared PlotSquared Main Class - * - * @see PS - */ - public PS getMain() { - return PS.get(); - } - - /** - * ChunkManager class contains several useful methods
- * - Chunk deletion
- * - Moving or copying regions
- * - plot swapping
- * - Entity tracking
- * - region regeneration
- * - * @return ChunkManager - * - * @see com.intellectualcrafters.plot.util.ChunkManager - */ - public ChunkManager getChunkManager() { - return ChunkManager.manager; - } - - /** - * Get the block/biome set queue - * @return SetQueue.IMP - */ - public SetQueue getSetQueue() { - return SetQueue.IMP; - } - - /** - * UUIDWrapper class has basic methods for getting UUIDS (it's recommended to use the UUIDHandler class instead) - * - * @return UUIDWrapper - * - * @see com.intellectualcrafters.plot.uuid.UUIDWrapper - */ - public UUIDWrapper getUUIDWrapper() { - return UUIDHandler.getUUIDWrapper(); - } - - /** - * Do not use this. Instead use FlagManager.[method] in your code. - * - Flag related stuff - * - * @return FlagManager - * - * @see com.intellectualcrafters.plot.flag.FlagManager - */ - @Deprecated - public FlagManager getFlagManager() { - return new FlagManager(); - } - - /** - * Do not use this. Instead use MainUtil.[method] in your code. - * - Basic plot management stuff - * - * @return MainUtil - * - * @see MainUtil - */ - @Deprecated - public MainUtil getMainUtil() { - return new MainUtil(); - } - - /** - * Do not use this. Instead use C.PERMISSION_[method] in your code. - * - Basic permission management stuff - * - * @return Array of strings - * - * @see com.intellectualcrafters.plot.util.Permissions - */ - @Deprecated - public String[] getPermissions() { - final ArrayList perms = new ArrayList<>(); - for (final C c : C.values()) { - if ("static.permissions".equals(c.getCat())) { - perms.add(c.s()); - } - } - return perms.toArray(new String[perms.size()]); - } - - /** - * SchematicHandler class contains methods related to pasting, reading and writing schematics - * - * @return SchematicHandler - * - * @see com.intellectualcrafters.plot.util.SchematicHandler - */ - public SchematicHandler getSchematicHandler() { - return SchematicHandler.manager; - } - - /** - * Use C.[caption] instead - * - * @return C - * - * @see com.intellectualcrafters.plot.config.C - */ - @Deprecated - public C[] getCaptions() { - return C.values(); - } - - /** - * Get the plot manager for a world. - Most of these methods can be accessed through the MainUtil - * - * @param world Which manager to get - * - * @return PlotManager - * - * @see com.intellectualcrafters.plot.object.PlotManager - * @see PS#getPlotManager(Plot) - */ - @Deprecated - public PlotManager getPlotManager(final World world) { - if (world == null) { - return null; - } - return getPlotManager(world.getName()); - } - - public Set getPlotAreas(World world) { - if (world == null) { - return new HashSet<>(); - } - return PS.get().getPlotAreas(world.getName()); - } - - /** - * Get the plot manager for a world. - Contains useful low level methods for plot merging, clearing, and - * tessellation - * - * @param world - * - * @return PlotManager - * - * @see PS#getPlotManager(Plot) - * @see com.intellectualcrafters.plot.object.PlotManager - */ - @Deprecated - public PlotManager getPlotManager(final String world) { - Set areas = PS.get().getPlotAreas(world); - switch (areas.size()) { - case 0: - return null; - case 1: - return areas.iterator().next().manager; - default: - PS.debug("PlotAPI#getPlotManager(org.bukkit.World) is deprecated and doesn't support multi plot area worlds."); - return null; - } - } - - /** - * Get the settings for a world (settings bundled in PlotArea class) - You will need to downcast for the specific - * settings a Generator has. e.g. DefaultPlotWorld class implements PlotArea - * - * @param world (to get settings of) - * - * @return PlotArea class for that world ! will return null if not a plot world world - * - * @see #getPlotAreas(World) - * @see com.intellectualcrafters.plot.object.PlotArea - */ - @Deprecated - public PlotArea getWorldSettings(final World world) { - if (world == null) { - return null; - } - return getWorldSettings(world.getName()); - } - - /** - * Get the settings for a world (settings bundled in PlotArea class) - * - * @param world (to get settings of) - * - * @return PlotArea class for that world ! will return null if not a plot world world - * - * @see PS#getPlotArea(String, String) - * @see com.intellectualcrafters.plot.object.PlotArea - */ - @Deprecated - public PlotArea getWorldSettings(final String world) { - if (world == null) { - return null; - } - Set areas = PS.get().getPlotAreas(world); - switch (areas.size()) { - case 0: - return null; - case 1: - return areas.iterator().next(); - default: - PS.debug("PlotAPI#getWorldSettings(org.bukkit.World) is deprecated and doesn't support multi plot area worlds."); - return null; - } - } - - /** - * Send a message to a player. - * - * @param player Player that will receive the message - * @param c (Caption) - * - * @see MainUtil#sendMessage(PlotPlayer, C, String...) - * com.intellectualcrafters.plot.config.C, String...) - */ - public void sendMessage(final Player player, final C c) { - MainUtil.sendMessage(BukkitUtil.getPlayer(player), c); - } - - /** - * Send a message to a player. - Supports color codes - * - * @param player Player that will receive the message - * @param string The message - * - * @see MainUtil#sendMessage(PlotPlayer, String) - */ - public void sendMessage(final Player player, final String string) { - MainUtil.sendMessage(BukkitUtil.getPlayer(player), string); - } - - /** - * Send a message to the console. - Supports color codes - * - * @param msg Message that should be sent to the console - * - * @see MainUtil#sendConsoleMessage(C, String...) - */ - public void sendConsoleMessage(final String msg) { - PS.log(msg); - } - - /** - * Send a message to the console - * - * @param c (Caption) - * - * @see #sendConsoleMessage(String) - * @see com.intellectualcrafters.plot.config.C - */ - public void sendConsoleMessage(final C c) { - sendConsoleMessage(c.s()); - } - - /** - * Register a flag for use in plots - * - * @param flag Flag that should be registered - * - * @see com.intellectualcrafters.plot.flag.FlagManager#addFlag(com.intellectualcrafters.plot.flag.AbstractFlag) - * @see com.intellectualcrafters.plot.flag.AbstractFlag - */ - public void addFlag(final AbstractFlag flag) { - FlagManager.addFlag(flag); - } - - /** - * get all the currently registered flags - * - * @return array of Flag[] - * - * @see com.intellectualcrafters.plot.flag.FlagManager#getFlags() - * @see com.intellectualcrafters.plot.flag.AbstractFlag - */ - public AbstractFlag[] getFlags() { - return FlagManager.getFlags().toArray(new AbstractFlag[FlagManager.getFlags().size()]); - } - - /** - * Get a plot based on the ID - * - * @param world World in which the plot is located - * @param x Plot Location X Co-ord - * @param z Plot Location Z Co-ord - * - * @return plot, null if ID is wrong - * - * @see PlotArea#getPlot(PlotId) - */ - @Deprecated - public Plot getPlot(final World world, final int x, final int z) { - if (world == null) { - return null; - } - PlotArea area = getWorldSettings(world); - if (area == null) { - return null; - } - return area.getPlot(new PlotId(x, z)); - } - - /** - * Get a plot based on the location - * - * @param l The location that you want to to retrieve the plot from - * - * @return plot if found, otherwise it creates a temporary plot- - * - * @see Plot - */ - public Plot getPlot(final Location l) { - if (l == null) { - return null; - } - return BukkitUtil.getLocation(l).getPlot(); - } - - /** - * Get a plot based on the player location - * - * @param player Get the current plot for the player location - * - * @return plot if found, otherwise it creates a temporary plot - * - * @see #getPlot(org.bukkit.Location) - * @see Plot - */ - public Plot getPlot(final Player player) { - return this.getPlot(player.getLocation()); - } - - /** - * Check whether or not a player has a plot - * - * @param player Player that you want to check for - * - * @return true if player has a plot, false if not. - * - * @see #getPlots(World, Player, boolean) - */ - @Deprecated - public boolean hasPlot(final World world, final Player player) { - return getPlots(world, player, true) != null && getPlots(world, player, true).length > 0; - } - - /** - * Get all plots for the player - * - * @param plr to search for - * @param just_owner should we just search for owner? Or with rights? - */ - @Deprecated - public Plot[] getPlots(final World world, final Player plr, final boolean just_owner) { - final ArrayList pPlots = new ArrayList<>(); - UUID uuid = BukkitUtil.getPlayer(plr).getUUID(); - for (final Plot plot : PS.get().getPlots(world.getName())) { - if (just_owner) { - if (plot.hasOwner() && plot.isOwner(uuid)) { - pPlots.add(plot); - } - } else { - if (plot.isAdded(uuid)) { - pPlots.add(plot); - } - } - } - return pPlots.toArray(new Plot[pPlots.size()]); - } - - /** - * Get all plots for the world - * - * @param world to get plots of - * - * @return Plot[] - array of plot objects in world - * - * @see PS#getPlots(String) - * @see Plot - */ - @Deprecated - public Plot[] getPlots(final World world) { - if (world == null) { - return new Plot[0]; - } - Collection plots = PS.get().getPlots(world.getName()); - return plots.toArray(new Plot[plots.size()]); - } - - /** - * Get all plot worlds - * - * @return World[] - array of plot worlds - * - */ - @Deprecated - public String[] getPlotWorlds() { - Set plotWorldStrings = PS.get().getPlotWorldStrings(); - return plotWorldStrings.toArray(new String[plotWorldStrings.size()]); - } - - /** - * Get if plot world - * - * @param world (to check if plot world) - * - * @return boolean (if plot world or not) - * - * @see PS#hasPlotArea(String) - */ - @Deprecated - public boolean isPlotWorld(final World world) { - return PS.get().hasPlotArea(world.getName()); - } - - /** - * Get plot locations - * - * @param p Plot that you want to get the locations for - * - * @return [0] = bottomLc, [1] = topLoc, [2] = home - * - * @deprecated As merged plots may not have a rectangular shape - * - * @see Plot - */ - @Deprecated - public Location[] getLocations(final Plot p) { - return new Location[] { BukkitUtil.getLocation(p.getBottom()), BukkitUtil.getLocation(p.getTop()), BukkitUtil.getLocation(p.getHome()) }; - } - - /** - * Get home location - * - * @param p Plot that you want to get the location for - * - * @return plot bottom location - * - * @see Plot - */ - public Location getHomeLocation(final Plot p) { - return BukkitUtil.getLocation(p.getHome()); - } - - /** - * Get Bottom Location (min, min, min) - * - * @param p Plot that you want to get the location for - * - * @return plot bottom location - * - * @deprecated As merged plots may not have a rectangular shape - * - * @see Plot - */ - @Deprecated - public Location getBottomLocation(final Plot p) { - return BukkitUtil.getLocation(p.getBottom()); - } - - /** - * Get Top Location (max, max, max) - * - * @param p Plot that you want to get the location for - * - * @return plot top location - * - * @deprecated As merged plots may not have a rectangular shape - * - * @see Plot - */ - @Deprecated - public Location getTopLocation(final Plot p) { - return BukkitUtil.getLocation(p.getTop()); - } - - /** - * Check whether or not a player is in a plot - * - * @param player who we're checking for - * - * @return true if the player is in a plot, false if not- - * - */ - public boolean isInPlot(final Player player) { - return getPlot(player) != null; - } - - /** - * Register a subcommand - * - * @param c SubCommand, that we want to register - * - * @see com.intellectualcrafters.plot.commands.SubCommand - */ - public void registerCommand(final SubCommand c) { - if (c.getCommand() != null) { - MainCommand.getInstance().addCommand(c); - } else { - MainCommand.getInstance().createCommand(c); - } - } - - /** - * Get the PlotSquared class - * - * @return PlotSquared Class - * - * @see PS - */ - public PS getPlotSquared() { - return PS.get(); - } - - /** - * Get the player plot count - * - * @param world Specify the world we want to select the plots from - * @param player Player, for whom we're getting the plot count - * - * @return the number of plots the player has - * - */ - public int getPlayerPlotCount(final World world, final Player player) { - if (world == null) { - return 0; - } - return BukkitUtil.getPlayer(player).getPlotCount(world.getName()); - } - - /** - * Get a collection containing the players plots - * - * @param world Specify the world we want to select the plots from - * @param player Player, for whom we're getting the plots - * - * @return a set containing the players plots - * - * @see PS#getPlots(String, PlotPlayer) - * - * @see Plot - */ - public Set getPlayerPlots(final World world, final Player player) { - if (world == null) { - return new HashSet<>(); - } - return BukkitUtil.getPlayer(player).getPlots(world.getName()); - } - - /** - * Get the numbers of plots, which the player is able to build in - * - * @param player Player, for whom we're getting the plots (trusted, member and owner) - * - * @return the number of allowed plots - * - */ - public int getAllowedPlots(final Player player) { - final PlotPlayer pp = BukkitUtil.getPlayer(player); - return pp.getAllowedPlots(); - } - - /** - * Get the PlotPlayer for a player
- * - The PlotPlayer is usually cached and will provide useful functions relating to players - * - * @see PlotPlayer#wrap(Object) - * - * @param player - * @return - */ - public PlotPlayer wrapPlayer(final Player player) { - return PlotPlayer.wrap(player); - } - - /** - * Get the PlotPlayer for a UUID (Please note that PlotSquared can be configured to provide different UUIDs than bukkit) - * - * @see PlotPlayer#wrap(Object) - * - * @param uuid - * @return - */ - public PlotPlayer wrapPlayer(final UUID uuid) { - return PlotPlayer.wrap(uuid); - } - - /** - * Get the PlotPlayer for a username - * - * @see PlotPlayer#wrap(Object) - * - * @param player - * @return - */ - public PlotPlayer wrapPlayer(final String player) { - return PlotPlayer.wrap(player); - } - - /** - * Get the PlotPlayer for an offline player
- * Note that this will work if the player is offline, however not all functionality will work - * - * @see PlotPlayer#wrap(Object) - * - * @param player - * @return - */ - public PlotPlayer wrapPlayer(final OfflinePlayer player) { - return PlotPlayer.wrap(player); - } -} +//////////////////////////////////////////////////////////////////////////////////////////////////// +// PlotSquared - A plot manager and world generator for the Bukkit API / +// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / +// / +// This program is free software; you can redistribute it and/or modify / +// it under the terms of the GNU General Public License as published by / +// the Free Software Foundation; either version 3 of the License, or / +// (at your option) any later version. / +// / +// This program is distributed in the hope that it will be useful, / +// but WITHOUT ANY WARRANTY; without even the implied warranty of / +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / +// GNU General Public License for more details. / +// / +// You should have received a copy of the GNU General Public License / +// along with this program; if not, write to the Free Software Foundation, / +// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / +// / +// You can contact us via: support@intellectualsites.com / +//////////////////////////////////////////////////////////////////////////////////////////////////// + +package com.intellectualcrafters.plot.api; + +import com.intellectualcrafters.configuration.file.YamlConfiguration; +import com.intellectualcrafters.plot.PS; +import com.intellectualcrafters.plot.commands.MainCommand; +import com.intellectualcrafters.plot.commands.SubCommand; +import com.intellectualcrafters.plot.config.C; +import com.intellectualcrafters.plot.flag.AbstractFlag; +import com.intellectualcrafters.plot.flag.FlagManager; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotArea; +import com.intellectualcrafters.plot.object.PlotId; +import com.intellectualcrafters.plot.object.PlotManager; +import com.intellectualcrafters.plot.object.PlotPlayer; +import com.intellectualcrafters.plot.util.ChunkManager; +import com.intellectualcrafters.plot.util.MainUtil; +import com.intellectualcrafters.plot.util.SchematicHandler; +import com.intellectualcrafters.plot.util.SetQueue; +import com.intellectualcrafters.plot.util.UUIDHandler; +import com.intellectualcrafters.plot.uuid.UUIDWrapper; +import com.plotsquared.bukkit.util.BukkitUtil; +import org.bukkit.Location; +import org.bukkit.OfflinePlayer; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; + +/** + * PlotSquared API + * + + + * @version API 2.0 + * + */ + +public class PlotAPI { + + /** + * Permission that allows for admin access, this permission node will allow the player to use any part of the + * plugin, without limitations. + * @deprecated Use C.PERMISSION_ADMIN.s() instead + */ + @Deprecated + public static final String ADMIN_PERMISSION = C.PERMISSION_ADMIN.s(); + + /** + * @deprecated Use new PlotAPI() instead + */ + @Deprecated + public PlotAPI(final JavaPlugin plugin) {} + + /** + * @see PS + * + * @deprecated Use this class if you just want to do a few simple things.
+ * - It will remain stable for future versions of the plugin + * - The PlotPlayer and Plot class should be considered relatively safe + * - For more advanced/intensive tasks you should consider using other classes + * + * + */ + @Deprecated + public PlotAPI() {} + + /** + * Get all plots + * + * @return all plots + * + * @see PS#getPlots() + */ + public Set getAllPlots() { + return PS.get().getPlots(); + } + + /** + * Return all plots for a player + * + * @param player Player, whose plots to search for + * + * @return all plots that a player owns + */ + public Set getPlayerPlots(final Player player) { + return PS.get().getPlots(BukkitUtil.getPlayer(player)); + } + + /** + * Add a plot world + * + * @param plotArea Plot World Object + * @see PS#addPlotArea(PlotArea) + */ + public void addPlotArea(final PlotArea plotArea) { + PS.get().addPlotArea(plotArea); + } + + /** + * @return main configuration + * + * @see PS#config + */ + public YamlConfiguration getConfig() { + return PS.get().config; + } + + /** + * @return storage configuration + * + * @see PS#storage + */ + public YamlConfiguration getStorage() { + return PS.get().storage; + } + + /** + * Get the main class for this plugin
- Contains a lot of fields and methods - not very well organized
+ * Only use this if you really need it + * + * @return PlotSquared PlotSquared Main Class + * + * @see PS + */ + public PS getMain() { + return PS.get(); + } + + /** + * ChunkManager class contains several useful methods
+ * - Chunk deletion
+ * - Moving or copying regions
+ * - plot swapping
+ * - Entity tracking
+ * - region regeneration
+ * + * @return ChunkManager + * + * @see com.intellectualcrafters.plot.util.ChunkManager + */ + public ChunkManager getChunkManager() { + return ChunkManager.manager; + } + + /** + * Get the block/biome set queue + * @return SetQueue.IMP + */ + public SetQueue getSetQueue() { + return SetQueue.IMP; + } + + /** + * UUIDWrapper class has basic methods for getting UUIDS (it's recommended to use the UUIDHandler class instead) + * + * @return UUIDWrapper + * + * @see com.intellectualcrafters.plot.uuid.UUIDWrapper + */ + public UUIDWrapper getUUIDWrapper() { + return UUIDHandler.getUUIDWrapper(); + } + + /** + * Do not use this. Instead use FlagManager.[method] in your code. + * - Flag related stuff + * + * @return FlagManager + * + * @see com.intellectualcrafters.plot.flag.FlagManager + */ + @Deprecated + public FlagManager getFlagManager() { + return new FlagManager(); + } + + /** + * Do not use this. Instead use MainUtil.[method] in your code. + * - Basic plot management stuff + * + * @return MainUtil + * + * @see MainUtil + */ + @Deprecated + public MainUtil getMainUtil() { + return new MainUtil(); + } + + /** + * Do not use this. Instead use C.PERMISSION_[method] in your code. + * - Basic permission management stuff + * + * @return Array of strings + * + * @see com.intellectualcrafters.plot.util.Permissions + */ + @Deprecated + public String[] getPermissions() { + final ArrayList perms = new ArrayList<>(); + for (final C c : C.values()) { + if ("static.permissions".equals(c.getCat())) { + perms.add(c.s()); + } + } + return perms.toArray(new String[perms.size()]); + } + + /** + * SchematicHandler class contains methods related to pasting, reading and writing schematics + * + * @return SchematicHandler + * + * @see com.intellectualcrafters.plot.util.SchematicHandler + */ + public SchematicHandler getSchematicHandler() { + return SchematicHandler.manager; + } + + /** + * Use C.[caption] instead + * + * @return C + * + * @see com.intellectualcrafters.plot.config.C + */ + @Deprecated + public C[] getCaptions() { + return C.values(); + } + + /** + * Get the plot manager for a world. - Most of these methods can be accessed through the MainUtil + * + * @param world Which manager to get + * + * @return PlotManager + * + * @see com.intellectualcrafters.plot.object.PlotManager + * @see PS#getPlotManager(Plot) + */ + @Deprecated + public PlotManager getPlotManager(final World world) { + if (world == null) { + return null; + } + return getPlotManager(world.getName()); + } + + public Set getPlotAreas(World world) { + if (world == null) { + return new HashSet<>(); + } + return PS.get().getPlotAreas(world.getName()); + } + + /** + * Get the plot manager for a world. - Contains useful low level methods for plot merging, clearing, and + * tessellation + * + * @param world + * + * @return PlotManager + * + * @see PS#getPlotManager(Plot) + * @see com.intellectualcrafters.plot.object.PlotManager + */ + @Deprecated + public PlotManager getPlotManager(final String world) { + Set areas = PS.get().getPlotAreas(world); + switch (areas.size()) { + case 0: + return null; + case 1: + return areas.iterator().next().manager; + default: + PS.debug("PlotAPI#getPlotManager(org.bukkit.World) is deprecated and doesn't support multi plot area worlds."); + return null; + } + } + + /** + * Get the settings for a world (settings bundled in PlotArea class) - You will need to downcast for the specific + * settings a Generator has. e.g. DefaultPlotWorld class implements PlotArea + * + * @param world (to get settings of) + * + * @return PlotArea class for that world ! will return null if not a plot world world + * + * @see #getPlotAreas(World) + * @see com.intellectualcrafters.plot.object.PlotArea + */ + @Deprecated + public PlotArea getWorldSettings(final World world) { + if (world == null) { + return null; + } + return getWorldSettings(world.getName()); + } + + /** + * Get the settings for a world (settings bundled in PlotArea class) + * + * @param world (to get settings of) + * + * @return PlotArea class for that world ! will return null if not a plot world world + * + * @see PS#getPlotArea(String, String) + * @see com.intellectualcrafters.plot.object.PlotArea + */ + @Deprecated + public PlotArea getWorldSettings(final String world) { + if (world == null) { + return null; + } + Set areas = PS.get().getPlotAreas(world); + switch (areas.size()) { + case 0: + return null; + case 1: + return areas.iterator().next(); + default: + PS.debug("PlotAPI#getWorldSettings(org.bukkit.World) is deprecated and doesn't support multi plot area worlds."); + return null; + } + } + + /** + * Send a message to a player. + * + * @param player Player that will receive the message + * @param c (Caption) + * + * @see MainUtil#sendMessage(PlotPlayer, C, String...) + * com.intellectualcrafters.plot.config.C, String...) + */ + public void sendMessage(final Player player, final C c) { + MainUtil.sendMessage(BukkitUtil.getPlayer(player), c); + } + + /** + * Send a message to a player. - Supports color codes + * + * @param player Player that will receive the message + * @param string The message + * + * @see MainUtil#sendMessage(PlotPlayer, String) + */ + public void sendMessage(final Player player, final String string) { + MainUtil.sendMessage(BukkitUtil.getPlayer(player), string); + } + + /** + * Send a message to the console. - Supports color codes + * + * @param msg Message that should be sent to the console + * + * @see MainUtil#sendConsoleMessage(C, String...) + */ + public void sendConsoleMessage(final String msg) { + PS.log(msg); + } + + /** + * Send a message to the console + * + * @param c (Caption) + * + * @see #sendConsoleMessage(String) + * @see com.intellectualcrafters.plot.config.C + */ + public void sendConsoleMessage(final C c) { + sendConsoleMessage(c.s()); + } + + /** + * Register a flag for use in plots + * + * @param flag Flag that should be registered + * + * @see com.intellectualcrafters.plot.flag.FlagManager#addFlag(com.intellectualcrafters.plot.flag.AbstractFlag) + * @see com.intellectualcrafters.plot.flag.AbstractFlag + */ + public void addFlag(final AbstractFlag flag) { + FlagManager.addFlag(flag); + } + + /** + * get all the currently registered flags + * + * @return array of Flag[] + * + * @see com.intellectualcrafters.plot.flag.FlagManager#getFlags() + * @see com.intellectualcrafters.plot.flag.AbstractFlag + */ + public AbstractFlag[] getFlags() { + return FlagManager.getFlags().toArray(new AbstractFlag[FlagManager.getFlags().size()]); + } + + /** + * Get a plot based on the ID + * + * @param world World in which the plot is located + * @param x Plot Location X Co-ord + * @param z Plot Location Z Co-ord + * + * @return plot, null if ID is wrong + * + * @see PlotArea#getPlot(PlotId) + */ + @Deprecated + public Plot getPlot(final World world, final int x, final int z) { + if (world == null) { + return null; + } + PlotArea area = getWorldSettings(world); + if (area == null) { + return null; + } + return area.getPlot(new PlotId(x, z)); + } + + /** + * Get a plot based on the location + * + * @param l The location that you want to to retrieve the plot from + * + * @return plot if found, otherwise it creates a temporary plot- + * + * @see Plot + */ + public Plot getPlot(final Location l) { + if (l == null) { + return null; + } + return BukkitUtil.getLocation(l).getPlot(); + } + + /** + * Get a plot based on the player location + * + * @param player Get the current plot for the player location + * + * @return plot if found, otherwise it creates a temporary plot + * + * @see #getPlot(org.bukkit.Location) + * @see Plot + */ + public Plot getPlot(final Player player) { + return this.getPlot(player.getLocation()); + } + + /** + * Check whether or not a player has a plot + * + * @param player Player that you want to check for + * + * @return true if player has a plot, false if not. + * + * @see #getPlots(World, Player, boolean) + */ + @Deprecated + public boolean hasPlot(final World world, final Player player) { + return getPlots(world, player, true) != null && getPlots(world, player, true).length > 0; + } + + /** + * Get all plots for the player + * + * @param plr to search for + * @param just_owner should we just search for owner? Or with rights? + */ + @Deprecated + public Plot[] getPlots(final World world, final Player plr, final boolean just_owner) { + final ArrayList pPlots = new ArrayList<>(); + UUID uuid = BukkitUtil.getPlayer(plr).getUUID(); + for (final Plot plot : PS.get().getPlots(world.getName())) { + if (just_owner) { + if (plot.hasOwner() && plot.isOwner(uuid)) { + pPlots.add(plot); + } + } else { + if (plot.isAdded(uuid)) { + pPlots.add(plot); + } + } + } + return pPlots.toArray(new Plot[pPlots.size()]); + } + + /** + * Get all plots for the world + * + * @param world to get plots of + * + * @return Plot[] - array of plot objects in world + * + * @see PS#getPlots(String) + * @see Plot + */ + @Deprecated + public Plot[] getPlots(final World world) { + if (world == null) { + return new Plot[0]; + } + Collection plots = PS.get().getPlots(world.getName()); + return plots.toArray(new Plot[plots.size()]); + } + + /** + * Get all plot worlds + * + * @return World[] - array of plot worlds + * + */ + @Deprecated + public String[] getPlotWorlds() { + Set plotWorldStrings = PS.get().getPlotWorldStrings(); + return plotWorldStrings.toArray(new String[plotWorldStrings.size()]); + } + + /** + * Get if plot world + * + * @param world (to check if plot world) + * + * @return boolean (if plot world or not) + * + * @see PS#hasPlotArea(String) + */ + @Deprecated + public boolean isPlotWorld(final World world) { + return PS.get().hasPlotArea(world.getName()); + } + + /** + * Get plot locations + * + * @param p Plot that you want to get the locations for + * + * @return [0] = bottomLc, [1] = topLoc, [2] = home + * + * @deprecated As merged plots may not have a rectangular shape + * + * @see Plot + */ + @Deprecated + public Location[] getLocations(final Plot p) { + return new Location[] { BukkitUtil.getLocation(p.getBottom()), BukkitUtil.getLocation(p.getTop()), BukkitUtil.getLocation(p.getHome()) }; + } + + /** + * Get home location + * + * @param p Plot that you want to get the location for + * + * @return plot bottom location + * + * @see Plot + */ + public Location getHomeLocation(final Plot p) { + return BukkitUtil.getLocation(p.getHome()); + } + + /** + * Get Bottom Location (min, min, min) + * + * @param p Plot that you want to get the location for + * + * @return plot bottom location + * + * @deprecated As merged plots may not have a rectangular shape + * + * @see Plot + */ + @Deprecated + public Location getBottomLocation(final Plot p) { + return BukkitUtil.getLocation(p.getBottom()); + } + + /** + * Get Top Location (max, max, max) + * + * @param p Plot that you want to get the location for + * + * @return plot top location + * + * @deprecated As merged plots may not have a rectangular shape + * + * @see Plot + */ + @Deprecated + public Location getTopLocation(final Plot p) { + return BukkitUtil.getLocation(p.getTop()); + } + + /** + * Check whether or not a player is in a plot + * + * @param player who we're checking for + * + * @return true if the player is in a plot, false if not- + * + */ + public boolean isInPlot(final Player player) { + return getPlot(player) != null; + } + + /** + * Register a subcommand + * + * @param c SubCommand, that we want to register + * + * @see com.intellectualcrafters.plot.commands.SubCommand + */ + public void registerCommand(final SubCommand c) { + if (c.getCommand() != null) { + MainCommand.getInstance().addCommand(c); + } else { + MainCommand.getInstance().createCommand(c); + } + } + + /** + * Get the PlotSquared class + * + * @return PlotSquared Class + * + * @see PS + */ + public PS getPlotSquared() { + return PS.get(); + } + + /** + * Get the player plot count + * + * @param world Specify the world we want to select the plots from + * @param player Player, for whom we're getting the plot count + * + * @return the number of plots the player has + * + */ + public int getPlayerPlotCount(final World world, final Player player) { + if (world == null) { + return 0; + } + return BukkitUtil.getPlayer(player).getPlotCount(world.getName()); + } + + /** + * Get a collection containing the players plots + * + * @param world Specify the world we want to select the plots from + * @param player Player, for whom we're getting the plots + * + * @return a set containing the players plots + * + * @see PS#getPlots(String, PlotPlayer) + * + * @see Plot + */ + public Set getPlayerPlots(final World world, final Player player) { + if (world == null) { + return new HashSet<>(); + } + return BukkitUtil.getPlayer(player).getPlots(world.getName()); + } + + /** + * Get the numbers of plots, which the player is able to build in + * + * @param player Player, for whom we're getting the plots (trusted, member and owner) + * + * @return the number of allowed plots + * + */ + public int getAllowedPlots(final Player player) { + final PlotPlayer pp = BukkitUtil.getPlayer(player); + return pp.getAllowedPlots(); + } + + /** + * Get the PlotPlayer for a player
+ * - The PlotPlayer is usually cached and will provide useful functions relating to players + * + * @see PlotPlayer#wrap(Object) + * + * @param player + * @return + */ + public PlotPlayer wrapPlayer(final Player player) { + return PlotPlayer.wrap(player); + } + + /** + * Get the PlotPlayer for a UUID (Please note that PlotSquared can be configured to provide different UUIDs than bukkit) + * + * @see PlotPlayer#wrap(Object) + * + * @param uuid + * @return + */ + public PlotPlayer wrapPlayer(final UUID uuid) { + return PlotPlayer.wrap(uuid); + } + + /** + * Get the PlotPlayer for a username + * + * @see PlotPlayer#wrap(Object) + * + * @param player + * @return + */ + public PlotPlayer wrapPlayer(final String player) { + return PlotPlayer.wrap(player); + } + + /** + * Get the PlotPlayer for an offline player
+ * Note that this will work if the player is offline, however not all functionality will work + * + * @see PlotPlayer#wrap(Object) + * + * @param player + * @return + */ + public PlotPlayer wrapPlayer(final OfflinePlayer player) { + return PlotPlayer.wrap(player); + } +} diff --git a/src/main/java/com/plotsquared/bukkit/BukkitMain.java b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/BukkitMain.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java diff --git a/src/main/java/com/plotsquared/bukkit/chat/ArrayWrapper.java b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/ArrayWrapper.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/chat/ArrayWrapper.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/chat/ArrayWrapper.java diff --git a/src/main/java/com/plotsquared/bukkit/chat/FancyMessage.java b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/FancyMessage.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/chat/FancyMessage.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/chat/FancyMessage.java diff --git a/src/main/java/com/plotsquared/bukkit/chat/JsonRepresentedObject.java b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonRepresentedObject.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/chat/JsonRepresentedObject.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonRepresentedObject.java diff --git a/src/main/java/com/plotsquared/bukkit/chat/JsonString.java b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonString.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/chat/JsonString.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonString.java diff --git a/src/main/java/com/plotsquared/bukkit/chat/MessagePart.java b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/MessagePart.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/chat/MessagePart.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/chat/MessagePart.java diff --git a/src/main/java/com/plotsquared/bukkit/chat/Reflection.java b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/Reflection.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/chat/Reflection.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/chat/Reflection.java diff --git a/src/main/java/com/plotsquared/bukkit/chat/TextualComponent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/TextualComponent.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/chat/TextualComponent.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/chat/TextualComponent.java diff --git a/src/main/java/com/plotsquared/bukkit/commands/DebugUUID.java b/Bukkit/src/main/java/com/plotsquared/bukkit/commands/DebugUUID.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/commands/DebugUUID.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/commands/DebugUUID.java diff --git a/src/main/java/com/plotsquared/bukkit/database/plotme/APlotMeConnector.java b/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/APlotMeConnector.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/database/plotme/APlotMeConnector.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/APlotMeConnector.java diff --git a/src/main/java/com/plotsquared/bukkit/database/plotme/ClassicPlotMeConnector.java b/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/ClassicPlotMeConnector.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/database/plotme/ClassicPlotMeConnector.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/ClassicPlotMeConnector.java diff --git a/src/main/java/com/plotsquared/bukkit/database/plotme/LikePlotMeConverter.java b/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/LikePlotMeConverter.java similarity index 98% rename from src/main/java/com/plotsquared/bukkit/database/plotme/LikePlotMeConverter.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/LikePlotMeConverter.java index 5f6fd9b09..2028d2db0 100644 --- a/src/main/java/com/plotsquared/bukkit/database/plotme/LikePlotMeConverter.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/LikePlotMeConverter.java @@ -1,404 +1,404 @@ -//////////////////////////////////////////////////////////////////////////////////////////////////// -// PlotSquared - A plot manager and world generator for the Bukkit API / -// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / -// / -// This program is free software; you can redistribute it and/or modify / -// it under the terms of the GNU General Public License as published by / -// the Free Software Foundation; either version 3 of the License, or / -// (at your option) any later version. / -// / -// This program is distributed in the hope that it will be useful, / -// but WITHOUT ANY WARRANTY; without even the implied warranty of / -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / -// GNU General Public License for more details. / -// / -// You should have received a copy of the GNU General Public License / -// along with this program; if not, write to the Free Software Foundation, / -// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / -// / -// You can contact us via: support@intellectualsites.com / -//////////////////////////////////////////////////////////////////////////////////////////////////// -package com.plotsquared.bukkit.database.plotme; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.sql.Connection; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map.Entry; -import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.WorldCreator; - -import com.intellectualcrafters.configuration.file.FileConfiguration; -import com.intellectualcrafters.configuration.file.YamlConfiguration; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.generator.HybridGen; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.util.TaskManager; -import com.plotsquared.bukkit.generator.BukkitPlotGenerator; - -/** - * Created 2014-08-17 for PlotSquared - * - - - */ -public class LikePlotMeConverter { - private final String plugin; - - /** - * Constructor - * - * @param plugin Plugin Used to run the converter - */ - public LikePlotMeConverter(final String plugin) { - this.plugin = plugin; - } - - public static String getWorld(final String world) { - for (final World newworld : Bukkit.getWorlds()) { - if (newworld.getName().equalsIgnoreCase(world)) { - return newworld.getName(); - } - } - return world; - } - - private void sendMessage(final String message) { - PS.debug("&3PlotMe&8->&3PlotSquared&8: &7" + message); - } - - public String getPlotMePath() { - return new File(".").getAbsolutePath() + File.separator + "plugins" + File.separator + plugin + File.separator; - } - - public String getAthionPlotsPath() { - return new File(".").getAbsolutePath() + File.separator + "plugins" + File.separator + plugin + File.separator; - } - - public FileConfiguration getPlotMeConfig(final String dataFolder) { - final File plotMeFile = new File(dataFolder + "config.yml"); - if (!plotMeFile.exists()) { - return null; - } - return YamlConfiguration.loadConfiguration(plotMeFile); - } - - public Set getPlotMeWorlds(final FileConfiguration plotConfig) { - return plotConfig.getConfigurationSection("worlds").getKeys(false); - } - - public void mergeWorldYml(final String plugin, FileConfiguration plotConfig) { - try { - File genConfig = new File("plugins" + File.separator + plugin + File.separator + "PlotMe-DefaultGenerator" + File.separator + "config.yml"); - if (genConfig.exists()) { - YamlConfiguration yml = YamlConfiguration.loadConfiguration(genConfig); - for (String key : yml.getKeys(true)) { - if (!plotConfig.contains(key)) { - plotConfig.set(key, yml.get(key)); - } - } - genConfig.delete(); - } - } - catch (Exception e) { - e.printStackTrace(); - } - } - - public void updateWorldYml(final String plugin, final String location) { - try { - final Path path = Paths.get(location); - final File file = new File(location); - if (!file.exists()) { - return; - } - final Charset charset = StandardCharsets.UTF_8; - String content = new String(Files.readAllBytes(path), charset); - content = content.replaceAll("PlotMe-DefaultGenerator", "PlotSquared"); - content = content.replaceAll(plugin, "PlotSquared"); - Files.write(path, content.getBytes(charset)); - } catch (IOException e) { - } - } - - public boolean run(final APlotMeConnector connector) { - try { - final String dataFolder = getPlotMePath(); - final FileConfiguration plotConfig = getPlotMeConfig(dataFolder); - if (plotConfig == null) { - return false; - } - - String version = plotConfig.getString("Version"); - if (version == null) { - version = plotConfig.getString("version"); - } - if (!connector.accepts(version)) { - return false; - } - - PS.debug("&3Using connector: " + connector.getClass().getCanonicalName()); - - final Connection connection = connector.getPlotMeConnection(plugin, plotConfig, dataFolder); - - if (!connector.isValidConnection(connection)) { - sendMessage("Cannot connect to PlotMe DB. Conversion process will not continue"); - return false; - } - - sendMessage(plugin + " conversion has started. To disable this, please set 'plotme-convert.enabled' to false in the 'settings.yml'"); - - mergeWorldYml(plugin, plotConfig); - - sendMessage("Connecting to " + plugin + " DB"); - - int plotCount = 0; - final ArrayList createdPlots = new ArrayList<>(); - - sendMessage("Collecting plot data"); - - final String dbPrefix = plugin.toLowerCase(); - sendMessage(" - " + dbPrefix + "Plots"); - final Set worlds = getPlotMeWorlds(plotConfig); - - if (Settings.CONVERT_PLOTME) { - sendMessage("Updating bukkit.yml"); - updateWorldYml(plugin, "bukkit.yml"); - updateWorldYml(plugin, "plugins/Multiverse-Core/worlds.yml"); - for (final String world : plotConfig.getConfigurationSection("worlds").getKeys(false)) { - sendMessage("Copying config for: " + world); - try { - final String actualWorldName = getWorld(world); - connector.copyConfig(plotConfig, world, actualWorldName); - PS.get().config.save(PS.get().configFile); - } catch (final Exception e) { - e.printStackTrace(); - sendMessage("&c-- &lFailed to save configuration for world '" + world + "'\nThis will need to be done using the setup command, or manually"); - } - } - } - final HashMap> plots = connector.getPlotMePlots(connection); - for (final Entry> entry : plots.entrySet()) { - plotCount += entry.getValue().size(); - } - if (!Settings.CONVERT_PLOTME) { - return false; - } - - sendMessage(" - " + dbPrefix + "Allowed"); - - sendMessage("Collected " + plotCount + " plots from PlotMe"); - final File PLOTME_DG_FILE = new File(dataFolder + File.separator + "PlotMe-DefaultGenerator" + File.separator + "config.yml"); - if (PLOTME_DG_FILE.exists()) { - final YamlConfiguration PLOTME_DG_YML = YamlConfiguration.loadConfiguration(PLOTME_DG_FILE); - try { - for (final String world : plots.keySet()) { - final String actualWorldName = getWorld(world); - final String plotMeWorldName = world.toLowerCase(); - Integer pathwidth = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".PathWidth"); // - /* - * TODO: dead code - * - if (pathwidth == null) { - pathwidth = 7; - } - */ - PS.get().config.set("worlds." + world + ".road.width", pathwidth); - - Integer pathheight = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".RoadHeight"); // - if ((pathheight == null) || (pathheight == 0)) { - pathheight = 64; - } - PS.get().config.set("worlds." + world + ".road.height", pathheight); - PS.get().config.set("worlds." + world + ".wall.height", pathheight); - PS.get().config.set("worlds." + world + ".plot.height", pathheight); - Integer plotsize = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".PlotSize"); // - if ((plotsize == null) || (plotsize == 0)) { - plotsize = 32; - } - PS.get().config.set("worlds." + world + ".plot.size", plotsize); - String wallblock = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".WallBlock"); // - if (wallblock == null) { - wallblock = "44"; - } - PS.get().config.set("worlds." + world + ".wall.block", wallblock); - String floor = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".PlotFloorBlock"); // - if (floor == null) { - floor = "2"; - } - PS.get().config.set("worlds." + world + ".plot.floor", Collections.singletonList(floor)); - String filling = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".FillBlock"); // - if (filling == null) { - filling = "3"; - } - PS.get().config.set("worlds." + world + ".plot.filling", Collections.singletonList(filling)); - String road = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".RoadMainBlock"); - if (road == null) { - road = "5"; - } - PS.get().config.set("worlds." + world + ".road.block", road); - Integer height = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".RoadHeight"); // - if (height == 0) { - height = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".GroundHeight"); // - if (height == 0) { - height = 64; - } - } - PS.get().config.set("worlds." + actualWorldName + ".road.height", height); - PS.get().config.set("worlds." + actualWorldName + ".plot.height", height); - PS.get().config.set("worlds." + actualWorldName + ".wall.height", height); - PS.get().config.save(PS.get().configFile); - } - } catch (IOException e) { - } - } - for (Entry> entry : plots.entrySet()) { - String world = entry.getKey(); - PlotArea area = PS.get().getPlotArea(world, null); - int duplicate = 0; - if (area != null) { - for (Entry entry2 : entry.getValue().entrySet()) { - if (area.getOwnedPlotAbs(entry2.getKey()) != null) { - duplicate++; - } else { - createdPlots.add(entry2.getValue()); - } - } - if (duplicate > 0) { - PS.debug("&c[WARNING] Found " + duplicate + " duplicate plots already in DB for world: '" + world + "'. Have you run the converter already?"); - } - } else { - if (PS.get().plots_tmp != null) { - HashMap map = PS.get().plots_tmp.get(world); - if (map != null) { - for (Entry entry2 : entry.getValue().entrySet()) { - if (map.containsKey(entry2.getKey())) { - duplicate++; - } else { - createdPlots.add(entry2.getValue()); - } - } - if (duplicate > 0) { - PS.debug("&c[WARNING] Found " + duplicate + " duplicate plots already in DB for world: '" + world + "'. Have you run the converter already?"); - } - continue; - } - } - createdPlots.addAll(entry.getValue().values()); - } - } - sendMessage("Creating plot DB"); - Thread.sleep(1000); - final AtomicBoolean done = new AtomicBoolean(false); - DBFunc.createPlotsAndData(createdPlots, new Runnable() { - @Override - public void run() { - if (done.get()) { - done(); - sendMessage("&aDatabase conversion is now complete!"); - PS.debug("&c - Stop the server"); - PS.debug("&c - Disable 'plotme-convert.enabled' and 'plotme-convert.cache-uuids' in the settings.yml"); - PS.debug("&c - Correct any generator settings that haven't copied to 'settings.yml' properly"); - PS.debug("&c - Start the server"); - PS.get().setPlots(DBFunc.getPlots()); - } else { - sendMessage("&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!"); - done.set(true); - } - } - }); - sendMessage("Saving configuration..."); - try { - PS.get().config.save(PS.get().configFile); - } catch (final IOException e) { - sendMessage(" - &cFailed to save configuration."); - } - TaskManager.runTask(new Runnable() { - @Override - public void run() { - try { - boolean MV = false; - boolean MW = false; - if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) && Bukkit.getPluginManager().getPlugin("Multiverse-Core").isEnabled()) { - MV = true; - } else if ((Bukkit.getPluginManager().getPlugin("MultiWorld") != null) && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled()) { - MW = true; - } - for (final String worldname : worlds) { - final World world = Bukkit.getWorld(getWorld(worldname)); - if (world == null) { - sendMessage("&cInvalid world in PlotMe configuration: " + worldname); - } - final String actualWorldName = world.getName(); - sendMessage("Reloading generator for world: '" + actualWorldName + "'..."); - PS.get().removePlotAreas(actualWorldName); - if (MV) { - // unload world with MV - Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv unload " + actualWorldName); - try { - Thread.sleep(1000); - } catch (final InterruptedException ex) { - Thread.currentThread().interrupt(); - } - // load world with MV - Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv import " + actualWorldName + " normal -g PlotSquared"); - } else if (MW) { - // unload world with MW - Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw unload " + actualWorldName); - try { - Thread.sleep(1000); - } catch (final InterruptedException ex) { - Thread.currentThread().interrupt(); - } - // load world with MW - Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + actualWorldName + " plugin:PlotSquared"); - } else { - // Load using Bukkit API - // - User must set generator manually - Bukkit.getServer().unloadWorld(world, true); - final World myworld = WorldCreator.name(actualWorldName).generator(new BukkitPlotGenerator(new HybridGen())).createWorld(); - myworld.save(); - } - } - } catch (final Exception e) { - e.printStackTrace(); - } - if (done.get()) { - done(); - sendMessage("&aDatabase conversion is now complete!"); - PS.debug("&c - Stop the server"); - PS.debug("&c - Disable 'plotme-convert.enabled' and 'plotme-convert.cache-uuids' in the settings.yml"); - PS.debug("&c - Correct any generator settings that haven't copied to 'settings.yml' properly"); - PS.debug("&c - Start the server"); - } else { - sendMessage("&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!"); - done.set(true); - } - } - }); - } catch (final Exception e) { - e.printStackTrace(); - PS.debug("&/end/"); - } - return true; - } - - public void done() { - PS.get().setPlots(DBFunc.getPlots()); - } -} +//////////////////////////////////////////////////////////////////////////////////////////////////// +// PlotSquared - A plot manager and world generator for the Bukkit API / +// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / +// / +// This program is free software; you can redistribute it and/or modify / +// it under the terms of the GNU General Public License as published by / +// the Free Software Foundation; either version 3 of the License, or / +// (at your option) any later version. / +// / +// This program is distributed in the hope that it will be useful, / +// but WITHOUT ANY WARRANTY; without even the implied warranty of / +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / +// GNU General Public License for more details. / +// / +// You should have received a copy of the GNU General Public License / +// along with this program; if not, write to the Free Software Foundation, / +// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / +// / +// You can contact us via: support@intellectualsites.com / +//////////////////////////////////////////////////////////////////////////////////////////////////// +package com.plotsquared.bukkit.database.plotme; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.sql.Connection; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map.Entry; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.WorldCreator; + +import com.intellectualcrafters.configuration.file.FileConfiguration; +import com.intellectualcrafters.configuration.file.YamlConfiguration; +import com.intellectualcrafters.plot.PS; +import com.intellectualcrafters.plot.config.Settings; +import com.intellectualcrafters.plot.database.DBFunc; +import com.intellectualcrafters.plot.generator.HybridGen; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotArea; +import com.intellectualcrafters.plot.object.PlotId; +import com.intellectualcrafters.plot.util.TaskManager; +import com.plotsquared.bukkit.generator.BukkitPlotGenerator; + +/** + * Created 2014-08-17 for PlotSquared + * + + + */ +public class LikePlotMeConverter { + private final String plugin; + + /** + * Constructor + * + * @param plugin Plugin Used to run the converter + */ + public LikePlotMeConverter(final String plugin) { + this.plugin = plugin; + } + + public static String getWorld(final String world) { + for (final World newworld : Bukkit.getWorlds()) { + if (newworld.getName().equalsIgnoreCase(world)) { + return newworld.getName(); + } + } + return world; + } + + private void sendMessage(final String message) { + PS.debug("&3PlotMe&8->&3PlotSquared&8: &7" + message); + } + + public String getPlotMePath() { + return new File(".").getAbsolutePath() + File.separator + "plugins" + File.separator + plugin + File.separator; + } + + public String getAthionPlotsPath() { + return new File(".").getAbsolutePath() + File.separator + "plugins" + File.separator + plugin + File.separator; + } + + public FileConfiguration getPlotMeConfig(final String dataFolder) { + final File plotMeFile = new File(dataFolder + "config.yml"); + if (!plotMeFile.exists()) { + return null; + } + return YamlConfiguration.loadConfiguration(plotMeFile); + } + + public Set getPlotMeWorlds(final FileConfiguration plotConfig) { + return plotConfig.getConfigurationSection("worlds").getKeys(false); + } + + public void mergeWorldYml(final String plugin, FileConfiguration plotConfig) { + try { + File genConfig = new File("plugins" + File.separator + plugin + File.separator + "PlotMe-DefaultGenerator" + File.separator + "config.yml"); + if (genConfig.exists()) { + YamlConfiguration yml = YamlConfiguration.loadConfiguration(genConfig); + for (String key : yml.getKeys(true)) { + if (!plotConfig.contains(key)) { + plotConfig.set(key, yml.get(key)); + } + } + genConfig.delete(); + } + } + catch (Exception e) { + e.printStackTrace(); + } + } + + public void updateWorldYml(final String plugin, final String location) { + try { + final Path path = Paths.get(location); + final File file = new File(location); + if (!file.exists()) { + return; + } + final Charset charset = StandardCharsets.UTF_8; + String content = new String(Files.readAllBytes(path), charset); + content = content.replaceAll("PlotMe-DefaultGenerator", "PlotSquared"); + content = content.replaceAll(plugin, "PlotSquared"); + Files.write(path, content.getBytes(charset)); + } catch (IOException e) { + } + } + + public boolean run(final APlotMeConnector connector) { + try { + final String dataFolder = getPlotMePath(); + final FileConfiguration plotConfig = getPlotMeConfig(dataFolder); + if (plotConfig == null) { + return false; + } + + String version = plotConfig.getString("Version"); + if (version == null) { + version = plotConfig.getString("version"); + } + if (!connector.accepts(version)) { + return false; + } + + PS.debug("&3Using connector: " + connector.getClass().getCanonicalName()); + + final Connection connection = connector.getPlotMeConnection(plugin, plotConfig, dataFolder); + + if (!connector.isValidConnection(connection)) { + sendMessage("Cannot connect to PlotMe DB. Conversion process will not continue"); + return false; + } + + sendMessage(plugin + " conversion has started. To disable this, please set 'plotme-convert.enabled' to false in the 'settings.yml'"); + + mergeWorldYml(plugin, plotConfig); + + sendMessage("Connecting to " + plugin + " DB"); + + int plotCount = 0; + final ArrayList createdPlots = new ArrayList<>(); + + sendMessage("Collecting plot data"); + + final String dbPrefix = plugin.toLowerCase(); + sendMessage(" - " + dbPrefix + "Plots"); + final Set worlds = getPlotMeWorlds(plotConfig); + + if (Settings.CONVERT_PLOTME) { + sendMessage("Updating bukkit.yml"); + updateWorldYml(plugin, "bukkit.yml"); + updateWorldYml(plugin, "plugins/Multiverse-Core/worlds.yml"); + for (final String world : plotConfig.getConfigurationSection("worlds").getKeys(false)) { + sendMessage("Copying config for: " + world); + try { + final String actualWorldName = getWorld(world); + connector.copyConfig(plotConfig, world, actualWorldName); + PS.get().config.save(PS.get().configFile); + } catch (final Exception e) { + e.printStackTrace(); + sendMessage("&c-- &lFailed to save configuration for world '" + world + "'\nThis will need to be done using the setup command, or manually"); + } + } + } + final HashMap> plots = connector.getPlotMePlots(connection); + for (final Entry> entry : plots.entrySet()) { + plotCount += entry.getValue().size(); + } + if (!Settings.CONVERT_PLOTME) { + return false; + } + + sendMessage(" - " + dbPrefix + "Allowed"); + + sendMessage("Collected " + plotCount + " plots from PlotMe"); + final File PLOTME_DG_FILE = new File(dataFolder + File.separator + "PlotMe-DefaultGenerator" + File.separator + "config.yml"); + if (PLOTME_DG_FILE.exists()) { + final YamlConfiguration PLOTME_DG_YML = YamlConfiguration.loadConfiguration(PLOTME_DG_FILE); + try { + for (final String world : plots.keySet()) { + final String actualWorldName = getWorld(world); + final String plotMeWorldName = world.toLowerCase(); + Integer pathwidth = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".PathWidth"); // + /* + * TODO: dead code + * + if (pathwidth == null) { + pathwidth = 7; + } + */ + PS.get().config.set("worlds." + world + ".road.width", pathwidth); + + Integer pathheight = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".RoadHeight"); // + if ((pathheight == null) || (pathheight == 0)) { + pathheight = 64; + } + PS.get().config.set("worlds." + world + ".road.height", pathheight); + PS.get().config.set("worlds." + world + ".wall.height", pathheight); + PS.get().config.set("worlds." + world + ".plot.height", pathheight); + Integer plotsize = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".PlotSize"); // + if ((plotsize == null) || (plotsize == 0)) { + plotsize = 32; + } + PS.get().config.set("worlds." + world + ".plot.size", plotsize); + String wallblock = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".WallBlock"); // + if (wallblock == null) { + wallblock = "44"; + } + PS.get().config.set("worlds." + world + ".wall.block", wallblock); + String floor = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".PlotFloorBlock"); // + if (floor == null) { + floor = "2"; + } + PS.get().config.set("worlds." + world + ".plot.floor", Collections.singletonList(floor)); + String filling = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".FillBlock"); // + if (filling == null) { + filling = "3"; + } + PS.get().config.set("worlds." + world + ".plot.filling", Collections.singletonList(filling)); + String road = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".RoadMainBlock"); + if (road == null) { + road = "5"; + } + PS.get().config.set("worlds." + world + ".road.block", road); + Integer height = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".RoadHeight"); // + if (height == 0) { + height = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".GroundHeight"); // + if (height == 0) { + height = 64; + } + } + PS.get().config.set("worlds." + actualWorldName + ".road.height", height); + PS.get().config.set("worlds." + actualWorldName + ".plot.height", height); + PS.get().config.set("worlds." + actualWorldName + ".wall.height", height); + PS.get().config.save(PS.get().configFile); + } + } catch (IOException e) { + } + } + for (Entry> entry : plots.entrySet()) { + String world = entry.getKey(); + PlotArea area = PS.get().getPlotArea(world, null); + int duplicate = 0; + if (area != null) { + for (Entry entry2 : entry.getValue().entrySet()) { + if (area.getOwnedPlotAbs(entry2.getKey()) != null) { + duplicate++; + } else { + createdPlots.add(entry2.getValue()); + } + } + if (duplicate > 0) { + PS.debug("&c[WARNING] Found " + duplicate + " duplicate plots already in DB for world: '" + world + "'. Have you run the converter already?"); + } + } else { + if (PS.get().plots_tmp != null) { + HashMap map = PS.get().plots_tmp.get(world); + if (map != null) { + for (Entry entry2 : entry.getValue().entrySet()) { + if (map.containsKey(entry2.getKey())) { + duplicate++; + } else { + createdPlots.add(entry2.getValue()); + } + } + if (duplicate > 0) { + PS.debug("&c[WARNING] Found " + duplicate + " duplicate plots already in DB for world: '" + world + "'. Have you run the converter already?"); + } + continue; + } + } + createdPlots.addAll(entry.getValue().values()); + } + } + sendMessage("Creating plot DB"); + Thread.sleep(1000); + final AtomicBoolean done = new AtomicBoolean(false); + DBFunc.createPlotsAndData(createdPlots, new Runnable() { + @Override + public void run() { + if (done.get()) { + done(); + sendMessage("&aDatabase conversion is now complete!"); + PS.debug("&c - Stop the server"); + PS.debug("&c - Disable 'plotme-convert.enabled' and 'plotme-convert.cache-uuids' in the settings.yml"); + PS.debug("&c - Correct any generator settings that haven't copied to 'settings.yml' properly"); + PS.debug("&c - Start the server"); + PS.get().setPlots(DBFunc.getPlots()); + } else { + sendMessage("&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!"); + done.set(true); + } + } + }); + sendMessage("Saving configuration..."); + try { + PS.get().config.save(PS.get().configFile); + } catch (final IOException e) { + sendMessage(" - &cFailed to save configuration."); + } + TaskManager.runTask(new Runnable() { + @Override + public void run() { + try { + boolean MV = false; + boolean MW = false; + if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) && Bukkit.getPluginManager().getPlugin("Multiverse-Core").isEnabled()) { + MV = true; + } else if ((Bukkit.getPluginManager().getPlugin("MultiWorld") != null) && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled()) { + MW = true; + } + for (final String worldname : worlds) { + final World world = Bukkit.getWorld(getWorld(worldname)); + if (world == null) { + sendMessage("&cInvalid world in PlotMe configuration: " + worldname); + } + final String actualWorldName = world.getName(); + sendMessage("Reloading generator for world: '" + actualWorldName + "'..."); + PS.get().removePlotAreas(actualWorldName); + if (MV) { + // unload world with MV + Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv unload " + actualWorldName); + try { + Thread.sleep(1000); + } catch (final InterruptedException ex) { + Thread.currentThread().interrupt(); + } + // load world with MV + Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv import " + actualWorldName + " normal -g PlotSquared"); + } else if (MW) { + // unload world with MW + Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw unload " + actualWorldName); + try { + Thread.sleep(1000); + } catch (final InterruptedException ex) { + Thread.currentThread().interrupt(); + } + // load world with MW + Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + actualWorldName + " plugin:PlotSquared"); + } else { + // Load using Bukkit API + // - User must set generator manually + Bukkit.getServer().unloadWorld(world, true); + final World myworld = WorldCreator.name(actualWorldName).generator(new BukkitPlotGenerator(new HybridGen())).createWorld(); + myworld.save(); + } + } + } catch (final Exception e) { + e.printStackTrace(); + } + if (done.get()) { + done(); + sendMessage("&aDatabase conversion is now complete!"); + PS.debug("&c - Stop the server"); + PS.debug("&c - Disable 'plotme-convert.enabled' and 'plotme-convert.cache-uuids' in the settings.yml"); + PS.debug("&c - Correct any generator settings that haven't copied to 'settings.yml' properly"); + PS.debug("&c - Start the server"); + } else { + sendMessage("&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!"); + done.set(true); + } + } + }); + } catch (final Exception e) { + e.printStackTrace(); + PS.debug("&/end/"); + } + return true; + } + + public void done() { + PS.get().setPlots(DBFunc.getPlots()); + } +} diff --git a/src/main/java/com/plotsquared/bukkit/database/plotme/PlotMeConnector_017.java b/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/PlotMeConnector_017.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/database/plotme/PlotMeConnector_017.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/PlotMeConnector_017.java diff --git a/src/main/java/com/plotsquared/bukkit/events/ClusterFlagRemoveEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/ClusterFlagRemoveEvent.java similarity index 97% rename from src/main/java/com/plotsquared/bukkit/events/ClusterFlagRemoveEvent.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/events/ClusterFlagRemoveEvent.java index b4ff0f900..c8cf638c9 100644 --- a/src/main/java/com/plotsquared/bukkit/events/ClusterFlagRemoveEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/ClusterFlagRemoveEvent.java @@ -1,89 +1,89 @@ -//////////////////////////////////////////////////////////////////////////////////////////////////// -// PlotSquared - A plot manager and world generator for the Bukkit API / -// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / -// / -// This program is free software; you can redistribute it and/or modify / -// it under the terms of the GNU General Public License as published by / -// the Free Software Foundation; either version 3 of the License, or / -// (at your option) any later version. / -// / -// This program is distributed in the hope that it will be useful, / -// but WITHOUT ANY WARRANTY; without even the implied warranty of / -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / -// GNU General Public License for more details. / -// / -// You should have received a copy of the GNU General Public License / -// along with this program; if not, write to the Free Software Foundation, / -// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / -// / -// You can contact us via: support@intellectualsites.com / -//////////////////////////////////////////////////////////////////////////////////////////////////// -package com.plotsquared.bukkit.events; - -import org.bukkit.event.Cancellable; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -import com.intellectualcrafters.plot.flag.Flag; -import com.intellectualcrafters.plot.object.PlotCluster; - -/** - * Called when a flag is removed from a plot - * - - - */ -public class ClusterFlagRemoveEvent extends Event implements Cancellable { - private static HandlerList handlers = new HandlerList(); - private final PlotCluster cluster; - private final Flag flag; - private boolean cancelled; - - /** - * PlotFlagRemoveEvent: Called when a flag is removed from a plot - * - * @param flag Flag that was removed - * @param cluster PlotCluster from which the flag was removed - */ - public ClusterFlagRemoveEvent(final Flag flag, final PlotCluster cluster) { - this.cluster = cluster; - this.flag = flag; - } - - public static HandlerList getHandlerList() { - return handlers; - } - - /** - * Get the cluster involved - * - * @return PlotCluster - */ - public PlotCluster getCluster() { - return cluster; - } - - /** - * Get the flag involved - * - * @return Flag - */ - public Flag getFlag() { - return flag; - } - - @Override - public HandlerList getHandlers() { - return handlers; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(final boolean b) { - cancelled = b; - } -} +//////////////////////////////////////////////////////////////////////////////////////////////////// +// PlotSquared - A plot manager and world generator for the Bukkit API / +// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / +// / +// This program is free software; you can redistribute it and/or modify / +// it under the terms of the GNU General Public License as published by / +// the Free Software Foundation; either version 3 of the License, or / +// (at your option) any later version. / +// / +// This program is distributed in the hope that it will be useful, / +// but WITHOUT ANY WARRANTY; without even the implied warranty of / +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / +// GNU General Public License for more details. / +// / +// You should have received a copy of the GNU General Public License / +// along with this program; if not, write to the Free Software Foundation, / +// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / +// / +// You can contact us via: support@intellectualsites.com / +//////////////////////////////////////////////////////////////////////////////////////////////////// +package com.plotsquared.bukkit.events; + +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +import com.intellectualcrafters.plot.flag.Flag; +import com.intellectualcrafters.plot.object.PlotCluster; + +/** + * Called when a flag is removed from a plot + * + + + */ +public class ClusterFlagRemoveEvent extends Event implements Cancellable { + private static HandlerList handlers = new HandlerList(); + private final PlotCluster cluster; + private final Flag flag; + private boolean cancelled; + + /** + * PlotFlagRemoveEvent: Called when a flag is removed from a plot + * + * @param flag Flag that was removed + * @param cluster PlotCluster from which the flag was removed + */ + public ClusterFlagRemoveEvent(final Flag flag, final PlotCluster cluster) { + this.cluster = cluster; + this.flag = flag; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * Get the cluster involved + * + * @return PlotCluster + */ + public PlotCluster getCluster() { + return cluster; + } + + /** + * Get the flag involved + * + * @return Flag + */ + public Flag getFlag() { + return flag; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(final boolean b) { + cancelled = b; + } +} diff --git a/src/main/java/com/plotsquared/bukkit/events/PlayerClaimPlotEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerClaimPlotEvent.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/events/PlayerClaimPlotEvent.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerClaimPlotEvent.java diff --git a/src/main/java/com/plotsquared/bukkit/events/PlayerEnterPlotEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerEnterPlotEvent.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/events/PlayerEnterPlotEvent.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerEnterPlotEvent.java diff --git a/src/main/java/com/plotsquared/bukkit/events/PlayerLeavePlotEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerLeavePlotEvent.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/events/PlayerLeavePlotEvent.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerLeavePlotEvent.java diff --git a/src/main/java/com/plotsquared/bukkit/events/PlayerPlotDeniedEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotDeniedEvent.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/events/PlayerPlotDeniedEvent.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotDeniedEvent.java diff --git a/src/main/java/com/plotsquared/bukkit/events/PlayerPlotHelperEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotHelperEvent.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/events/PlayerPlotHelperEvent.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotHelperEvent.java diff --git a/src/main/java/com/plotsquared/bukkit/events/PlayerPlotTrustedEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotTrustedEvent.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/events/PlayerPlotTrustedEvent.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotTrustedEvent.java diff --git a/src/main/java/com/plotsquared/bukkit/events/PlayerTeleportToPlotEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerTeleportToPlotEvent.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/events/PlayerTeleportToPlotEvent.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerTeleportToPlotEvent.java diff --git a/src/main/java/com/plotsquared/bukkit/events/PlotClearEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotClearEvent.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/events/PlotClearEvent.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotClearEvent.java diff --git a/src/main/java/com/plotsquared/bukkit/events/PlotDeleteEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotDeleteEvent.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/events/PlotDeleteEvent.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotDeleteEvent.java diff --git a/src/main/java/com/plotsquared/bukkit/events/PlotEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotEvent.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/events/PlotEvent.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotEvent.java diff --git a/src/main/java/com/plotsquared/bukkit/events/PlotFlagAddEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotFlagAddEvent.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/events/PlotFlagAddEvent.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotFlagAddEvent.java diff --git a/src/main/java/com/plotsquared/bukkit/events/PlotFlagRemoveEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotFlagRemoveEvent.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/events/PlotFlagRemoveEvent.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotFlagRemoveEvent.java diff --git a/src/main/java/com/plotsquared/bukkit/events/PlotMergeEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotMergeEvent.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/events/PlotMergeEvent.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotMergeEvent.java diff --git a/src/main/java/com/plotsquared/bukkit/events/PlotRateEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotRateEvent.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/events/PlotRateEvent.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotRateEvent.java diff --git a/src/main/java/com/plotsquared/bukkit/events/PlotUnlinkEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotUnlinkEvent.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/events/PlotUnlinkEvent.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotUnlinkEvent.java diff --git a/src/main/java/com/plotsquared/bukkit/generator/BukkitAugmentedGenerator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitAugmentedGenerator.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/generator/BukkitAugmentedGenerator.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitAugmentedGenerator.java diff --git a/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java diff --git a/src/main/java/com/plotsquared/bukkit/listeners/ChunkListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/ChunkListener.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/listeners/ChunkListener.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/listeners/ChunkListener.java diff --git a/src/main/java/com/plotsquared/bukkit/listeners/ForceFieldListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/ForceFieldListener.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/listeners/ForceFieldListener.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/listeners/ForceFieldListener.java diff --git a/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents.java similarity index 97% rename from src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents.java index 7f6023daf..2bf04f751 100644 --- a/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents.java @@ -1,2190 +1,2190 @@ -package com.plotsquared.bukkit.listeners; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map.Entry; -import java.util.Objects; -import java.util.Set; -import java.util.UUID; -import java.util.regex.Pattern; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.BlockState; -import org.bukkit.command.PluginCommand; -import org.bukkit.entity.Animals; -import org.bukkit.entity.Arrow; -import org.bukkit.entity.Creature; -import org.bukkit.entity.EnderDragon; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Hanging; -import org.bukkit.entity.HumanEntity; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Monster; -import org.bukkit.entity.Player; -import org.bukkit.entity.Projectile; -import org.bukkit.entity.TNTPrimed; -import org.bukkit.entity.Tameable; -import org.bukkit.entity.ThrownPotion; -import org.bukkit.entity.Vehicle; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.Action; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockDamageEvent; -import org.bukkit.event.block.BlockDispenseEvent; -import org.bukkit.event.block.BlockFadeEvent; -import org.bukkit.event.block.BlockFormEvent; -import org.bukkit.event.block.BlockFromToEvent; -import org.bukkit.event.block.BlockGrowEvent; -import org.bukkit.event.block.BlockIgniteEvent; -import org.bukkit.event.block.BlockPhysicsEvent; -import org.bukkit.event.block.BlockPistonExtendEvent; -import org.bukkit.event.block.BlockPistonRetractEvent; -import org.bukkit.event.block.BlockPlaceEvent; -import org.bukkit.event.block.BlockRedstoneEvent; -import org.bukkit.event.block.BlockSpreadEvent; -import org.bukkit.event.block.EntityBlockFormEvent; -import org.bukkit.event.entity.CreatureSpawnEvent; -import org.bukkit.event.entity.EntityChangeBlockEvent; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.event.entity.EntityExplodeEvent; -import org.bukkit.event.entity.ExplosionPrimeEvent; -import org.bukkit.event.entity.PotionSplashEvent; -import org.bukkit.event.entity.ProjectileHitEvent; -import org.bukkit.event.hanging.HangingBreakByEntityEvent; -import org.bukkit.event.hanging.HangingPlaceEvent; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.event.inventory.InventoryCloseEvent; -import org.bukkit.event.player.AsyncPlayerChatEvent; -import org.bukkit.event.player.PlayerBucketEmptyEvent; -import org.bukkit.event.player.PlayerBucketFillEvent; -import org.bukkit.event.player.PlayerChangedWorldEvent; -import org.bukkit.event.player.PlayerCommandPreprocessEvent; -import org.bukkit.event.player.PlayerEggThrowEvent; -import org.bukkit.event.player.PlayerInteractEntityEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerMoveEvent; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.event.player.PlayerTeleportEvent; -import org.bukkit.event.vehicle.VehicleCreateEvent; -import org.bukkit.event.vehicle.VehicleDestroyEvent; -import org.bukkit.event.world.StructureGrowEvent; -import org.bukkit.help.HelpTopic; -import org.bukkit.inventory.ItemStack; -import org.bukkit.metadata.FixedMetadataValue; -import org.bukkit.metadata.MetadataValue; -import org.bukkit.plugin.Plugin; -import org.bukkit.projectiles.BlockProjectileSource; -import org.bukkit.projectiles.ProjectileSource; -import org.bukkit.util.Vector; - -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.flag.Flag; -import com.intellectualcrafters.plot.flag.FlagManager; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotBlock; -import com.intellectualcrafters.plot.object.PlotHandler; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotInventory; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.StringWrapper; -import com.intellectualcrafters.plot.util.EventUtil; -import com.intellectualcrafters.plot.util.ExpireManager; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.MathMan; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.RegExUtil; -import com.intellectualcrafters.plot.util.StringMan; -import com.intellectualcrafters.plot.util.TaskManager; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.plotsquared.bukkit.BukkitMain; -import com.plotsquared.bukkit.object.BukkitLazyBlock; -import com.plotsquared.bukkit.object.BukkitPlayer; -import com.plotsquared.bukkit.util.BukkitUtil; -import com.plotsquared.listener.PlayerBlockEventType; - -/** - * Player Events involving plots - * - */ -@SuppressWarnings({ "deprecation", "unchecked" }) -public class PlayerEvents extends com.plotsquared.listener.PlotListener implements Listener { - - private boolean pistonBlocks = true; - private float lastRadius; - // To prevent recursion - private boolean tmp_teleport = true; - - public static void sendBlockChange(final org.bukkit.Location bloc, final Material type, final byte data) { - TaskManager.runTaskLater(new Runnable() { - @Override - public void run() { - final String world = bloc.getWorld().getName(); - final int x = bloc.getBlockX(); - final int z = bloc.getBlockZ(); - final int distance = Bukkit.getViewDistance() * 16; - for (Entry entry : UUIDHandler.getPlayers().entrySet()) { - PlotPlayer player = entry.getValue(); - final Location loc = player.getLocation(); - if (loc.getWorld().equals(world)) { - if (16 * Math.abs(loc.getX() - x) / 16 > distance || 16 * Math.abs(loc.getZ() - z) / 16 > distance) { - continue; - } - ((BukkitPlayer) player).player.sendBlockChange(bloc, type, data); - } - } - } - }, 3); - } - - @EventHandler - public void onRedstoneEvent(final BlockRedstoneEvent event) { - final Block block = event.getBlock(); - switch (block.getType()) { - case REDSTONE_LAMP_OFF: - case REDSTONE_WIRE: - case REDSTONE_LAMP_ON: - case PISTON_BASE: - case PISTON_STICKY_BASE: - case IRON_DOOR_BLOCK: - case LEVER: - case WOODEN_DOOR: - case FENCE_GATE: - case WOOD_BUTTON: - case STONE_BUTTON: - case IRON_PLATE: - case WOOD_PLATE: - case STONE_PLATE: - case GOLD_PLATE: - case SPRUCE_DOOR: - case BIRCH_DOOR: - case JUNGLE_DOOR: - case ACACIA_DOOR: - case DARK_OAK_DOOR: - case IRON_TRAPDOOR: - case SPRUCE_FENCE_GATE: - case BIRCH_FENCE_GATE: - case JUNGLE_FENCE_GATE: - case ACACIA_FENCE_GATE: - case DARK_OAK_FENCE_GATE: - case POWERED_RAIL: - return; - default: - final Location loc = BukkitUtil.getLocation(block.getLocation()); - PlotArea area = loc.getPlotArea(); - if (area == null) { - return; - } - final Plot plot = area.getOwnedPlotAbs(loc); - if (plot == null) { - return; - } - final Flag redstone = FlagManager.getPlotFlagRaw(plot, "redstone"); - if (redstone != null) { - if ((Boolean) redstone.getValue()) { - return; - } else { - event.setNewCurrent(0); - return; - } - } - if (Settings.REDSTONE_DISABLER) { - if (UUIDHandler.getPlayer(plot.owner) == null) { - boolean disable = true; - for (final UUID trusted : plot.getTrusted()) { - if (UUIDHandler.getPlayer(trusted) != null) { - disable = false; - break; - } - } - if (disable) { - event.setNewCurrent(0); - return; - } - } - } - if (Settings.REDSTONE_DISABLER_UNOCCUPIED) { - for (Entry entry : UUIDHandler.getPlayers().entrySet()) { - if (plot.equals(entry.getValue().getCurrentPlot())) { - return; - } - } - event.setNewCurrent(0); - } - } - } - - @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) - public void onPhysicsEvent(final BlockPhysicsEvent event) { - switch (event.getChangedType()) { - case REDSTONE_COMPARATOR_OFF: - case REDSTONE_COMPARATOR_ON: { - final Block block = event.getBlock(); - final Location loc = BukkitUtil.getLocation(block.getLocation()); - PlotArea area = loc.getPlotArea(); - if (area == null) { - return; - } - final Plot plot = area.getOwnedPlotAbs(loc); - if (plot == null) { - return; - } - if (FlagManager.isPlotFlagFalse(plot, "redstone")) { - event.setCancelled(true); - } - return; - } - case DRAGON_EGG: - case ANVIL: - case SAND: - case GRAVEL: - final Block block = event.getBlock(); - final Location loc = BukkitUtil.getLocation(block.getLocation()); - PlotArea area = loc.getPlotArea(); - if (area == null) { - return; - } - final Plot plot = area.getOwnedPlotAbs(loc); - if (plot != null && FlagManager.isPlotFlagTrue(plot, "disable-physics")) { - event.setCancelled(true); - return; - } - return; - default: - break; - } - } - - @EventHandler - public void onProjectileHit(final ProjectileHitEvent event) { - final Projectile entity = event.getEntity(); - final Location loc = BukkitUtil.getLocation(entity); - if (!PS.get().hasPlotArea(loc.getWorld())) { - return; - } - PlotArea area = loc.getPlotArea(); - if (area == null) { - return; - } - Plot plot = area.getPlotAbs(loc); - // - final ProjectileSource shooter = entity.getShooter(); - if (shooter instanceof Player) { - final PlotPlayer pp = BukkitUtil.getPlayer((Player) shooter); - if (plot == null) { - if (!Permissions.hasPermission(pp, C.PERMISSION_PROJECTILE_UNOWNED)) { - entity.remove(); - } - return; - } - if (plot.isAdded(pp.getUUID()) || Permissions.hasPermission(pp, C.PERMISSION_PROJECTILE_OTHER)) { - return; - } - entity.remove(); - } else if (!(shooter instanceof Entity) && shooter != null) { - if (plot == null) { - entity.remove(); - return; - } - final Location sLoc = BukkitUtil.getLocation(((BlockProjectileSource) shooter).getBlock().getLocation()); - if (!area.contains(sLoc.getX(), sLoc.getZ())) { - entity.remove(); - return; - } - final Plot sPlot = area.getOwnedPlotAbs(sLoc); - if (sPlot == null || !PlotHandler.sameOwners(plot, sPlot)) { - entity.remove(); - } - } - } - - @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) - public void PlayerCommand(final PlayerCommandPreprocessEvent event) { - String msg = event.getMessage().toLowerCase().replaceAll("/", "").trim(); - if (msg.isEmpty()) { - return; - } - final String[] split = msg.split(" "); - final PluginCommand cmd = Bukkit.getServer().getPluginCommand(split[0]); - if (cmd == null) { - if (split[0].equals("plotme") || split[0].equals("ap")) { - final Player player = event.getPlayer(); - if (Settings.USE_PLOTME_ALIAS) { - player.performCommand("plots " + StringMan.join(Arrays.copyOfRange(split, 1, split.length), " ")); - } else { - MainUtil.sendMessage(BukkitUtil.getPlayer(player), C.NOT_USING_PLOTME); - } - event.setCancelled(true); - return; - } - } - final Player player = event.getPlayer(); - final BukkitPlayer pp = (BukkitPlayer) BukkitUtil.getPlayer(player); - Plot plot = pp.getCurrentPlot(); - if (plot == null) { - return; - } - Flag flag = FlagManager.getPlotFlagRaw(plot, "blocked-cmds"); - if (flag == null || Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_BLOCKED_CMDS)) { - return; - } - final List v = (List) flag.getValue(); - final String[] parts = msg.split(" "); - String c = parts[0]; - if (parts[0].contains(":")) { - c = parts[0].split(":")[1]; - msg = msg.replace(parts[0].split(":")[0] + ":", ""); - } - final String l = c; - final List aliases = new ArrayList<>(); - for (final HelpTopic cmdLabel : Bukkit.getServer().getHelpMap().getHelpTopics()) { - if (c.equals(cmdLabel.getName())) { - break; - } - PluginCommand p; - final String label = cmdLabel.getName().replaceFirst("/", ""); - if (aliases.contains(label)) { - continue; - } - if ((p = Bukkit.getPluginCommand(label)) != null) { - for (String a : p.getAliases()) { - if (aliases.contains(a)) { - continue; - } - aliases.add(a); - a = a.replaceFirst("/", ""); - if (!a.equals(label) && a.equals(c)) { - c = label; - break; - } - } - } - } - if (!l.equals(c)) { - msg = msg.replace(l, c); - } - for (final String s : v) { - Pattern pattern; - if (!RegExUtil.compiledPatterns.containsKey(s)) { - RegExUtil.compiledPatterns.put(s, pattern = Pattern.compile(s)); - } else { - pattern = RegExUtil.compiledPatterns.get(s); - } - if (pattern.matcher(msg).matches()) { - MainUtil.sendMessage(pp, C.COMMAND_BLOCKED); - String perm; - if (plot.isAdded(pp.getUUID())) { - perm = "plots.admin.command.blocked-cmds.shared"; - } else { - perm = "plots.admin.command.blocked-cmds.other"; - } - if (!Permissions.hasPermission(pp, perm)) { - event.setCancelled(true); - } - return; - } - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onConnect(final PlayerJoinEvent event) { - final Player player = event.getPlayer(); - BukkitUtil.getPlayer(event.getPlayer()).unregister(); - final PlotPlayer pp = BukkitUtil.getPlayer(player); - // Now - String name = pp.getName(); - StringWrapper sw = new StringWrapper(name); - final UUID uuid = pp.getUUID(); - UUIDHandler.add(sw, uuid); - - Location loc = pp.getLocation(); - PlotArea area = loc.getPlotArea(); - final Plot plot; - if (area != null) { - plot = area.getPlot(loc); - if (plot != null) { - plotEntry(pp, plot); - } - } else { - plot = null; - } - // Delayed - - // Async - TaskManager.runTaskLaterAsync(new Runnable() { - @Override - public void run() { - if (!player.hasPlayedBefore() && player.isOnline()) { - player.saveData(); - } - ExpireManager.dates.put(uuid, System.currentTimeMillis()); - if (BukkitMain.worldEdit != null) { - if (pp.getAttribute("worldedit")) { - MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASSED); - } - } - if (PS.get().update != null && Permissions.hasPermission(pp, C.PERMISSION_ADMIN_UPDATE) && Settings.UPDATE_NOTIFICATIONS) { - MainUtil.sendMessage(pp, "&6An update for PlotSquared is available: &7/plot update"); - } - if (Settings.TELEPORT_ON_LOGIN && plot != null) { - TaskManager.runTask(new Runnable() { - @Override - public void run() { - plot.teleportPlayer(pp); - } - }); - MainUtil.sendMessage(pp, C.TELEPORTED_TO_ROAD); - } - } - }, 20); - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void PlayerMove(final PlayerMoveEvent event) { - final org.bukkit.Location from = event.getFrom(); - final org.bukkit.Location to = event.getTo(); - int x2; - if (MathMan.roundInt(from.getX()) != (x2 = MathMan.roundInt(to.getX()))) { - final Player player = event.getPlayer(); - final PlotPlayer pp = BukkitUtil.getPlayer(player); - - // Cancel teleport - TaskManager.TELEPORT_QUEUE.remove(pp.getName()); - - // Set last location - Location loc = BukkitUtil.getLocation(to); - pp.setMeta("location", loc); - PlotArea area = loc.getPlotArea(); - if (area == null) { - pp.deleteMeta("lastplot"); - return; - } - Plot now = area.getPlotAbs(loc); - final Plot lastPlot = pp.getMeta("lastplot"); - if (now == null) { - if (lastPlot != null && !plotExit(pp, lastPlot)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED); - if (lastPlot.equals(BukkitUtil.getLocation(from).getPlot())) { - player.teleport(from); - } else { - player.teleport(player.getWorld().getSpawnLocation()); - } - event.setCancelled(true); - return; - } - } else if (now.equals(lastPlot)) { - return; - } else if (!plotEntry(pp, now)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_ENTRY_DENIED); - player.teleport(from); - event.setCancelled(true); - return; - } - final Integer border = area.getBorder(); - if (x2 > border) { - to.setX(border - 4); - player.teleport(event.getTo()); - MainUtil.sendMessage(pp, C.BORDER); - return; - } else if (x2 < -border) { - to.setX(-border + 4); - player.teleport(event.getTo()); - MainUtil.sendMessage(pp, C.BORDER); - return; - } - return; - } - int z2; - if (MathMan.roundInt(from.getZ()) != (z2 = MathMan.roundInt(to.getZ()))) { - final Player player = event.getPlayer(); - final PlotPlayer pp = BukkitUtil.getPlayer(player); - - // Cancel teleport - TaskManager.TELEPORT_QUEUE.remove(pp.getName()); - - // Set last location - Location loc = BukkitUtil.getLocation(to); - pp.setMeta("location", loc); - - PlotArea area = loc.getPlotArea(); - if (area == null) { - pp.deleteMeta("lastplot"); - return; - } - Plot now = area.getPlotAbs(loc); - final Plot lastPlot = pp.getMeta("lastplot"); - if (now == null) { - if (lastPlot != null && !plotExit(pp, lastPlot)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED); - if (lastPlot.equals(BukkitUtil.getLocation(from).getPlot())) { - player.teleport(from); - } else { - player.teleport(player.getWorld().getSpawnLocation()); - } - event.setCancelled(true); - return; - } - } else if (now.equals(lastPlot)) { - return; - } else if (!plotEntry(pp, now)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_ENTRY_DENIED); - player.teleport(from); - event.setCancelled(true); - return; - } - final Integer border = area.getBorder(); - if (z2 > border) { - to.setZ(border - 4); - player.teleport(event.getTo()); - MainUtil.sendMessage(pp, C.BORDER); - } else if (z2 < -border) { - to.setZ(-border + 4); - player.teleport(event.getTo()); - MainUtil.sendMessage(pp, C.BORDER); - } - } - } - - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onChat(final AsyncPlayerChatEvent event) { - final Player player = event.getPlayer(); - final PlotPlayer plr = BukkitUtil.getPlayer(player); - Location loc = plr.getLocation(); - PlotArea area = loc.getPlotArea(); - if (area == null || !area.PLOT_CHAT && !plr.getAttribute("chat")) { - return; - } - final Plot plot = area.getPlotAbs(loc); - if (plot == null) { - return; - } - final String message = event.getMessage(); - String format = C.PLOT_CHAT_FORMAT.s(); - final String sender = event.getPlayer().getDisplayName(); - final PlotId id = plot.getId(); - final Set recipients = event.getRecipients(); - recipients.clear(); - for (final Player p : Bukkit.getOnlinePlayers()) { - final PlotPlayer pp = BukkitUtil.getPlayer(p); - if (pp.getAttribute("chatspy")) { - String spy = event.getFormat(); - spy = String.format(spy, sender, message); - pp.sendMessage(spy); - } else if (plot.equals(pp.getCurrentPlot())) { - recipients.add(p); - } - } - format = format.replaceAll("%plot_id%", id.x + ";" + id.y).replaceAll("%sender%", "%s").replaceAll("%msg%", "%s"); - format = ChatColor.translateAlternateColorCodes('&', format); - event.setFormat(format); - } - - @EventHandler(priority = EventPriority.LOWEST) - public void BlockDestroy(final BlockBreakEvent event) { - final Player player = event.getPlayer(); - final Location loc = BukkitUtil.getLocation(event.getBlock().getLocation()); - PlotArea area = loc.getPlotArea(); - if (area == null) { - return; - } - final Plot plot = area.getPlotAbs(loc); - if (plot != null) { - if (event.getBlock().getY() == 0) { - event.setCancelled(true); - return; - } - final PlotPlayer pp = BukkitUtil.getPlayer(player); - if (!plot.hasOwner()) { - if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_UNOWNED)) { - return; - } - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_UNOWNED); - event.setCancelled(true); - return; - } else if (!plot.isAdded(pp.getUUID())) { - final Flag destroy = FlagManager.getPlotFlagRaw(plot, "break"); - final Block block = event.getBlock(); - if (destroy != null && ((HashSet) destroy.getValue()) - .contains(new PlotBlock((short) block.getTypeId(), block.getData()))) { - return; - } - if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_OTHER)) { - return; - } - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_OTHER); - event.setCancelled(true); - } else if (Settings.DONE_RESTRICTS_BUILDING && plot.getFlags().containsKey("done")) { - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); - event.setCancelled(true); - return; - } - } - return; - } - final PlotPlayer pp = BukkitUtil.getPlayer(player); - if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_ROAD)) { - return; - } - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_ROAD); - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBigBoom(final EntityExplodeEvent event) { - Location loc = BukkitUtil.getLocation(event.getLocation()); - PlotArea area = loc.getPlotArea(); - if (area == null) { - if (!PS.get().hasPlotArea(loc.getWorld())) { - return; - } - final Iterator iter = event.blockList().iterator(); - while (iter.hasNext()) { - iter.next(); - if (loc.getPlotArea() != null) { - iter.remove(); - } - } - } else { - Plot plot = area.getOwnedPlot(loc); - if (plot != null) { - if (FlagManager.isPlotFlagTrue(plot, "explosion")) { - List meta = event.getEntity().getMetadata("plot"); - Plot origin; - if (meta.isEmpty()) { - origin = plot; - } else { - origin = (Plot) meta.get(0).value(); - } - if (lastRadius != 0) { - final List nearby = event.getEntity().getNearbyEntities(lastRadius, lastRadius, lastRadius); - for (final Entity near : nearby) { - if (near instanceof TNTPrimed || near.getType() == EntityType.MINECART_TNT) { - if (!near.hasMetadata("plot")) { - near.setMetadata("plot", new FixedMetadataValue((Plugin) PS.get().IMP, plot)); - } - } - } - lastRadius = 0; - } - final Iterator iter = event.blockList().iterator(); - while (iter.hasNext()) { - final Block b = iter.next(); - loc = BukkitUtil.getLocation(b.getLocation()); - if (!area.contains(loc.getX(), loc.getZ()) || !origin.equals(area.getOwnedPlot(loc))) { - iter.remove(); - } - } - } - } else { - event.setCancelled(true); - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onWorldChanged(final PlayerChangedWorldEvent event) { - final Player player = event.getPlayer(); - final PlotPlayer pp = BukkitUtil.getPlayer(player); - - - // Delete last location - pp.deleteMeta("location"); - Plot plot = (Plot) pp.deleteMeta("lastplot"); - if (plot != null) { - plotExit(pp, plot); - } - - if (BukkitMain.worldEdit != null) { - if (!Permissions.hasPermission(pp, C.PERMISSION_WORLDEDIT_BYPASS)) { - if (pp.getAttribute("worldedit")) { - pp.removeAttribute("worldedit"); - } - } - } - if (Settings.PERMISSION_CACHING) { - pp.deleteMeta("perm"); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onPeskyMobsChangeTheWorldLikeWTFEvent(final EntityChangeBlockEvent event) { - final String world = event.getBlock().getWorld().getName(); - if (!PS.get().hasPlotArea(world)) { - return; - } - final Entity e = event.getEntity(); - if (!(e instanceof org.bukkit.entity.FallingBlock)) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onEntityBlockForm(final EntityBlockFormEvent e) { - final String world = e.getBlock().getWorld().getName(); - if (!PS.get().hasPlotArea(world)) { - return; - } - if (BukkitUtil.getLocation(e.getBlock().getLocation()).getPlotArea() != null) { - e.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBS(final BlockSpreadEvent e) { - final Block b = e.getBlock(); - final Location loc = BukkitUtil.getLocation(b.getLocation()); - if (loc.isPlotRoad()) { - e.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBF(final BlockFormEvent e) { - final Block b = e.getBlock(); - final Location loc = BukkitUtil.getLocation(b.getLocation()); - if (loc.isPlotRoad()) { - e.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBD(final BlockDamageEvent event) { - final Player player = event.getPlayer(); - Location loc = BukkitUtil.getLocation(event.getBlock().getLocation()); - if (player == null) { - if (loc.isPlotRoad()) { - event.setCancelled(true); - return; - } - } - PlotArea area = loc.getPlotArea(); - if (area == null) { - return; - } - final Plot plot = area.getPlotAbs(loc); - if (plot != null) { - if (loc.getY() == 0) { - event.setCancelled(true); - return; - } - if (!plot.hasOwner()) { - final PlotPlayer pp = BukkitUtil.getPlayer(player); - if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_UNOWNED)) { - return; - } - event.setCancelled(true); - return; - } - final PlotPlayer pp = BukkitUtil.getPlayer(player); - if (!plot.isAdded(pp.getUUID())) { - final Flag destroy = FlagManager.getPlotFlagRaw(plot, "break"); - final Block block = event.getBlock(); - if (destroy != null && ((HashSet) destroy.getValue()) - .contains(new PlotBlock((short) block.getTypeId(), block.getData()))) { - return; - } - if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_OTHER)) { - return; - } - event.setCancelled(true); - return; - } - return; - } - final PlotPlayer pp = BukkitUtil.getPlayer(player); - if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_ROAD)) { - return; - } - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onFade(final BlockFadeEvent e) { - final Block b = e.getBlock(); - Location loc = BukkitUtil.getLocation(b.getLocation()); - PlotArea area = loc.getPlotArea(); - if (area == null) { - return; - } - if (area.getOwnedPlot(loc) == null) { - e.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onChange(final BlockFromToEvent e) { - final Block b = e.getBlock(); - Location loc = BukkitUtil.getLocation(b.getLocation()); - PlotArea area = loc.getPlotArea(); - if (area == null) { - return; - } - Plot plot = area.getOwnedPlot(loc); - if (plot == null || FlagManager.isPlotFlagTrue(plot, "disable-physics")) { - e.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onGrow(final BlockGrowEvent e) { - final Block b = e.getBlock(); - final Location loc = BukkitUtil.getLocation(b.getLocation()); - if (loc.isUnownedPlotArea()) { - e.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockPistonExtend(final BlockPistonExtendEvent event) { - final Block block = event.getBlock(); - final Location loc = BukkitUtil.getLocation(block.getLocation()); - final BlockFace face = event.getDirection(); - final Vector relative = new Vector(face.getModX(), face.getModY(), face.getModZ()); - PlotArea area = loc.getPlotArea(); - if (area == null) { - if (!PS.get().hasPlotArea(loc.getWorld())) { - return; - } - for (final Block b : event.getBlocks()) { - if (BukkitUtil.getLocation(b.getLocation().add(relative)).getPlotArea() != null) { - event.setCancelled(true); - return; - } - } - } - final Plot plot = area.getOwnedPlot(loc); - if (plot == null) { - event.setCancelled(true); - return; - } - final List blocks = event.getBlocks(); - for (final Block b : blocks) { - final Location bloc = BukkitUtil.getLocation(b.getLocation().add(relative)); - if (!area.contains(bloc.getX(), bloc.getZ())) { - event.setCancelled(true); - return; - } - if (!plot.equals(area.getOwnedPlot(bloc))) { - event.setCancelled(true); - return; - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockPistonRetract(final BlockPistonRetractEvent event) { - final Block block = event.getBlock(); - Location loc = BukkitUtil.getLocation(block.getLocation()); - PlotArea area = loc.getPlotArea(); - if (area == null) { - if (!PS.get().hasPlotArea(loc.getWorld())) { - return; - } - if (pistonBlocks) { - try { - for (final Block pulled : event.getBlocks()) { - loc = BukkitUtil.getLocation(pulled.getLocation()); - if (loc.getPlotArea() != null) { - event.setCancelled(true); - return; - } - } - } catch (final Throwable e) { - pistonBlocks = false; - } - } - if (!pistonBlocks && block.getType() != Material.PISTON_BASE) { - final BlockFace dir = event.getDirection(); - loc = BukkitUtil.getLocation(block.getLocation().add(dir.getModX() * 2, dir.getModY() * 2, dir.getModZ() * 2)); - if (loc.getPlotArea() != null) { - event.setCancelled(true); - return; - } - } - return; - } - Plot plot = area.getOwnedPlot(loc); - if (pistonBlocks) { - try { - for (final Block pulled : event.getBlocks()) { - loc = BukkitUtil.getLocation(pulled.getLocation()); - if (!area.contains(loc.getX(), loc.getZ())) { - event.setCancelled(true); - return; - } - Plot newPlot = area.getOwnedPlot(loc); - if (!Objects.equals(plot, newPlot)) { - event.setCancelled(true); - return; - } - } - } catch (final Throwable e) { - pistonBlocks = false; - } - } - if (!pistonBlocks && block.getType() != Material.PISTON_BASE) { - final BlockFace dir = event.getDirection(); - loc = BukkitUtil.getLocation(block.getLocation().add(dir.getModX() * 2, dir.getModY() * 2, dir.getModZ() * 2)); - if (!area.contains(loc)) { - event.setCancelled(true); - return; - } - Plot newPlot = area.getOwnedPlot(loc); - if (!Objects.equals(plot, newPlot)) { - event.setCancelled(true); - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockDispense(final BlockDispenseEvent e) { - Material type = e.getItem().getType(); - if (type != Material.WATER_BUCKET && type != Material.LAVA_BUCKET) { - return; - } - final Location loc = BukkitUtil.getLocation(e.getVelocity().toLocation(e.getBlock().getWorld())); - if (loc.isPlotRoad()) { - e.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onStructureGrow(final StructureGrowEvent e) { - if (!PS.get().hasPlotArea(e.getWorld().getName())) { - return; - } - final List blocks = e.getBlocks(); - if (blocks.isEmpty()) { - return; - } - Location loc = BukkitUtil.getLocation(blocks.get(0).getLocation()); - PlotArea area = loc.getPlotArea(); - if (area == null) { - for (int i = blocks.size() - 1; i >= 0; i--) { - loc = BukkitUtil.getLocation(blocks.get(i).getLocation()); - if (loc.getPlotArea() != null) { - blocks.remove(i); - } - } - } else { - Plot origin = area.getOwnedPlot(loc); - if (origin == null) { - e.setCancelled(true); - return; - } - for (int i = blocks.size() - 1; i >= 0; i--) { - loc = BukkitUtil.getLocation(blocks.get(i).getLocation()); - if (!area.contains(loc.getX(), loc.getZ())) { - blocks.remove(i); - continue; - } - final Plot plot = area.getOwnedPlot(loc); - if (!Objects.equals(plot, origin)) { - e.getBlocks().remove(i); - } - } - } - final Plot origin = area.getPlotAbs(loc); - if (origin == null) { - e.setCancelled(true); - return; - } - for (int i = blocks.size() - 1; i >= 0; i--) { - loc = BukkitUtil.getLocation(blocks.get(i).getLocation()); - final Plot plot = area.getOwnedPlot(loc); - if (!Objects.equals(plot, origin)) { - e.getBlocks().remove(i); - } - } - } - - @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) - public void onInteract(final PlayerInteractEvent event) { - final Player player = event.getPlayer(); - final PlotPlayer pp = BukkitUtil.getPlayer(player); - PlotArea area = pp.getPlotAreaAbs(); - if (area == null) { - return; - } - PlayerBlockEventType eventType = null; - BukkitLazyBlock lb; - Location loc; - final Action action = event.getAction(); - switch (action) { - case PHYSICAL: { - eventType = PlayerBlockEventType.TRIGGER_PHYSICAL; - Block block = event.getClickedBlock(); - lb = new BukkitLazyBlock(block); - loc = BukkitUtil.getLocation(block.getLocation()); - break; - } - case RIGHT_CLICK_BLOCK: { - Block block = event.getClickedBlock(); - loc = BukkitUtil.getLocation(block.getLocation()); - final Material blockType = block.getType(); - final int blockId = blockType.getId(); - switch (blockType) { - case ANVIL: - case ACACIA_DOOR: - case BIRCH_DOOR: - case DARK_OAK_DOOR: - case IRON_DOOR: - case JUNGLE_DOOR: - case SPRUCE_DOOR: - case TRAP_DOOR: - case IRON_TRAPDOOR: - case WOOD_DOOR: - case WOODEN_DOOR: - case TRAPPED_CHEST: - case ENDER_CHEST: - case CHEST: - case ACACIA_FENCE_GATE: - case BIRCH_FENCE_GATE: - case DARK_OAK_FENCE_GATE: - case FENCE_GATE: - case JUNGLE_FENCE_GATE: - case SPRUCE_FENCE_GATE: - case LEVER: - case DIODE: - case DIODE_BLOCK_OFF: - case DIODE_BLOCK_ON: - case COMMAND: - case REDSTONE_COMPARATOR: - case REDSTONE_COMPARATOR_OFF: - case REDSTONE_COMPARATOR_ON: - case REDSTONE_ORE: - case WOOD_BUTTON: - case STONE_BUTTON: - case BEACON: - case BED_BLOCK: - case SIGN: - case WALL_SIGN: - case SIGN_POST: - case ENCHANTMENT_TABLE: - case BREWING_STAND: - case STANDING_BANNER: - case BURNING_FURNACE: - case FURNACE: - case CAKE_BLOCK: - case DISPENSER: - case DROPPER: - case HOPPER: - case NOTE_BLOCK: - case JUKEBOX: - case WORKBENCH: - eventType = PlayerBlockEventType.INTERACT_BLOCK; - break; - case DRAGON_EGG: - eventType = PlayerBlockEventType.TELEPORT_OBJECT; - break; - default: - if (blockId > 197) { - eventType = PlayerBlockEventType.INTERACT_BLOCK; - } - break; - } - lb = new BukkitLazyBlock(blockId, block); - final ItemStack hand = player.getItemInHand(); - if (eventType != null && !player.isSneaking()) { - break; - } - Material type = hand == null ? null : hand.getType(); - int id = type == null ? 0 : type.getId(); - if (id == 0) { - eventType = PlayerBlockEventType.INTERACT_BLOCK; - lb = new BukkitLazyBlock(id, block); - break; - } else if (id < 198) { - loc = BukkitUtil.getLocation(block.getRelative(event.getBlockFace()).getLocation()); - eventType = PlayerBlockEventType.PLACE_BLOCK; - lb = new BukkitLazyBlock(id, block); - break; - } - Material handType = hand.getType(); - lb = new BukkitLazyBlock(new PlotBlock((short) handType.getId(), (byte) 0)); - switch (handType) { - case MONSTER_EGG: - case MONSTER_EGGS: - eventType = PlayerBlockEventType.SPAWN_MOB; - break; - - case ARMOR_STAND: - loc = BukkitUtil.getLocation(block.getRelative(event.getBlockFace()).getLocation()); - eventType = PlayerBlockEventType.PLACE_MISC; - break; - - case WRITTEN_BOOK: - case BOOK_AND_QUILL: - case BOOK: - eventType = PlayerBlockEventType.READ; - break; - - case APPLE: - case BAKED_POTATO: - case MUSHROOM_SOUP: - case BREAD: - case CARROT: - case CARROT_ITEM: - case COOKIE: - case GRILLED_PORK: - case POISONOUS_POTATO: - case MUTTON: - case PORK: - case POTATO: - case POTATO_ITEM: - case POTION: - case PUMPKIN_PIE: - case RABBIT: - case RABBIT_FOOT: - case RABBIT_STEW: - case RAW_BEEF: - case RAW_FISH: - case RAW_CHICKEN: - eventType = PlayerBlockEventType.EAT; - break; - case MINECART: - case STORAGE_MINECART: - case POWERED_MINECART: - case HOPPER_MINECART: - case EXPLOSIVE_MINECART: - case COMMAND_MINECART: - case BOAT: - eventType = PlayerBlockEventType.PLACE_VEHICLE; - break; - case PAINTING: - case ITEM_FRAME: - loc = BukkitUtil.getLocation(block.getRelative(event.getBlockFace()).getLocation()); - eventType = PlayerBlockEventType.PLACE_HANGING; - break; - default: - eventType = PlayerBlockEventType.INTERACT_BLOCK; - break; - } - break; - } - case LEFT_CLICK_BLOCK: - Block block = event.getClickedBlock(); - loc = BukkitUtil.getLocation(block.getLocation()); - eventType = PlayerBlockEventType.BREAK_BLOCK; - lb = new BukkitLazyBlock(block); - break; - default: - return; - } - if (!EventUtil.manager.checkPlayerBlockEvent(pp, eventType, loc, lb, true)) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void MobSpawn(final CreatureSpawnEvent event) { - final Entity entity = event.getEntity(); - if (entity instanceof Player) { - return; - } - final Location loc = BukkitUtil.getLocation(entity.getLocation()); - final PlotArea area = loc.getPlotArea(); - if (area == null) { - return; - } - final CreatureSpawnEvent.SpawnReason reason = event.getSpawnReason(); - switch (reason) { - case SPAWNER_EGG: - case DISPENSE_EGG: - if (!area.SPAWN_EGGS) { - event.setCancelled(true); - return; - } - break; - case BREEDING: - if (!area.SPAWN_BREEDING) { - event.setCancelled(true); - return; - } - break; - case CUSTOM: - if (!area.SPAWN_CUSTOM && entity.getType().getTypeId() != 30) { - event.setCancelled(true); - return; - } - break; - } - final Plot plot = area.getOwnedPlotAbs(loc); - if (plot == null) { - if (!area.MOB_SPAWNING) { - event.setCancelled(true); - } - return; - } - if (checkEntity(entity, plot)) { - event.setCancelled(true); - } - } - - @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) - public void onEntityFall(final EntityChangeBlockEvent event) { - if (event.getEntityType() != EntityType.FALLING_BLOCK) { - return; - } - final Block block = event.getBlock(); - final World world = block.getWorld(); - final String worldname = world.getName(); - if (!PS.get().hasPlotArea(worldname)) { - return; - } - final Location loc = BukkitUtil.getLocation(block.getLocation()); - PlotArea area = loc.getPlotArea(); - if (area == null) { - return; - } - final Plot plot = area.getOwnedPlotAbs(loc); - if (plot == null) { - event.setCancelled(true); - return; - } - if (FlagManager.isPlotFlagTrue(plot, "disable-physics")) { - event.setCancelled(true); - return; - } - if (event.getTo().hasGravity()) { - Entity entity = event.getEntity(); - List meta = entity.getMetadata("plot"); - if (meta.isEmpty()) { - return; - } - Plot origin = (Plot) meta.get(0).value(); - if (origin != null && !origin.equals(plot)) { - event.setCancelled(true); - entity.remove(); - } - } - else if (event.getTo() == Material.AIR) { - event.getEntity().setMetadata("plot", new FixedMetadataValue((Plugin) PS.get().IMP, plot)); - } - } - - @EventHandler - public void onPrime(final ExplosionPrimeEvent event) { - lastRadius = event.getRadius() + 1; - } - - public boolean checkEntity(Plot plot, String... flags) { - int[] mobs = null; - for (String flag : flags) { - int i; - switch (flag) { - case "entity-cap": - i = 0; - break; - case "mob-cap": - i = 3; - break; - case "hostile-cap": - i = 2; - break; - case "animal-cap": - i = 1; - break; - case "vehicle-cap": - i = 4; - break; - case "misc-cap": - i = 5; - break; - default: - i = 0; - } - final Flag plotFlag = FlagManager.getPlotFlagRaw(plot, flag); - if (plotFlag == null) { - continue; - } - if (mobs == null) { - mobs = plot.countEntities(); - } - if (mobs[i] >= (Integer) plotFlag.getValue()) { - return true; - } - } - return false; - } - - public boolean checkEntity(final Entity entity, final Plot plot) { - if (plot == null || plot.owner == null || plot.settings == null || plot.getFlags().isEmpty() && plot.getArea().DEFAULT_FLAGS - .isEmpty - ()) { - return false; - } - switch (entity.getType()) { - case PLAYER: - return false; - case SMALL_FIREBALL: - case FIREBALL: - case DROPPED_ITEM: - case EGG: - case THROWN_EXP_BOTTLE: - case SPLASH_POTION: - case SNOWBALL: - case ENDER_PEARL: - case ARROW: - // projectile - case PRIMED_TNT: - case FALLING_BLOCK: - // Block entities - case ENDER_CRYSTAL: - case COMPLEX_PART: - case FISHING_HOOK: - case ENDER_SIGNAL: - case EXPERIENCE_ORB: - case LEASH_HITCH: - case FIREWORK: - case WEATHER: - case LIGHTNING: - case WITHER_SKULL: - case UNKNOWN: - // non moving / unremovable - return checkEntity(plot, "entity-cap"); - case ITEM_FRAME: - case PAINTING: - case ARMOR_STAND: - return checkEntity(plot, "entity-cap", "misc-cap"); - // misc - case MINECART: - case MINECART_CHEST: - case MINECART_COMMAND: - case MINECART_FURNACE: - case MINECART_HOPPER: - case MINECART_MOB_SPAWNER: - case MINECART_TNT: - case BOAT: - return checkEntity(plot, "entity-cap", "vehicle-cap"); - case RABBIT: - case SHEEP: - case MUSHROOM_COW: - case OCELOT: - case PIG: - case HORSE: - case SQUID: - case VILLAGER: - case IRON_GOLEM: - case WOLF: - case CHICKEN: - case COW: - case SNOWMAN: - case BAT: - // animal - return checkEntity(plot, "entity-cap", "mob-cap", "animal-cap"); - case BLAZE: - case CAVE_SPIDER: - case CREEPER: - case ENDERMAN: - case ENDERMITE: - case ENDER_DRAGON: - case GHAST: - case GIANT: - case GUARDIAN: - case MAGMA_CUBE: - case PIG_ZOMBIE: - case SILVERFISH: - case SKELETON: - case SLIME: - case SPIDER: - case WITCH: - case WITHER: - case ZOMBIE: - // monster - return checkEntity(plot, "entity-cap", "mob-cap", "hostile-cap"); - default: - String[] types; - if (entity instanceof LivingEntity) { - if (entity instanceof Animals) { - types = new String[] { "entity-cap", "mob-cap", "animal-cap" }; - } else if (entity instanceof Monster) { - types = new String[] { "entity-cap", "mob-cap", "hostile-cap" }; - } else { - types = new String[] { "entity-cap", "mob-cap" }; - } - } else if (entity instanceof Vehicle) { - types = new String[] { "entity-cap", "vehicle-cap" }; - } else if (entity instanceof Hanging) { - types = new String[] { "entity-cap", "misc-cap" }; - } else { - types = new String[] { "entity-cap" }; - } - return checkEntity(plot, types); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockIgnite(final BlockIgniteEvent e) { - final Player player = e.getPlayer(); - final Block b = e.getBlock(); - final Location loc; - if (b != null) { - loc = BukkitUtil.getLocation(b.getLocation()); - } else { - final Entity ent = e.getIgnitingEntity(); - if (ent != null) { - loc = BukkitUtil.getLocation(ent); - } else { - if (player != null) { - loc = BukkitUtil.getLocation(player); - } else { - return; - } - } - } - PlotArea area = loc.getPlotArea(); - if (area == null) { - return; - } - if (e.getCause() == BlockIgniteEvent.IgniteCause.LIGHTNING) { - e.setCancelled(true); - return; - } - if (player == null) { - e.setCancelled(true); - return; - } - final Player p = e.getPlayer(); - final Plot plot = area.getOwnedPlotAbs(loc); - if (plot == null) { - final PlotPlayer pp = BukkitUtil.getPlayer(p); - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_ROAD); - e.setCancelled(true); - } - } else { - if (!plot.hasOwner()) { - final PlotPlayer pp = BukkitUtil.getPlayer(p); - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); - e.setCancelled(true); - } - } else { - final PlotPlayer pp = BukkitUtil.getPlayer(p); - if (!plot.isAdded(pp.getUUID())) { - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); - e.setCancelled(true); - } - } - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onTeleport(final PlayerTeleportEvent event) { - if (event.getTo() == null || event.getFrom() == null) { - BukkitUtil.getPlayer(event.getPlayer()).deleteMeta("location"); - BukkitUtil.getPlayer(event.getPlayer()).deleteMeta("lastplot"); - return; - } - final org.bukkit.Location from = event.getFrom(); - final org.bukkit.Location to = event.getTo(); - int x2; - if (MathMan.roundInt(from.getX()) != (x2 = MathMan.roundInt(to.getX()))) { - final Player player = event.getPlayer(); - final PlotPlayer pp = BukkitUtil.getPlayer(player); - Location loc = BukkitUtil.getLocation(to); - pp.setMeta("location", loc); - PlotArea area = loc.getPlotArea(); - if (area == null) { - return; - } - Plot now = area.getPlotAbs(loc); - final Plot lastPlot = pp.getMeta("lastplot"); - if (now == null) { - if (lastPlot != null && !plotExit(pp, lastPlot) && tmp_teleport) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED); - if (lastPlot.equals(area.getPlot(BukkitUtil.getLocation(from)))) { - tmp_teleport = false; - player.teleport(from); - tmp_teleport = true; - } else { - Location spawn = BukkitUtil.getLocation(player.getWorld().getSpawnLocation()); - if (spawn.getEuclideanDistanceSquared(pp.getLocation()) > 2) { - tmp_teleport = false; - player.teleport(player.getWorld().getSpawnLocation()); - tmp_teleport = true; - } - } - event.setCancelled(true); - return; - } - } else if (lastPlot != null && now.equals(lastPlot)) { - return; - } else { - if (!plotEntry(pp, now) && tmp_teleport) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_ENTRY_DENIED); - if (!now.equals(area.getPlot(BukkitUtil.getLocation(from)))) { - tmp_teleport = false; - player.teleport(from); - tmp_teleport = true; - } else { - Location spawn = BukkitUtil.getLocation(player.getWorld().getSpawnLocation()); - if (spawn.getEuclideanDistanceSquared(pp.getLocation()) > 2) { - tmp_teleport = false; - player.teleport(player.getWorld().getSpawnLocation()); - tmp_teleport = true; - } - } - event.setCancelled(true); - return; - } - } - final Integer border = area.getBorder(); - if (tmp_teleport) { - if (x2 > border) { - to.setX(border - 4); - tmp_teleport = false; - player.teleport(event.getTo()); - tmp_teleport = true; - MainUtil.sendMessage(pp, C.BORDER); - return; - } else if (x2 < -border) { - to.setX(-border + 4); - tmp_teleport = false; - player.teleport(event.getTo()); - tmp_teleport = true; - MainUtil.sendMessage(pp, C.BORDER); - return; - } - } - return; - } - int z2; - if (MathMan.roundInt(from.getZ()) != (z2 = MathMan.roundInt(to.getZ()))) { - final Player player = event.getPlayer(); - final PlotPlayer pp = BukkitUtil.getPlayer(player); - // Set last location - Location loc = BukkitUtil.getLocation(to); - pp.setMeta("location", loc); - final PlotArea area = loc.getPlotArea(); - if (area == null) { - return; - } - Plot now = area.getPlotAbs(loc); - final Plot lastPlot = pp.getMeta("lastplot"); - if (now == null) { - if (lastPlot != null && !plotExit(pp, lastPlot) && tmp_teleport) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED); - if (lastPlot.equals(area.getPlot(BukkitUtil.getLocation(from)))) { - tmp_teleport = false; - player.teleport(from); - tmp_teleport = true; - } else { - Location spawn = BukkitUtil.getLocation(player.getWorld().getSpawnLocation()); - if (spawn.getEuclideanDistanceSquared(pp.getLocation()) > 2) { - tmp_teleport = false; - player.teleport(player.getWorld().getSpawnLocation()); - tmp_teleport = true; - } - } - event.setCancelled(true); - return; - } - } else if (lastPlot != null && now.equals(lastPlot)) { - return; - } else { - if (!plotEntry(pp, now) && tmp_teleport) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_ENTRY_DENIED); - if (!now.equals(area.getPlot(BukkitUtil.getLocation(from)))) { - tmp_teleport = false; - player.teleport(from); - tmp_teleport = true; - } else { - Location spawn = BukkitUtil.getLocation(player.getWorld().getSpawnLocation()); - if (spawn.getEuclideanDistanceSquared(pp.getLocation()) > 2) { - tmp_teleport = false; - player.teleport(player.getWorld().getSpawnLocation()); - tmp_teleport = true; - } - } - event.setCancelled(true); - return; - } - } - final Integer border = area.getBorder(); - if (tmp_teleport) { - if (z2 > border) { - to.setZ(border - 4); - tmp_teleport = false; - player.teleport(event.getTo()); - tmp_teleport = true; - MainUtil.sendMessage(pp, C.BORDER); - } else if (z2 < -border) { - to.setZ(-border + 4); - tmp_teleport = false; - player.teleport(event.getTo()); - tmp_teleport = true; - MainUtil.sendMessage(pp, C.BORDER); - } - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBucketEmpty(final PlayerBucketEmptyEvent e) { - final BlockFace bf = e.getBlockFace(); - final Block b = e.getBlockClicked().getLocation().add(bf.getModX(), bf.getModY(), bf.getModZ()).getBlock(); - final Location loc = BukkitUtil.getLocation(b.getLocation()); - PlotArea area = loc.getPlotArea(); - if (area == null) { - return; - } - final PlotPlayer pp = BukkitUtil.getPlayer(e.getPlayer()); - final Plot plot = area.getPlotAbs(loc); - if (plot == null) { - if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD)) { - return; - } - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_ROAD); - e.setCancelled(true); - } else { - if (!plot.hasOwner()) { - if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED)) { - return; - } - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); - e.setCancelled(true); - } else if (!plot.isAdded(pp.getUUID())) { - final Flag use = FlagManager.getPlotFlagRaw(plot, C.FLAG_USE.s()); - if (use != null && ((HashSet) use.getValue()).contains(new PlotBlock((short) e.getBucket().getId(), (byte) 0))) { - return; - } - if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { - return; - } - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); - e.setCancelled(true); - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onInventoryClick(final InventoryClickEvent event) { - final HumanEntity clicker = event.getWhoClicked(); - if (!(clicker instanceof Player)) { - return; - } - final Player player = (Player) clicker; - final PlotPlayer pp = BukkitUtil.getPlayer(player); - final PlotInventory inv = pp.getMeta("inventory"); - if (inv != null && event.getRawSlot() == event.getSlot()) { - if (!inv.onClick(event.getSlot())) { - event.setCancelled(true); - inv.close(); - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onInventoryClose(final InventoryCloseEvent event) { - final HumanEntity closer = event.getPlayer(); - if (!(closer instanceof Player)) { - return; - } - final Player player = (Player) closer; - BukkitUtil.getPlayer(player).deleteMeta("inventory"); - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onLeave(final PlayerQuitEvent event) { - final PlotPlayer pp = BukkitUtil.getPlayer(event.getPlayer()); - pp.unregister(); - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBucketFill(final PlayerBucketFillEvent e) { - final Block b = e.getBlockClicked(); - final Location loc = BukkitUtil.getLocation(b.getLocation()); - PlotArea area = loc.getPlotArea(); - if (area == null) { - return; - } - final Player p = e.getPlayer(); - final PlotPlayer pp = BukkitUtil.getPlayer(p); - final Plot plot = area.getPlotAbs(loc); - if (plot == null) { - if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD)) { - return; - } - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_ROAD); - e.setCancelled(true); - } else { - if (!plot.hasOwner()) { - if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED)) { - return; - } - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); - e.setCancelled(true); - } else if (!plot.isAdded(pp.getUUID())) { - final Flag use = FlagManager.getPlotFlagRaw(plot, C.FLAG_USE.s()); - final Block block = e.getBlockClicked(); - if (use != null && ((HashSet) use.getValue()).contains(new PlotBlock((short) block.getTypeId(), block.getData()))) { - return; - } - if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { - return; - } - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); - e.setCancelled(true); - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onVehicleCreate(final VehicleCreateEvent event) { - final Vehicle entity = event.getVehicle(); - final Location loc = BukkitUtil.getLocation(entity); - PlotArea area = loc.getPlotArea(); - if (area == null) { - return; - } - Plot plot = area.getOwnedPlotAbs(loc); - if (plot == null) { - entity.remove(); - return; - } - if (checkEntity(entity, plot)) { - entity.remove(); - return; - } - if (Settings.KILL_ROAD_VEHICLES) { - entity.setMetadata("plot", new FixedMetadataValue((Plugin) PS.get().IMP, plot)); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onHangingPlace(final HangingPlaceEvent e) { - final Block b = e.getBlock().getRelative(e.getBlockFace()); - final Location loc = BukkitUtil.getLocation(b.getLocation()); - PlotArea area = loc.getPlotArea(); - if (area == null) { - return; - } - final Player p = e.getPlayer(); - final PlotPlayer pp = BukkitUtil.getPlayer(p); - final Plot plot = area.getPlotAbs(loc); - if (plot == null) { - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_ROAD); - e.setCancelled(true); - } - } else { - if (!plot.hasOwner()) { - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); - e.setCancelled(true); - } - return; - } else if (!plot.isAdded(pp.getUUID())) { - if (!FlagManager.isPlotFlagTrue(plot, C.FLAG_HANGING_PLACE.s())) { - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); - e.setCancelled(true); - } - return; - } - } - if (checkEntity(e.getEntity(), plot)) { - e.setCancelled(true); - } - - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onHangingBreakByEntity(final HangingBreakByEntityEvent e) { - final Entity r = e.getRemover(); - if (r instanceof Player) { - final Player p = (Player) r; - final Location l = BukkitUtil.getLocation(e.getEntity()); - PlotArea area = l.getPlotArea(); - if (area == null) { - return; - } - final PlotPlayer pp = BukkitUtil.getPlayer(p); - final Plot plot = area.getPlotAbs(l); - if (plot == null) { - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_ROAD)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_ROAD); - e.setCancelled(true); - } - } else { - if (!plot.hasOwner()) { - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_UNOWNED)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_UNOWNED); - e.setCancelled(true); - } - } else if (!plot.isAdded(pp.getUUID())) { - if (FlagManager.isPlotFlagTrue(plot, C.FLAG_HANGING_BREAK.s())) { - return; - } - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_OTHER)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_OTHER); - e.setCancelled(true); - } - } - } - } else if (r instanceof Projectile) { - final Projectile p = (Projectile) r; - if (p.getShooter() instanceof Player) { - final Player shooter = (Player) p.getShooter(); - Location loc = BukkitUtil.getLocation(e.getEntity()); - PlotArea area = loc.getPlotArea(); - if (area == null) { - return; - } - final PlotPlayer player = BukkitUtil.getPlayer(shooter); - final Plot plot = area.getPlotAbs(BukkitUtil.getLocation(e.getEntity())); - if (plot != null) { - if (!plot.hasOwner()) { - if (!Permissions.hasPermission(player, C.PERMISSION_ADMIN_DESTROY_UNOWNED)) { - MainUtil.sendMessage(player, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_UNOWNED); - e.setCancelled(true); - } - } else if (!plot.isAdded(player.getUUID())) { - if (!FlagManager.isPlotFlagTrue(plot, C.FLAG_HANGING_BREAK.s())) { - if (!Permissions.hasPermission(player, C.PERMISSION_ADMIN_DESTROY_OTHER)) { - MainUtil.sendMessage(player, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_OTHER); - e.setCancelled(true); - } - } - } - } - } - } else { - e.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onPlayerInteractEntity(final PlayerInteractEntityEvent e) { - final Location l = BukkitUtil.getLocation(e.getRightClicked().getLocation()); - PlotArea area = l.getPlotArea(); - if (area == null) { - return; - } - final Player p = e.getPlayer(); - final PlotPlayer pp = BukkitUtil.getPlayer(p); - final Plot plot = area.getPlotAbs(l); - if (plot == null) { - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_INTERACT_ROAD); - e.setCancelled(true); - } - } else { - if (!plot.hasOwner()) { - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_INTERACT_UNOWNED); - e.setCancelled(true); - } - } else if (!plot.isAdded(pp.getUUID())) { - final Entity entity = e.getRightClicked(); - if (entity instanceof Monster && FlagManager.isPlotFlagTrue(plot, C.FLAG_HOSTILE_INTERACT.s())) { - return; - } - if (entity instanceof Animals && FlagManager.isPlotFlagTrue(plot, C.FLAG_ANIMAL_INTERACT.s())) { - return; - } - if (entity instanceof Tameable && ((Tameable) entity).isTamed() && FlagManager.isPlotFlagTrue(plot, C.FLAG_TAMED_INTERACT.s())) { - return; - } - if (entity instanceof Vehicle && FlagManager.isPlotFlagTrue(plot, C.FLAG_VEHICLE_USE.s())) { - return; - } - if (entity instanceof Player && FlagManager.isPlotFlagTrue(plot, C.FLAG_PLAYER_INTERACT.s())) { - return; - } - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_INTERACT_OTHER); - e.setCancelled(true); - } - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onVehicleDestroy(final VehicleDestroyEvent e) { - final Location l = BukkitUtil.getLocation(e.getVehicle()); - PlotArea area = l.getPlotArea(); - if (area == null) { - return; - } - final Entity d = e.getAttacker(); - if (d instanceof Player) { - final Player p = (Player) d; - final PlotPlayer pp = BukkitUtil.getPlayer(p); - final Plot plot = area.getPlotAbs(l); - if (plot == null) { - if (!Permissions.hasPermission(pp, "plots.admin.vehicle.break.road")) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.vehicle.break.road"); - e.setCancelled(true); - } - } else { - if (!plot.hasOwner()) { - if (!Permissions.hasPermission(pp, "plots.admin.vehicle.break.unowned")) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.vehicle.break.unowned"); - e.setCancelled(true); - return; - } - return; - } - if (!plot.isAdded(pp.getUUID())) { - if (FlagManager.isPlotFlagTrue(plot, "vehicle-break")) { - return; - } - if (!Permissions.hasPermission(pp, "plots.admin.vehicle.break.other")) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.vehicle.break.other"); - e.setCancelled(true); - } - } - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onPotionSplash(final PotionSplashEvent event) { - final ThrownPotion damager = event.getPotion(); - final Location l = BukkitUtil.getLocation(damager); - if (!PS.get().hasPlotArea(l.getWorld())) { - return; - } - for (final LivingEntity victim : event.getAffectedEntities()) { - if (!entityDamage(l, damager, victim)) { - event.setIntensity(victim, 0); - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onEntityDamageByEntityEvent(final EntityDamageByEntityEvent e) { - final Entity damager = e.getDamager(); - final Location l = BukkitUtil.getLocation(damager); - if (!PS.get().hasPlotArea(l.getWorld())) { - return; - } - final Entity victim = e.getEntity(); - if (!entityDamage(l, damager, victim)) { - e.setCancelled(true); - } - } - - public boolean entityDamage(final Location l, final Entity damager, final Entity victim) { - final Location dloc = BukkitUtil.getLocation(damager); - final Location vloc = BukkitUtil.getLocation(victim); - PlotArea dArea = dloc.getPlotArea(); - PlotArea vArea = dArea != null && dArea.contains(vloc.getX(), vloc.getZ()) ? dArea : vloc.getPlotArea(); - if (dArea == null && vArea == null) { - return true; - } - - final Plot dplot = dArea != null ? dArea.getPlot(dloc) : null; - final Plot vplot = vArea != null ? vArea.getPlot(vloc) : null; - - Plot plot; - String stub; - if (dplot == null && vplot == null) { - if (dArea == null) { - return true; - } - plot = null; - stub = "road"; - } else { - // Priorize plots for close to seamless pvp zones - plot = vplot == null ? dplot : dplot == null || !(victim instanceof Player) ? vplot : - victim.getTicksLived() > damager.getTicksLived() ? dplot : vplot; - stub = plot.hasOwner() ? "other" : "unowned"; - } - - Player player; - if (damager instanceof Player) { // attacker is player - player = (Player) damager; - } else if (damager instanceof Projectile) { - final Projectile projectile = (Projectile) damager; - final ProjectileSource shooter = projectile.getShooter(); - if (shooter instanceof Player) { // shooter is player - player = (Player) shooter; - } else { // shooter is not player - player = null; - } - } else { // Attacker is not player - player = null; - } - if (player != null) { - final PlotPlayer pp = BukkitUtil.getPlayer(player); - if (victim instanceof Hanging) { // hanging - if (plot != null && (FlagManager.isPlotFlagTrue(plot, "hanging-break") || plot.isAdded(pp.getUUID()))) { - return true; - } - if (!Permissions.hasPermission(pp, "plots.admin.destroy." + stub)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.destroy." + stub); - return false; - } - } else if (victim.getEntityId() == 30) { - if (plot != null && (FlagManager.isPlotFlagTrue(plot, "misc-break") || plot.isAdded(pp.getUUID()))) { - return true; - } - if (!Permissions.hasPermission(pp, "plots.admin.destroy." + stub)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.destroy." + stub); - return false; - } - } else if (victim instanceof Monster || victim instanceof EnderDragon) { // victim is monster - if (plot != null && (FlagManager.isPlotFlagTrue(plot, "hostile-attack") || FlagManager.isPlotFlagTrue(plot, "pve") || plot - .isAdded(pp.getUUID()))) { - return true; - } - if (!Permissions.hasPermission(pp, "plots.admin.pve." + stub)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); - return false; - } - } else if (victim instanceof Tameable) { // victim is tameable - if (plot != null && (FlagManager.isPlotFlagTrue(plot, "tamed-attack") || FlagManager.isPlotFlagTrue(plot, "pve") || plot - .isAdded(pp.getUUID()))) { - return true; - } - if (!Permissions.hasPermission(pp, "plots.admin.pve." + stub)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); - return false; - } - } else if (victim instanceof Player) { - if (plot != null) { - final Flag pvp = FlagManager.getPlotFlagRaw(plot, C.FLAG_PVP.s()); - if (pvp == null) { - return true; - } else { - if ((Boolean) pvp.getValue()) { - return true; - } else if (!Permissions.hasPermission(pp, "plots.admin.pve." + stub)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); - return false; - } - } - } - if (!Permissions.hasPermission(pp, "plots.admin.pvp." + stub)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.pvp." + stub); - return false; - } - } else if (victim instanceof Creature) { // victim is animal - if (plot != null && (FlagManager.isPlotFlagTrue(plot, "animal-attack") || FlagManager.isPlotFlagTrue(plot, "pve") || plot - .isAdded(pp.getUUID()))) { - return true; - } - if (!Permissions.hasPermission(pp, "plots.admin.pve." + stub)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); - return false; - } - } else if (victim instanceof Vehicle) { // Vehicles are managed in vehicle destroy event - return true; - } else { // victim is something else - if (plot != null && (FlagManager.isPlotFlagTrue(plot, "pve") || plot.isAdded(pp.getUUID()))) { - return true; - } - if (!Permissions.hasPermission(pp, "plots.admin.pve." + stub)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); - return false; - } - } - return true; - } - // player is null - return !(damager instanceof Arrow && !(victim instanceof Creature)); - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onPlayerEggThrow(final PlayerEggThrowEvent e) { - final Location l = BukkitUtil.getLocation(e.getEgg().getLocation()); - PlotArea area = l.getPlotArea(); - if (area == null) { - return; - } - final Player p = e.getPlayer(); - final PlotPlayer pp = BukkitUtil.getPlayer(p); - final Plot plot = area.getPlot(l); - if (plot == null) { - if (!Permissions.hasPermission(pp, "plots.admin.projectile.road")) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.projectile.road"); - e.setHatching(false); - } - } else { - if (!plot.hasOwner()) { - if (!Permissions.hasPermission(pp, "plots.admin.projectile.unowned")) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.projectile.unowned"); - e.setHatching(false); - } - } else if (!plot.isAdded(pp.getUUID())) { - if (!Permissions.hasPermission(pp, "plots.admin.projectile.other")) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.projectile.other"); - e.setHatching(false); - } - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void BlockCreate(final BlockPlaceEvent event) { - final Location loc = BukkitUtil.getLocation(event.getBlock().getLocation()); - PlotArea area = loc.getPlotArea(); - if (area == null) { - return; - } - final Player player = event.getPlayer(); - final PlotPlayer pp = BukkitUtil.getPlayer(player); - final Plot plot = area.getPlotAbs(loc); - if (plot != null) { - if (!plot.hasOwner()) { - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); - event.setCancelled(true); - return; - } - } else if (!plot.isAdded(pp.getUUID())) { - final Flag place = FlagManager.getPlotFlagRaw(plot, C.FLAG_PLACE.s()); - final Block block = event.getBlock(); - if ((place == null || !((HashSet) place.getValue()).contains(new PlotBlock((short) block.getTypeId(), block.getData()))) - && !Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); - event.setCancelled(true); - return; - } - } else if (Settings.DONE_RESTRICTS_BUILDING && plot.getFlags().containsKey("done")) { - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); - event.setCancelled(true); - return; - } - } - if (FlagManager.isPlotFlagTrue(plot, C.FLAG_DISABLE_PHYSICS.s())) { - final Block block = event.getBlockPlaced(); - if (block.getType().hasGravity()) { - sendBlockChange(block.getLocation(), block.getType(), block.getData()); - } - } - if (loc.getY() > area.MAX_BUILD_HEIGHT && loc.getY() < area.MIN_BUILD_HEIGHT && !Permissions - .hasPermission(pp, C.PERMISSION_ADMIN_BUILD_HEIGHTLIMIT)) { - event.setCancelled(true); - MainUtil.sendMessage(pp, C.HEIGHT_LIMIT.s().replace("{limit}", "" + area.MAX_BUILD_HEIGHT)); - } - } else if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_ROAD); - event.setCancelled(true); - } - } -} +package com.plotsquared.bukkit.listeners; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map.Entry; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.BlockState; +import org.bukkit.command.PluginCommand; +import org.bukkit.entity.Animals; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.Creature; +import org.bukkit.entity.EnderDragon; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Hanging; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Monster; +import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; +import org.bukkit.entity.TNTPrimed; +import org.bukkit.entity.Tameable; +import org.bukkit.entity.ThrownPotion; +import org.bukkit.entity.Vehicle; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockDamageEvent; +import org.bukkit.event.block.BlockDispenseEvent; +import org.bukkit.event.block.BlockFadeEvent; +import org.bukkit.event.block.BlockFormEvent; +import org.bukkit.event.block.BlockFromToEvent; +import org.bukkit.event.block.BlockGrowEvent; +import org.bukkit.event.block.BlockIgniteEvent; +import org.bukkit.event.block.BlockPhysicsEvent; +import org.bukkit.event.block.BlockPistonExtendEvent; +import org.bukkit.event.block.BlockPistonRetractEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.block.BlockRedstoneEvent; +import org.bukkit.event.block.BlockSpreadEvent; +import org.bukkit.event.block.EntityBlockFormEvent; +import org.bukkit.event.entity.CreatureSpawnEvent; +import org.bukkit.event.entity.EntityChangeBlockEvent; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.event.entity.ExplosionPrimeEvent; +import org.bukkit.event.entity.PotionSplashEvent; +import org.bukkit.event.entity.ProjectileHitEvent; +import org.bukkit.event.hanging.HangingBreakByEntityEvent; +import org.bukkit.event.hanging.HangingPlaceEvent; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.event.player.PlayerBucketEmptyEvent; +import org.bukkit.event.player.PlayerBucketFillEvent; +import org.bukkit.event.player.PlayerChangedWorldEvent; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import org.bukkit.event.player.PlayerEggThrowEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.event.vehicle.VehicleCreateEvent; +import org.bukkit.event.vehicle.VehicleDestroyEvent; +import org.bukkit.event.world.StructureGrowEvent; +import org.bukkit.help.HelpTopic; +import org.bukkit.inventory.ItemStack; +import org.bukkit.metadata.FixedMetadataValue; +import org.bukkit.metadata.MetadataValue; +import org.bukkit.plugin.Plugin; +import org.bukkit.projectiles.BlockProjectileSource; +import org.bukkit.projectiles.ProjectileSource; +import org.bukkit.util.Vector; + +import com.intellectualcrafters.plot.PS; +import com.intellectualcrafters.plot.config.C; +import com.intellectualcrafters.plot.config.Settings; +import com.intellectualcrafters.plot.flag.Flag; +import com.intellectualcrafters.plot.flag.FlagManager; +import com.intellectualcrafters.plot.object.Location; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotArea; +import com.intellectualcrafters.plot.object.PlotBlock; +import com.intellectualcrafters.plot.object.PlotHandler; +import com.intellectualcrafters.plot.object.PlotId; +import com.intellectualcrafters.plot.object.PlotInventory; +import com.intellectualcrafters.plot.object.PlotPlayer; +import com.intellectualcrafters.plot.object.StringWrapper; +import com.intellectualcrafters.plot.util.EventUtil; +import com.intellectualcrafters.plot.util.ExpireManager; +import com.intellectualcrafters.plot.util.MainUtil; +import com.intellectualcrafters.plot.util.MathMan; +import com.intellectualcrafters.plot.util.Permissions; +import com.intellectualcrafters.plot.util.RegExUtil; +import com.intellectualcrafters.plot.util.StringMan; +import com.intellectualcrafters.plot.util.TaskManager; +import com.intellectualcrafters.plot.util.UUIDHandler; +import com.plotsquared.bukkit.BukkitMain; +import com.plotsquared.bukkit.object.BukkitLazyBlock; +import com.plotsquared.bukkit.object.BukkitPlayer; +import com.plotsquared.bukkit.util.BukkitUtil; +import com.plotsquared.listener.PlayerBlockEventType; + +/** + * Player Events involving plots + * + */ +@SuppressWarnings({ "deprecation", "unchecked" }) +public class PlayerEvents extends com.plotsquared.listener.PlotListener implements Listener { + + private boolean pistonBlocks = true; + private float lastRadius; + // To prevent recursion + private boolean tmp_teleport = true; + + public static void sendBlockChange(final org.bukkit.Location bloc, final Material type, final byte data) { + TaskManager.runTaskLater(new Runnable() { + @Override + public void run() { + final String world = bloc.getWorld().getName(); + final int x = bloc.getBlockX(); + final int z = bloc.getBlockZ(); + final int distance = Bukkit.getViewDistance() * 16; + for (Entry entry : UUIDHandler.getPlayers().entrySet()) { + PlotPlayer player = entry.getValue(); + final Location loc = player.getLocation(); + if (loc.getWorld().equals(world)) { + if (16 * Math.abs(loc.getX() - x) / 16 > distance || 16 * Math.abs(loc.getZ() - z) / 16 > distance) { + continue; + } + ((BukkitPlayer) player).player.sendBlockChange(bloc, type, data); + } + } + } + }, 3); + } + + @EventHandler + public void onRedstoneEvent(final BlockRedstoneEvent event) { + final Block block = event.getBlock(); + switch (block.getType()) { + case REDSTONE_LAMP_OFF: + case REDSTONE_WIRE: + case REDSTONE_LAMP_ON: + case PISTON_BASE: + case PISTON_STICKY_BASE: + case IRON_DOOR_BLOCK: + case LEVER: + case WOODEN_DOOR: + case FENCE_GATE: + case WOOD_BUTTON: + case STONE_BUTTON: + case IRON_PLATE: + case WOOD_PLATE: + case STONE_PLATE: + case GOLD_PLATE: + case SPRUCE_DOOR: + case BIRCH_DOOR: + case JUNGLE_DOOR: + case ACACIA_DOOR: + case DARK_OAK_DOOR: + case IRON_TRAPDOOR: + case SPRUCE_FENCE_GATE: + case BIRCH_FENCE_GATE: + case JUNGLE_FENCE_GATE: + case ACACIA_FENCE_GATE: + case DARK_OAK_FENCE_GATE: + case POWERED_RAIL: + return; + default: + final Location loc = BukkitUtil.getLocation(block.getLocation()); + PlotArea area = loc.getPlotArea(); + if (area == null) { + return; + } + final Plot plot = area.getOwnedPlotAbs(loc); + if (plot == null) { + return; + } + final Flag redstone = FlagManager.getPlotFlagRaw(plot, "redstone"); + if (redstone != null) { + if ((Boolean) redstone.getValue()) { + return; + } else { + event.setNewCurrent(0); + return; + } + } + if (Settings.REDSTONE_DISABLER) { + if (UUIDHandler.getPlayer(plot.owner) == null) { + boolean disable = true; + for (final UUID trusted : plot.getTrusted()) { + if (UUIDHandler.getPlayer(trusted) != null) { + disable = false; + break; + } + } + if (disable) { + event.setNewCurrent(0); + return; + } + } + } + if (Settings.REDSTONE_DISABLER_UNOCCUPIED) { + for (Entry entry : UUIDHandler.getPlayers().entrySet()) { + if (plot.equals(entry.getValue().getCurrentPlot())) { + return; + } + } + event.setNewCurrent(0); + } + } + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) + public void onPhysicsEvent(final BlockPhysicsEvent event) { + switch (event.getChangedType()) { + case REDSTONE_COMPARATOR_OFF: + case REDSTONE_COMPARATOR_ON: { + final Block block = event.getBlock(); + final Location loc = BukkitUtil.getLocation(block.getLocation()); + PlotArea area = loc.getPlotArea(); + if (area == null) { + return; + } + final Plot plot = area.getOwnedPlotAbs(loc); + if (plot == null) { + return; + } + if (FlagManager.isPlotFlagFalse(plot, "redstone")) { + event.setCancelled(true); + } + return; + } + case DRAGON_EGG: + case ANVIL: + case SAND: + case GRAVEL: + final Block block = event.getBlock(); + final Location loc = BukkitUtil.getLocation(block.getLocation()); + PlotArea area = loc.getPlotArea(); + if (area == null) { + return; + } + final Plot plot = area.getOwnedPlotAbs(loc); + if (plot != null && FlagManager.isPlotFlagTrue(plot, "disable-physics")) { + event.setCancelled(true); + return; + } + return; + default: + break; + } + } + + @EventHandler + public void onProjectileHit(final ProjectileHitEvent event) { + final Projectile entity = event.getEntity(); + final Location loc = BukkitUtil.getLocation(entity); + if (!PS.get().hasPlotArea(loc.getWorld())) { + return; + } + PlotArea area = loc.getPlotArea(); + if (area == null) { + return; + } + Plot plot = area.getPlotAbs(loc); + // + final ProjectileSource shooter = entity.getShooter(); + if (shooter instanceof Player) { + final PlotPlayer pp = BukkitUtil.getPlayer((Player) shooter); + if (plot == null) { + if (!Permissions.hasPermission(pp, C.PERMISSION_PROJECTILE_UNOWNED)) { + entity.remove(); + } + return; + } + if (plot.isAdded(pp.getUUID()) || Permissions.hasPermission(pp, C.PERMISSION_PROJECTILE_OTHER)) { + return; + } + entity.remove(); + } else if (!(shooter instanceof Entity) && shooter != null) { + if (plot == null) { + entity.remove(); + return; + } + final Location sLoc = BukkitUtil.getLocation(((BlockProjectileSource) shooter).getBlock().getLocation()); + if (!area.contains(sLoc.getX(), sLoc.getZ())) { + entity.remove(); + return; + } + final Plot sPlot = area.getOwnedPlotAbs(sLoc); + if (sPlot == null || !PlotHandler.sameOwners(plot, sPlot)) { + entity.remove(); + } + } + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) + public void PlayerCommand(final PlayerCommandPreprocessEvent event) { + String msg = event.getMessage().toLowerCase().replaceAll("/", "").trim(); + if (msg.isEmpty()) { + return; + } + final String[] split = msg.split(" "); + final PluginCommand cmd = Bukkit.getServer().getPluginCommand(split[0]); + if (cmd == null) { + if (split[0].equals("plotme") || split[0].equals("ap")) { + final Player player = event.getPlayer(); + if (Settings.USE_PLOTME_ALIAS) { + player.performCommand("plots " + StringMan.join(Arrays.copyOfRange(split, 1, split.length), " ")); + } else { + MainUtil.sendMessage(BukkitUtil.getPlayer(player), C.NOT_USING_PLOTME); + } + event.setCancelled(true); + return; + } + } + final Player player = event.getPlayer(); + final BukkitPlayer pp = (BukkitPlayer) BukkitUtil.getPlayer(player); + Plot plot = pp.getCurrentPlot(); + if (plot == null) { + return; + } + Flag flag = FlagManager.getPlotFlagRaw(plot, "blocked-cmds"); + if (flag == null || Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_BLOCKED_CMDS)) { + return; + } + final List v = (List) flag.getValue(); + final String[] parts = msg.split(" "); + String c = parts[0]; + if (parts[0].contains(":")) { + c = parts[0].split(":")[1]; + msg = msg.replace(parts[0].split(":")[0] + ":", ""); + } + final String l = c; + final List aliases = new ArrayList<>(); + for (final HelpTopic cmdLabel : Bukkit.getServer().getHelpMap().getHelpTopics()) { + if (c.equals(cmdLabel.getName())) { + break; + } + PluginCommand p; + final String label = cmdLabel.getName().replaceFirst("/", ""); + if (aliases.contains(label)) { + continue; + } + if ((p = Bukkit.getPluginCommand(label)) != null) { + for (String a : p.getAliases()) { + if (aliases.contains(a)) { + continue; + } + aliases.add(a); + a = a.replaceFirst("/", ""); + if (!a.equals(label) && a.equals(c)) { + c = label; + break; + } + } + } + } + if (!l.equals(c)) { + msg = msg.replace(l, c); + } + for (final String s : v) { + Pattern pattern; + if (!RegExUtil.compiledPatterns.containsKey(s)) { + RegExUtil.compiledPatterns.put(s, pattern = Pattern.compile(s)); + } else { + pattern = RegExUtil.compiledPatterns.get(s); + } + if (pattern.matcher(msg).matches()) { + MainUtil.sendMessage(pp, C.COMMAND_BLOCKED); + String perm; + if (plot.isAdded(pp.getUUID())) { + perm = "plots.admin.command.blocked-cmds.shared"; + } else { + perm = "plots.admin.command.blocked-cmds.other"; + } + if (!Permissions.hasPermission(pp, perm)) { + event.setCancelled(true); + } + return; + } + } + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onConnect(final PlayerJoinEvent event) { + final Player player = event.getPlayer(); + BukkitUtil.getPlayer(event.getPlayer()).unregister(); + final PlotPlayer pp = BukkitUtil.getPlayer(player); + // Now + String name = pp.getName(); + StringWrapper sw = new StringWrapper(name); + final UUID uuid = pp.getUUID(); + UUIDHandler.add(sw, uuid); + + Location loc = pp.getLocation(); + PlotArea area = loc.getPlotArea(); + final Plot plot; + if (area != null) { + plot = area.getPlot(loc); + if (plot != null) { + plotEntry(pp, plot); + } + } else { + plot = null; + } + // Delayed + + // Async + TaskManager.runTaskLaterAsync(new Runnable() { + @Override + public void run() { + if (!player.hasPlayedBefore() && player.isOnline()) { + player.saveData(); + } + ExpireManager.dates.put(uuid, System.currentTimeMillis()); + if (BukkitMain.worldEdit != null) { + if (pp.getAttribute("worldedit")) { + MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASSED); + } + } + if (PS.get().update != null && Permissions.hasPermission(pp, C.PERMISSION_ADMIN_UPDATE) && Settings.UPDATE_NOTIFICATIONS) { + MainUtil.sendMessage(pp, "&6An update for PlotSquared is available: &7/plot update"); + } + if (Settings.TELEPORT_ON_LOGIN && plot != null) { + TaskManager.runTask(new Runnable() { + @Override + public void run() { + plot.teleportPlayer(pp); + } + }); + MainUtil.sendMessage(pp, C.TELEPORTED_TO_ROAD); + } + } + }, 20); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void PlayerMove(final PlayerMoveEvent event) { + final org.bukkit.Location from = event.getFrom(); + final org.bukkit.Location to = event.getTo(); + int x2; + if (MathMan.roundInt(from.getX()) != (x2 = MathMan.roundInt(to.getX()))) { + final Player player = event.getPlayer(); + final PlotPlayer pp = BukkitUtil.getPlayer(player); + + // Cancel teleport + TaskManager.TELEPORT_QUEUE.remove(pp.getName()); + + // Set last location + Location loc = BukkitUtil.getLocation(to); + pp.setMeta("location", loc); + PlotArea area = loc.getPlotArea(); + if (area == null) { + pp.deleteMeta("lastplot"); + return; + } + Plot now = area.getPlotAbs(loc); + final Plot lastPlot = pp.getMeta("lastplot"); + if (now == null) { + if (lastPlot != null && !plotExit(pp, lastPlot)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED); + if (lastPlot.equals(BukkitUtil.getLocation(from).getPlot())) { + player.teleport(from); + } else { + player.teleport(player.getWorld().getSpawnLocation()); + } + event.setCancelled(true); + return; + } + } else if (now.equals(lastPlot)) { + return; + } else if (!plotEntry(pp, now)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_ENTRY_DENIED); + player.teleport(from); + event.setCancelled(true); + return; + } + final Integer border = area.getBorder(); + if (x2 > border) { + to.setX(border - 4); + player.teleport(event.getTo()); + MainUtil.sendMessage(pp, C.BORDER); + return; + } else if (x2 < -border) { + to.setX(-border + 4); + player.teleport(event.getTo()); + MainUtil.sendMessage(pp, C.BORDER); + return; + } + return; + } + int z2; + if (MathMan.roundInt(from.getZ()) != (z2 = MathMan.roundInt(to.getZ()))) { + final Player player = event.getPlayer(); + final PlotPlayer pp = BukkitUtil.getPlayer(player); + + // Cancel teleport + TaskManager.TELEPORT_QUEUE.remove(pp.getName()); + + // Set last location + Location loc = BukkitUtil.getLocation(to); + pp.setMeta("location", loc); + + PlotArea area = loc.getPlotArea(); + if (area == null) { + pp.deleteMeta("lastplot"); + return; + } + Plot now = area.getPlotAbs(loc); + final Plot lastPlot = pp.getMeta("lastplot"); + if (now == null) { + if (lastPlot != null && !plotExit(pp, lastPlot)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED); + if (lastPlot.equals(BukkitUtil.getLocation(from).getPlot())) { + player.teleport(from); + } else { + player.teleport(player.getWorld().getSpawnLocation()); + } + event.setCancelled(true); + return; + } + } else if (now.equals(lastPlot)) { + return; + } else if (!plotEntry(pp, now)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_ENTRY_DENIED); + player.teleport(from); + event.setCancelled(true); + return; + } + final Integer border = area.getBorder(); + if (z2 > border) { + to.setZ(border - 4); + player.teleport(event.getTo()); + MainUtil.sendMessage(pp, C.BORDER); + } else if (z2 < -border) { + to.setZ(-border + 4); + player.teleport(event.getTo()); + MainUtil.sendMessage(pp, C.BORDER); + } + } + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onChat(final AsyncPlayerChatEvent event) { + final Player player = event.getPlayer(); + final PlotPlayer plr = BukkitUtil.getPlayer(player); + Location loc = plr.getLocation(); + PlotArea area = loc.getPlotArea(); + if (area == null || !area.PLOT_CHAT && !plr.getAttribute("chat")) { + return; + } + final Plot plot = area.getPlotAbs(loc); + if (plot == null) { + return; + } + final String message = event.getMessage(); + String format = C.PLOT_CHAT_FORMAT.s(); + final String sender = event.getPlayer().getDisplayName(); + final PlotId id = plot.getId(); + final Set recipients = event.getRecipients(); + recipients.clear(); + for (final Player p : Bukkit.getOnlinePlayers()) { + final PlotPlayer pp = BukkitUtil.getPlayer(p); + if (pp.getAttribute("chatspy")) { + String spy = event.getFormat(); + spy = String.format(spy, sender, message); + pp.sendMessage(spy); + } else if (plot.equals(pp.getCurrentPlot())) { + recipients.add(p); + } + } + format = format.replaceAll("%plot_id%", id.x + ";" + id.y).replaceAll("%sender%", "%s").replaceAll("%msg%", "%s"); + format = ChatColor.translateAlternateColorCodes('&', format); + event.setFormat(format); + } + + @EventHandler(priority = EventPriority.LOWEST) + public void BlockDestroy(final BlockBreakEvent event) { + final Player player = event.getPlayer(); + final Location loc = BukkitUtil.getLocation(event.getBlock().getLocation()); + PlotArea area = loc.getPlotArea(); + if (area == null) { + return; + } + final Plot plot = area.getPlotAbs(loc); + if (plot != null) { + if (event.getBlock().getY() == 0) { + event.setCancelled(true); + return; + } + final PlotPlayer pp = BukkitUtil.getPlayer(player); + if (!plot.hasOwner()) { + if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_UNOWNED)) { + return; + } + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_UNOWNED); + event.setCancelled(true); + return; + } else if (!plot.isAdded(pp.getUUID())) { + final Flag destroy = FlagManager.getPlotFlagRaw(plot, "break"); + final Block block = event.getBlock(); + if (destroy != null && ((HashSet) destroy.getValue()) + .contains(new PlotBlock((short) block.getTypeId(), block.getData()))) { + return; + } + if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_OTHER)) { + return; + } + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_OTHER); + event.setCancelled(true); + } else if (Settings.DONE_RESTRICTS_BUILDING && plot.getFlags().containsKey("done")) { + if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); + event.setCancelled(true); + return; + } + } + return; + } + final PlotPlayer pp = BukkitUtil.getPlayer(player); + if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_ROAD)) { + return; + } + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_ROAD); + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBigBoom(final EntityExplodeEvent event) { + Location loc = BukkitUtil.getLocation(event.getLocation()); + PlotArea area = loc.getPlotArea(); + if (area == null) { + if (!PS.get().hasPlotArea(loc.getWorld())) { + return; + } + final Iterator iter = event.blockList().iterator(); + while (iter.hasNext()) { + iter.next(); + if (loc.getPlotArea() != null) { + iter.remove(); + } + } + } else { + Plot plot = area.getOwnedPlot(loc); + if (plot != null) { + if (FlagManager.isPlotFlagTrue(plot, "explosion")) { + List meta = event.getEntity().getMetadata("plot"); + Plot origin; + if (meta.isEmpty()) { + origin = plot; + } else { + origin = (Plot) meta.get(0).value(); + } + if (lastRadius != 0) { + final List nearby = event.getEntity().getNearbyEntities(lastRadius, lastRadius, lastRadius); + for (final Entity near : nearby) { + if (near instanceof TNTPrimed || near.getType() == EntityType.MINECART_TNT) { + if (!near.hasMetadata("plot")) { + near.setMetadata("plot", new FixedMetadataValue((Plugin) PS.get().IMP, plot)); + } + } + } + lastRadius = 0; + } + final Iterator iter = event.blockList().iterator(); + while (iter.hasNext()) { + final Block b = iter.next(); + loc = BukkitUtil.getLocation(b.getLocation()); + if (!area.contains(loc.getX(), loc.getZ()) || !origin.equals(area.getOwnedPlot(loc))) { + iter.remove(); + } + } + } + } else { + event.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onWorldChanged(final PlayerChangedWorldEvent event) { + final Player player = event.getPlayer(); + final PlotPlayer pp = BukkitUtil.getPlayer(player); + + + // Delete last location + pp.deleteMeta("location"); + Plot plot = (Plot) pp.deleteMeta("lastplot"); + if (plot != null) { + plotExit(pp, plot); + } + + if (BukkitMain.worldEdit != null) { + if (!Permissions.hasPermission(pp, C.PERMISSION_WORLDEDIT_BYPASS)) { + if (pp.getAttribute("worldedit")) { + pp.removeAttribute("worldedit"); + } + } + } + if (Settings.PERMISSION_CACHING) { + pp.deleteMeta("perm"); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onPeskyMobsChangeTheWorldLikeWTFEvent(final EntityChangeBlockEvent event) { + final String world = event.getBlock().getWorld().getName(); + if (!PS.get().hasPlotArea(world)) { + return; + } + final Entity e = event.getEntity(); + if (!(e instanceof org.bukkit.entity.FallingBlock)) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onEntityBlockForm(final EntityBlockFormEvent e) { + final String world = e.getBlock().getWorld().getName(); + if (!PS.get().hasPlotArea(world)) { + return; + } + if (BukkitUtil.getLocation(e.getBlock().getLocation()).getPlotArea() != null) { + e.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBS(final BlockSpreadEvent e) { + final Block b = e.getBlock(); + final Location loc = BukkitUtil.getLocation(b.getLocation()); + if (loc.isPlotRoad()) { + e.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBF(final BlockFormEvent e) { + final Block b = e.getBlock(); + final Location loc = BukkitUtil.getLocation(b.getLocation()); + if (loc.isPlotRoad()) { + e.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBD(final BlockDamageEvent event) { + final Player player = event.getPlayer(); + Location loc = BukkitUtil.getLocation(event.getBlock().getLocation()); + if (player == null) { + if (loc.isPlotRoad()) { + event.setCancelled(true); + return; + } + } + PlotArea area = loc.getPlotArea(); + if (area == null) { + return; + } + final Plot plot = area.getPlotAbs(loc); + if (plot != null) { + if (loc.getY() == 0) { + event.setCancelled(true); + return; + } + if (!plot.hasOwner()) { + final PlotPlayer pp = BukkitUtil.getPlayer(player); + if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_UNOWNED)) { + return; + } + event.setCancelled(true); + return; + } + final PlotPlayer pp = BukkitUtil.getPlayer(player); + if (!plot.isAdded(pp.getUUID())) { + final Flag destroy = FlagManager.getPlotFlagRaw(plot, "break"); + final Block block = event.getBlock(); + if (destroy != null && ((HashSet) destroy.getValue()) + .contains(new PlotBlock((short) block.getTypeId(), block.getData()))) { + return; + } + if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_OTHER)) { + return; + } + event.setCancelled(true); + return; + } + return; + } + final PlotPlayer pp = BukkitUtil.getPlayer(player); + if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_ROAD)) { + return; + } + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onFade(final BlockFadeEvent e) { + final Block b = e.getBlock(); + Location loc = BukkitUtil.getLocation(b.getLocation()); + PlotArea area = loc.getPlotArea(); + if (area == null) { + return; + } + if (area.getOwnedPlot(loc) == null) { + e.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onChange(final BlockFromToEvent e) { + final Block b = e.getBlock(); + Location loc = BukkitUtil.getLocation(b.getLocation()); + PlotArea area = loc.getPlotArea(); + if (area == null) { + return; + } + Plot plot = area.getOwnedPlot(loc); + if (plot == null || FlagManager.isPlotFlagTrue(plot, "disable-physics")) { + e.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onGrow(final BlockGrowEvent e) { + final Block b = e.getBlock(); + final Location loc = BukkitUtil.getLocation(b.getLocation()); + if (loc.isUnownedPlotArea()) { + e.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockPistonExtend(final BlockPistonExtendEvent event) { + final Block block = event.getBlock(); + final Location loc = BukkitUtil.getLocation(block.getLocation()); + final BlockFace face = event.getDirection(); + final Vector relative = new Vector(face.getModX(), face.getModY(), face.getModZ()); + PlotArea area = loc.getPlotArea(); + if (area == null) { + if (!PS.get().hasPlotArea(loc.getWorld())) { + return; + } + for (final Block b : event.getBlocks()) { + if (BukkitUtil.getLocation(b.getLocation().add(relative)).getPlotArea() != null) { + event.setCancelled(true); + return; + } + } + } + final Plot plot = area.getOwnedPlot(loc); + if (plot == null) { + event.setCancelled(true); + return; + } + final List blocks = event.getBlocks(); + for (final Block b : blocks) { + final Location bloc = BukkitUtil.getLocation(b.getLocation().add(relative)); + if (!area.contains(bloc.getX(), bloc.getZ())) { + event.setCancelled(true); + return; + } + if (!plot.equals(area.getOwnedPlot(bloc))) { + event.setCancelled(true); + return; + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockPistonRetract(final BlockPistonRetractEvent event) { + final Block block = event.getBlock(); + Location loc = BukkitUtil.getLocation(block.getLocation()); + PlotArea area = loc.getPlotArea(); + if (area == null) { + if (!PS.get().hasPlotArea(loc.getWorld())) { + return; + } + if (pistonBlocks) { + try { + for (final Block pulled : event.getBlocks()) { + loc = BukkitUtil.getLocation(pulled.getLocation()); + if (loc.getPlotArea() != null) { + event.setCancelled(true); + return; + } + } + } catch (final Throwable e) { + pistonBlocks = false; + } + } + if (!pistonBlocks && block.getType() != Material.PISTON_BASE) { + final BlockFace dir = event.getDirection(); + loc = BukkitUtil.getLocation(block.getLocation().add(dir.getModX() * 2, dir.getModY() * 2, dir.getModZ() * 2)); + if (loc.getPlotArea() != null) { + event.setCancelled(true); + return; + } + } + return; + } + Plot plot = area.getOwnedPlot(loc); + if (pistonBlocks) { + try { + for (final Block pulled : event.getBlocks()) { + loc = BukkitUtil.getLocation(pulled.getLocation()); + if (!area.contains(loc.getX(), loc.getZ())) { + event.setCancelled(true); + return; + } + Plot newPlot = area.getOwnedPlot(loc); + if (!Objects.equals(plot, newPlot)) { + event.setCancelled(true); + return; + } + } + } catch (final Throwable e) { + pistonBlocks = false; + } + } + if (!pistonBlocks && block.getType() != Material.PISTON_BASE) { + final BlockFace dir = event.getDirection(); + loc = BukkitUtil.getLocation(block.getLocation().add(dir.getModX() * 2, dir.getModY() * 2, dir.getModZ() * 2)); + if (!area.contains(loc)) { + event.setCancelled(true); + return; + } + Plot newPlot = area.getOwnedPlot(loc); + if (!Objects.equals(plot, newPlot)) { + event.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockDispense(final BlockDispenseEvent e) { + Material type = e.getItem().getType(); + if (type != Material.WATER_BUCKET && type != Material.LAVA_BUCKET) { + return; + } + final Location loc = BukkitUtil.getLocation(e.getVelocity().toLocation(e.getBlock().getWorld())); + if (loc.isPlotRoad()) { + e.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onStructureGrow(final StructureGrowEvent e) { + if (!PS.get().hasPlotArea(e.getWorld().getName())) { + return; + } + final List blocks = e.getBlocks(); + if (blocks.isEmpty()) { + return; + } + Location loc = BukkitUtil.getLocation(blocks.get(0).getLocation()); + PlotArea area = loc.getPlotArea(); + if (area == null) { + for (int i = blocks.size() - 1; i >= 0; i--) { + loc = BukkitUtil.getLocation(blocks.get(i).getLocation()); + if (loc.getPlotArea() != null) { + blocks.remove(i); + } + } + } else { + Plot origin = area.getOwnedPlot(loc); + if (origin == null) { + e.setCancelled(true); + return; + } + for (int i = blocks.size() - 1; i >= 0; i--) { + loc = BukkitUtil.getLocation(blocks.get(i).getLocation()); + if (!area.contains(loc.getX(), loc.getZ())) { + blocks.remove(i); + continue; + } + final Plot plot = area.getOwnedPlot(loc); + if (!Objects.equals(plot, origin)) { + e.getBlocks().remove(i); + } + } + } + final Plot origin = area.getPlotAbs(loc); + if (origin == null) { + e.setCancelled(true); + return; + } + for (int i = blocks.size() - 1; i >= 0; i--) { + loc = BukkitUtil.getLocation(blocks.get(i).getLocation()); + final Plot plot = area.getOwnedPlot(loc); + if (!Objects.equals(plot, origin)) { + e.getBlocks().remove(i); + } + } + } + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + public void onInteract(final PlayerInteractEvent event) { + final Player player = event.getPlayer(); + final PlotPlayer pp = BukkitUtil.getPlayer(player); + PlotArea area = pp.getPlotAreaAbs(); + if (area == null) { + return; + } + PlayerBlockEventType eventType = null; + BukkitLazyBlock lb; + Location loc; + final Action action = event.getAction(); + switch (action) { + case PHYSICAL: { + eventType = PlayerBlockEventType.TRIGGER_PHYSICAL; + Block block = event.getClickedBlock(); + lb = new BukkitLazyBlock(block); + loc = BukkitUtil.getLocation(block.getLocation()); + break; + } + case RIGHT_CLICK_BLOCK: { + Block block = event.getClickedBlock(); + loc = BukkitUtil.getLocation(block.getLocation()); + final Material blockType = block.getType(); + final int blockId = blockType.getId(); + switch (blockType) { + case ANVIL: + case ACACIA_DOOR: + case BIRCH_DOOR: + case DARK_OAK_DOOR: + case IRON_DOOR: + case JUNGLE_DOOR: + case SPRUCE_DOOR: + case TRAP_DOOR: + case IRON_TRAPDOOR: + case WOOD_DOOR: + case WOODEN_DOOR: + case TRAPPED_CHEST: + case ENDER_CHEST: + case CHEST: + case ACACIA_FENCE_GATE: + case BIRCH_FENCE_GATE: + case DARK_OAK_FENCE_GATE: + case FENCE_GATE: + case JUNGLE_FENCE_GATE: + case SPRUCE_FENCE_GATE: + case LEVER: + case DIODE: + case DIODE_BLOCK_OFF: + case DIODE_BLOCK_ON: + case COMMAND: + case REDSTONE_COMPARATOR: + case REDSTONE_COMPARATOR_OFF: + case REDSTONE_COMPARATOR_ON: + case REDSTONE_ORE: + case WOOD_BUTTON: + case STONE_BUTTON: + case BEACON: + case BED_BLOCK: + case SIGN: + case WALL_SIGN: + case SIGN_POST: + case ENCHANTMENT_TABLE: + case BREWING_STAND: + case STANDING_BANNER: + case BURNING_FURNACE: + case FURNACE: + case CAKE_BLOCK: + case DISPENSER: + case DROPPER: + case HOPPER: + case NOTE_BLOCK: + case JUKEBOX: + case WORKBENCH: + eventType = PlayerBlockEventType.INTERACT_BLOCK; + break; + case DRAGON_EGG: + eventType = PlayerBlockEventType.TELEPORT_OBJECT; + break; + default: + if (blockId > 197) { + eventType = PlayerBlockEventType.INTERACT_BLOCK; + } + break; + } + lb = new BukkitLazyBlock(blockId, block); + final ItemStack hand = player.getItemInHand(); + if (eventType != null && !player.isSneaking()) { + break; + } + Material type = hand == null ? null : hand.getType(); + int id = type == null ? 0 : type.getId(); + if (id == 0) { + eventType = PlayerBlockEventType.INTERACT_BLOCK; + lb = new BukkitLazyBlock(id, block); + break; + } else if (id < 198) { + loc = BukkitUtil.getLocation(block.getRelative(event.getBlockFace()).getLocation()); + eventType = PlayerBlockEventType.PLACE_BLOCK; + lb = new BukkitLazyBlock(id, block); + break; + } + Material handType = hand.getType(); + lb = new BukkitLazyBlock(new PlotBlock((short) handType.getId(), (byte) 0)); + switch (handType) { + case MONSTER_EGG: + case MONSTER_EGGS: + eventType = PlayerBlockEventType.SPAWN_MOB; + break; + + case ARMOR_STAND: + loc = BukkitUtil.getLocation(block.getRelative(event.getBlockFace()).getLocation()); + eventType = PlayerBlockEventType.PLACE_MISC; + break; + + case WRITTEN_BOOK: + case BOOK_AND_QUILL: + case BOOK: + eventType = PlayerBlockEventType.READ; + break; + + case APPLE: + case BAKED_POTATO: + case MUSHROOM_SOUP: + case BREAD: + case CARROT: + case CARROT_ITEM: + case COOKIE: + case GRILLED_PORK: + case POISONOUS_POTATO: + case MUTTON: + case PORK: + case POTATO: + case POTATO_ITEM: + case POTION: + case PUMPKIN_PIE: + case RABBIT: + case RABBIT_FOOT: + case RABBIT_STEW: + case RAW_BEEF: + case RAW_FISH: + case RAW_CHICKEN: + eventType = PlayerBlockEventType.EAT; + break; + case MINECART: + case STORAGE_MINECART: + case POWERED_MINECART: + case HOPPER_MINECART: + case EXPLOSIVE_MINECART: + case COMMAND_MINECART: + case BOAT: + eventType = PlayerBlockEventType.PLACE_VEHICLE; + break; + case PAINTING: + case ITEM_FRAME: + loc = BukkitUtil.getLocation(block.getRelative(event.getBlockFace()).getLocation()); + eventType = PlayerBlockEventType.PLACE_HANGING; + break; + default: + eventType = PlayerBlockEventType.INTERACT_BLOCK; + break; + } + break; + } + case LEFT_CLICK_BLOCK: + Block block = event.getClickedBlock(); + loc = BukkitUtil.getLocation(block.getLocation()); + eventType = PlayerBlockEventType.BREAK_BLOCK; + lb = new BukkitLazyBlock(block); + break; + default: + return; + } + if (!EventUtil.manager.checkPlayerBlockEvent(pp, eventType, loc, lb, true)) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void MobSpawn(final CreatureSpawnEvent event) { + final Entity entity = event.getEntity(); + if (entity instanceof Player) { + return; + } + final Location loc = BukkitUtil.getLocation(entity.getLocation()); + final PlotArea area = loc.getPlotArea(); + if (area == null) { + return; + } + final CreatureSpawnEvent.SpawnReason reason = event.getSpawnReason(); + switch (reason) { + case SPAWNER_EGG: + case DISPENSE_EGG: + if (!area.SPAWN_EGGS) { + event.setCancelled(true); + return; + } + break; + case BREEDING: + if (!area.SPAWN_BREEDING) { + event.setCancelled(true); + return; + } + break; + case CUSTOM: + if (!area.SPAWN_CUSTOM && entity.getType().getTypeId() != 30) { + event.setCancelled(true); + return; + } + break; + } + final Plot plot = area.getOwnedPlotAbs(loc); + if (plot == null) { + if (!area.MOB_SPAWNING) { + event.setCancelled(true); + } + return; + } + if (checkEntity(entity, plot)) { + event.setCancelled(true); + } + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) + public void onEntityFall(final EntityChangeBlockEvent event) { + if (event.getEntityType() != EntityType.FALLING_BLOCK) { + return; + } + final Block block = event.getBlock(); + final World world = block.getWorld(); + final String worldname = world.getName(); + if (!PS.get().hasPlotArea(worldname)) { + return; + } + final Location loc = BukkitUtil.getLocation(block.getLocation()); + PlotArea area = loc.getPlotArea(); + if (area == null) { + return; + } + final Plot plot = area.getOwnedPlotAbs(loc); + if (plot == null) { + event.setCancelled(true); + return; + } + if (FlagManager.isPlotFlagTrue(plot, "disable-physics")) { + event.setCancelled(true); + return; + } + if (event.getTo().hasGravity()) { + Entity entity = event.getEntity(); + List meta = entity.getMetadata("plot"); + if (meta.isEmpty()) { + return; + } + Plot origin = (Plot) meta.get(0).value(); + if (origin != null && !origin.equals(plot)) { + event.setCancelled(true); + entity.remove(); + } + } + else if (event.getTo() == Material.AIR) { + event.getEntity().setMetadata("plot", new FixedMetadataValue((Plugin) PS.get().IMP, plot)); + } + } + + @EventHandler + public void onPrime(final ExplosionPrimeEvent event) { + lastRadius = event.getRadius() + 1; + } + + public boolean checkEntity(Plot plot, String... flags) { + int[] mobs = null; + for (String flag : flags) { + int i; + switch (flag) { + case "entity-cap": + i = 0; + break; + case "mob-cap": + i = 3; + break; + case "hostile-cap": + i = 2; + break; + case "animal-cap": + i = 1; + break; + case "vehicle-cap": + i = 4; + break; + case "misc-cap": + i = 5; + break; + default: + i = 0; + } + final Flag plotFlag = FlagManager.getPlotFlagRaw(plot, flag); + if (plotFlag == null) { + continue; + } + if (mobs == null) { + mobs = plot.countEntities(); + } + if (mobs[i] >= (Integer) plotFlag.getValue()) { + return true; + } + } + return false; + } + + public boolean checkEntity(final Entity entity, final Plot plot) { + if (plot == null || plot.owner == null || plot.settings == null || plot.getFlags().isEmpty() && plot.getArea().DEFAULT_FLAGS + .isEmpty + ()) { + return false; + } + switch (entity.getType()) { + case PLAYER: + return false; + case SMALL_FIREBALL: + case FIREBALL: + case DROPPED_ITEM: + case EGG: + case THROWN_EXP_BOTTLE: + case SPLASH_POTION: + case SNOWBALL: + case ENDER_PEARL: + case ARROW: + // projectile + case PRIMED_TNT: + case FALLING_BLOCK: + // Block entities + case ENDER_CRYSTAL: + case COMPLEX_PART: + case FISHING_HOOK: + case ENDER_SIGNAL: + case EXPERIENCE_ORB: + case LEASH_HITCH: + case FIREWORK: + case WEATHER: + case LIGHTNING: + case WITHER_SKULL: + case UNKNOWN: + // non moving / unremovable + return checkEntity(plot, "entity-cap"); + case ITEM_FRAME: + case PAINTING: + case ARMOR_STAND: + return checkEntity(plot, "entity-cap", "misc-cap"); + // misc + case MINECART: + case MINECART_CHEST: + case MINECART_COMMAND: + case MINECART_FURNACE: + case MINECART_HOPPER: + case MINECART_MOB_SPAWNER: + case MINECART_TNT: + case BOAT: + return checkEntity(plot, "entity-cap", "vehicle-cap"); + case RABBIT: + case SHEEP: + case MUSHROOM_COW: + case OCELOT: + case PIG: + case HORSE: + case SQUID: + case VILLAGER: + case IRON_GOLEM: + case WOLF: + case CHICKEN: + case COW: + case SNOWMAN: + case BAT: + // animal + return checkEntity(plot, "entity-cap", "mob-cap", "animal-cap"); + case BLAZE: + case CAVE_SPIDER: + case CREEPER: + case ENDERMAN: + case ENDERMITE: + case ENDER_DRAGON: + case GHAST: + case GIANT: + case GUARDIAN: + case MAGMA_CUBE: + case PIG_ZOMBIE: + case SILVERFISH: + case SKELETON: + case SLIME: + case SPIDER: + case WITCH: + case WITHER: + case ZOMBIE: + // monster + return checkEntity(plot, "entity-cap", "mob-cap", "hostile-cap"); + default: + String[] types; + if (entity instanceof LivingEntity) { + if (entity instanceof Animals) { + types = new String[] { "entity-cap", "mob-cap", "animal-cap" }; + } else if (entity instanceof Monster) { + types = new String[] { "entity-cap", "mob-cap", "hostile-cap" }; + } else { + types = new String[] { "entity-cap", "mob-cap" }; + } + } else if (entity instanceof Vehicle) { + types = new String[] { "entity-cap", "vehicle-cap" }; + } else if (entity instanceof Hanging) { + types = new String[] { "entity-cap", "misc-cap" }; + } else { + types = new String[] { "entity-cap" }; + } + return checkEntity(plot, types); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockIgnite(final BlockIgniteEvent e) { + final Player player = e.getPlayer(); + final Block b = e.getBlock(); + final Location loc; + if (b != null) { + loc = BukkitUtil.getLocation(b.getLocation()); + } else { + final Entity ent = e.getIgnitingEntity(); + if (ent != null) { + loc = BukkitUtil.getLocation(ent); + } else { + if (player != null) { + loc = BukkitUtil.getLocation(player); + } else { + return; + } + } + } + PlotArea area = loc.getPlotArea(); + if (area == null) { + return; + } + if (e.getCause() == BlockIgniteEvent.IgniteCause.LIGHTNING) { + e.setCancelled(true); + return; + } + if (player == null) { + e.setCancelled(true); + return; + } + final Player p = e.getPlayer(); + final Plot plot = area.getOwnedPlotAbs(loc); + if (plot == null) { + final PlotPlayer pp = BukkitUtil.getPlayer(p); + if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_ROAD); + e.setCancelled(true); + } + } else { + if (!plot.hasOwner()) { + final PlotPlayer pp = BukkitUtil.getPlayer(p); + if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); + e.setCancelled(true); + } + } else { + final PlotPlayer pp = BukkitUtil.getPlayer(p); + if (!plot.isAdded(pp.getUUID())) { + if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); + e.setCancelled(true); + } + } + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onTeleport(final PlayerTeleportEvent event) { + if (event.getTo() == null || event.getFrom() == null) { + BukkitUtil.getPlayer(event.getPlayer()).deleteMeta("location"); + BukkitUtil.getPlayer(event.getPlayer()).deleteMeta("lastplot"); + return; + } + final org.bukkit.Location from = event.getFrom(); + final org.bukkit.Location to = event.getTo(); + int x2; + if (MathMan.roundInt(from.getX()) != (x2 = MathMan.roundInt(to.getX()))) { + final Player player = event.getPlayer(); + final PlotPlayer pp = BukkitUtil.getPlayer(player); + Location loc = BukkitUtil.getLocation(to); + pp.setMeta("location", loc); + PlotArea area = loc.getPlotArea(); + if (area == null) { + return; + } + Plot now = area.getPlotAbs(loc); + final Plot lastPlot = pp.getMeta("lastplot"); + if (now == null) { + if (lastPlot != null && !plotExit(pp, lastPlot) && tmp_teleport) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED); + if (lastPlot.equals(area.getPlot(BukkitUtil.getLocation(from)))) { + tmp_teleport = false; + player.teleport(from); + tmp_teleport = true; + } else { + Location spawn = BukkitUtil.getLocation(player.getWorld().getSpawnLocation()); + if (spawn.getEuclideanDistanceSquared(pp.getLocation()) > 2) { + tmp_teleport = false; + player.teleport(player.getWorld().getSpawnLocation()); + tmp_teleport = true; + } + } + event.setCancelled(true); + return; + } + } else if (lastPlot != null && now.equals(lastPlot)) { + return; + } else { + if (!plotEntry(pp, now) && tmp_teleport) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_ENTRY_DENIED); + if (!now.equals(area.getPlot(BukkitUtil.getLocation(from)))) { + tmp_teleport = false; + player.teleport(from); + tmp_teleport = true; + } else { + Location spawn = BukkitUtil.getLocation(player.getWorld().getSpawnLocation()); + if (spawn.getEuclideanDistanceSquared(pp.getLocation()) > 2) { + tmp_teleport = false; + player.teleport(player.getWorld().getSpawnLocation()); + tmp_teleport = true; + } + } + event.setCancelled(true); + return; + } + } + final Integer border = area.getBorder(); + if (tmp_teleport) { + if (x2 > border) { + to.setX(border - 4); + tmp_teleport = false; + player.teleport(event.getTo()); + tmp_teleport = true; + MainUtil.sendMessage(pp, C.BORDER); + return; + } else if (x2 < -border) { + to.setX(-border + 4); + tmp_teleport = false; + player.teleport(event.getTo()); + tmp_teleport = true; + MainUtil.sendMessage(pp, C.BORDER); + return; + } + } + return; + } + int z2; + if (MathMan.roundInt(from.getZ()) != (z2 = MathMan.roundInt(to.getZ()))) { + final Player player = event.getPlayer(); + final PlotPlayer pp = BukkitUtil.getPlayer(player); + // Set last location + Location loc = BukkitUtil.getLocation(to); + pp.setMeta("location", loc); + final PlotArea area = loc.getPlotArea(); + if (area == null) { + return; + } + Plot now = area.getPlotAbs(loc); + final Plot lastPlot = pp.getMeta("lastplot"); + if (now == null) { + if (lastPlot != null && !plotExit(pp, lastPlot) && tmp_teleport) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED); + if (lastPlot.equals(area.getPlot(BukkitUtil.getLocation(from)))) { + tmp_teleport = false; + player.teleport(from); + tmp_teleport = true; + } else { + Location spawn = BukkitUtil.getLocation(player.getWorld().getSpawnLocation()); + if (spawn.getEuclideanDistanceSquared(pp.getLocation()) > 2) { + tmp_teleport = false; + player.teleport(player.getWorld().getSpawnLocation()); + tmp_teleport = true; + } + } + event.setCancelled(true); + return; + } + } else if (lastPlot != null && now.equals(lastPlot)) { + return; + } else { + if (!plotEntry(pp, now) && tmp_teleport) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_ENTRY_DENIED); + if (!now.equals(area.getPlot(BukkitUtil.getLocation(from)))) { + tmp_teleport = false; + player.teleport(from); + tmp_teleport = true; + } else { + Location spawn = BukkitUtil.getLocation(player.getWorld().getSpawnLocation()); + if (spawn.getEuclideanDistanceSquared(pp.getLocation()) > 2) { + tmp_teleport = false; + player.teleport(player.getWorld().getSpawnLocation()); + tmp_teleport = true; + } + } + event.setCancelled(true); + return; + } + } + final Integer border = area.getBorder(); + if (tmp_teleport) { + if (z2 > border) { + to.setZ(border - 4); + tmp_teleport = false; + player.teleport(event.getTo()); + tmp_teleport = true; + MainUtil.sendMessage(pp, C.BORDER); + } else if (z2 < -border) { + to.setZ(-border + 4); + tmp_teleport = false; + player.teleport(event.getTo()); + tmp_teleport = true; + MainUtil.sendMessage(pp, C.BORDER); + } + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBucketEmpty(final PlayerBucketEmptyEvent e) { + final BlockFace bf = e.getBlockFace(); + final Block b = e.getBlockClicked().getLocation().add(bf.getModX(), bf.getModY(), bf.getModZ()).getBlock(); + final Location loc = BukkitUtil.getLocation(b.getLocation()); + PlotArea area = loc.getPlotArea(); + if (area == null) { + return; + } + final PlotPlayer pp = BukkitUtil.getPlayer(e.getPlayer()); + final Plot plot = area.getPlotAbs(loc); + if (plot == null) { + if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD)) { + return; + } + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_ROAD); + e.setCancelled(true); + } else { + if (!plot.hasOwner()) { + if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED)) { + return; + } + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); + e.setCancelled(true); + } else if (!plot.isAdded(pp.getUUID())) { + final Flag use = FlagManager.getPlotFlagRaw(plot, C.FLAG_USE.s()); + if (use != null && ((HashSet) use.getValue()).contains(new PlotBlock((short) e.getBucket().getId(), (byte) 0))) { + return; + } + if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { + return; + } + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); + e.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onInventoryClick(final InventoryClickEvent event) { + final HumanEntity clicker = event.getWhoClicked(); + if (!(clicker instanceof Player)) { + return; + } + final Player player = (Player) clicker; + final PlotPlayer pp = BukkitUtil.getPlayer(player); + final PlotInventory inv = pp.getMeta("inventory"); + if (inv != null && event.getRawSlot() == event.getSlot()) { + if (!inv.onClick(event.getSlot())) { + event.setCancelled(true); + inv.close(); + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onInventoryClose(final InventoryCloseEvent event) { + final HumanEntity closer = event.getPlayer(); + if (!(closer instanceof Player)) { + return; + } + final Player player = (Player) closer; + BukkitUtil.getPlayer(player).deleteMeta("inventory"); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onLeave(final PlayerQuitEvent event) { + final PlotPlayer pp = BukkitUtil.getPlayer(event.getPlayer()); + pp.unregister(); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBucketFill(final PlayerBucketFillEvent e) { + final Block b = e.getBlockClicked(); + final Location loc = BukkitUtil.getLocation(b.getLocation()); + PlotArea area = loc.getPlotArea(); + if (area == null) { + return; + } + final Player p = e.getPlayer(); + final PlotPlayer pp = BukkitUtil.getPlayer(p); + final Plot plot = area.getPlotAbs(loc); + if (plot == null) { + if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD)) { + return; + } + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_ROAD); + e.setCancelled(true); + } else { + if (!plot.hasOwner()) { + if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED)) { + return; + } + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); + e.setCancelled(true); + } else if (!plot.isAdded(pp.getUUID())) { + final Flag use = FlagManager.getPlotFlagRaw(plot, C.FLAG_USE.s()); + final Block block = e.getBlockClicked(); + if (use != null && ((HashSet) use.getValue()).contains(new PlotBlock((short) block.getTypeId(), block.getData()))) { + return; + } + if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { + return; + } + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); + e.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onVehicleCreate(final VehicleCreateEvent event) { + final Vehicle entity = event.getVehicle(); + final Location loc = BukkitUtil.getLocation(entity); + PlotArea area = loc.getPlotArea(); + if (area == null) { + return; + } + Plot plot = area.getOwnedPlotAbs(loc); + if (plot == null) { + entity.remove(); + return; + } + if (checkEntity(entity, plot)) { + entity.remove(); + return; + } + if (Settings.KILL_ROAD_VEHICLES) { + entity.setMetadata("plot", new FixedMetadataValue((Plugin) PS.get().IMP, plot)); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onHangingPlace(final HangingPlaceEvent e) { + final Block b = e.getBlock().getRelative(e.getBlockFace()); + final Location loc = BukkitUtil.getLocation(b.getLocation()); + PlotArea area = loc.getPlotArea(); + if (area == null) { + return; + } + final Player p = e.getPlayer(); + final PlotPlayer pp = BukkitUtil.getPlayer(p); + final Plot plot = area.getPlotAbs(loc); + if (plot == null) { + if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_ROAD); + e.setCancelled(true); + } + } else { + if (!plot.hasOwner()) { + if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); + e.setCancelled(true); + } + return; + } else if (!plot.isAdded(pp.getUUID())) { + if (!FlagManager.isPlotFlagTrue(plot, C.FLAG_HANGING_PLACE.s())) { + if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); + e.setCancelled(true); + } + return; + } + } + if (checkEntity(e.getEntity(), plot)) { + e.setCancelled(true); + } + + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onHangingBreakByEntity(final HangingBreakByEntityEvent e) { + final Entity r = e.getRemover(); + if (r instanceof Player) { + final Player p = (Player) r; + final Location l = BukkitUtil.getLocation(e.getEntity()); + PlotArea area = l.getPlotArea(); + if (area == null) { + return; + } + final PlotPlayer pp = BukkitUtil.getPlayer(p); + final Plot plot = area.getPlotAbs(l); + if (plot == null) { + if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_ROAD)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_ROAD); + e.setCancelled(true); + } + } else { + if (!plot.hasOwner()) { + if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_UNOWNED)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_UNOWNED); + e.setCancelled(true); + } + } else if (!plot.isAdded(pp.getUUID())) { + if (FlagManager.isPlotFlagTrue(plot, C.FLAG_HANGING_BREAK.s())) { + return; + } + if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_OTHER)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_OTHER); + e.setCancelled(true); + } + } + } + } else if (r instanceof Projectile) { + final Projectile p = (Projectile) r; + if (p.getShooter() instanceof Player) { + final Player shooter = (Player) p.getShooter(); + Location loc = BukkitUtil.getLocation(e.getEntity()); + PlotArea area = loc.getPlotArea(); + if (area == null) { + return; + } + final PlotPlayer player = BukkitUtil.getPlayer(shooter); + final Plot plot = area.getPlotAbs(BukkitUtil.getLocation(e.getEntity())); + if (plot != null) { + if (!plot.hasOwner()) { + if (!Permissions.hasPermission(player, C.PERMISSION_ADMIN_DESTROY_UNOWNED)) { + MainUtil.sendMessage(player, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_UNOWNED); + e.setCancelled(true); + } + } else if (!plot.isAdded(player.getUUID())) { + if (!FlagManager.isPlotFlagTrue(plot, C.FLAG_HANGING_BREAK.s())) { + if (!Permissions.hasPermission(player, C.PERMISSION_ADMIN_DESTROY_OTHER)) { + MainUtil.sendMessage(player, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_OTHER); + e.setCancelled(true); + } + } + } + } + } + } else { + e.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onPlayerInteractEntity(final PlayerInteractEntityEvent e) { + final Location l = BukkitUtil.getLocation(e.getRightClicked().getLocation()); + PlotArea area = l.getPlotArea(); + if (area == null) { + return; + } + final Player p = e.getPlayer(); + final PlotPlayer pp = BukkitUtil.getPlayer(p); + final Plot plot = area.getPlotAbs(l); + if (plot == null) { + if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_INTERACT_ROAD); + e.setCancelled(true); + } + } else { + if (!plot.hasOwner()) { + if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_INTERACT_UNOWNED); + e.setCancelled(true); + } + } else if (!plot.isAdded(pp.getUUID())) { + final Entity entity = e.getRightClicked(); + if (entity instanceof Monster && FlagManager.isPlotFlagTrue(plot, C.FLAG_HOSTILE_INTERACT.s())) { + return; + } + if (entity instanceof Animals && FlagManager.isPlotFlagTrue(plot, C.FLAG_ANIMAL_INTERACT.s())) { + return; + } + if (entity instanceof Tameable && ((Tameable) entity).isTamed() && FlagManager.isPlotFlagTrue(plot, C.FLAG_TAMED_INTERACT.s())) { + return; + } + if (entity instanceof Vehicle && FlagManager.isPlotFlagTrue(plot, C.FLAG_VEHICLE_USE.s())) { + return; + } + if (entity instanceof Player && FlagManager.isPlotFlagTrue(plot, C.FLAG_PLAYER_INTERACT.s())) { + return; + } + if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_INTERACT_OTHER); + e.setCancelled(true); + } + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onVehicleDestroy(final VehicleDestroyEvent e) { + final Location l = BukkitUtil.getLocation(e.getVehicle()); + PlotArea area = l.getPlotArea(); + if (area == null) { + return; + } + final Entity d = e.getAttacker(); + if (d instanceof Player) { + final Player p = (Player) d; + final PlotPlayer pp = BukkitUtil.getPlayer(p); + final Plot plot = area.getPlotAbs(l); + if (plot == null) { + if (!Permissions.hasPermission(pp, "plots.admin.vehicle.break.road")) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.vehicle.break.road"); + e.setCancelled(true); + } + } else { + if (!plot.hasOwner()) { + if (!Permissions.hasPermission(pp, "plots.admin.vehicle.break.unowned")) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.vehicle.break.unowned"); + e.setCancelled(true); + return; + } + return; + } + if (!plot.isAdded(pp.getUUID())) { + if (FlagManager.isPlotFlagTrue(plot, "vehicle-break")) { + return; + } + if (!Permissions.hasPermission(pp, "plots.admin.vehicle.break.other")) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.vehicle.break.other"); + e.setCancelled(true); + } + } + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onPotionSplash(final PotionSplashEvent event) { + final ThrownPotion damager = event.getPotion(); + final Location l = BukkitUtil.getLocation(damager); + if (!PS.get().hasPlotArea(l.getWorld())) { + return; + } + for (final LivingEntity victim : event.getAffectedEntities()) { + if (!entityDamage(l, damager, victim)) { + event.setIntensity(victim, 0); + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onEntityDamageByEntityEvent(final EntityDamageByEntityEvent e) { + final Entity damager = e.getDamager(); + final Location l = BukkitUtil.getLocation(damager); + if (!PS.get().hasPlotArea(l.getWorld())) { + return; + } + final Entity victim = e.getEntity(); + if (!entityDamage(l, damager, victim)) { + e.setCancelled(true); + } + } + + public boolean entityDamage(final Location l, final Entity damager, final Entity victim) { + final Location dloc = BukkitUtil.getLocation(damager); + final Location vloc = BukkitUtil.getLocation(victim); + PlotArea dArea = dloc.getPlotArea(); + PlotArea vArea = dArea != null && dArea.contains(vloc.getX(), vloc.getZ()) ? dArea : vloc.getPlotArea(); + if (dArea == null && vArea == null) { + return true; + } + + final Plot dplot = dArea != null ? dArea.getPlot(dloc) : null; + final Plot vplot = vArea != null ? vArea.getPlot(vloc) : null; + + Plot plot; + String stub; + if (dplot == null && vplot == null) { + if (dArea == null) { + return true; + } + plot = null; + stub = "road"; + } else { + // Priorize plots for close to seamless pvp zones + plot = vplot == null ? dplot : dplot == null || !(victim instanceof Player) ? vplot : + victim.getTicksLived() > damager.getTicksLived() ? dplot : vplot; + stub = plot.hasOwner() ? "other" : "unowned"; + } + + Player player; + if (damager instanceof Player) { // attacker is player + player = (Player) damager; + } else if (damager instanceof Projectile) { + final Projectile projectile = (Projectile) damager; + final ProjectileSource shooter = projectile.getShooter(); + if (shooter instanceof Player) { // shooter is player + player = (Player) shooter; + } else { // shooter is not player + player = null; + } + } else { // Attacker is not player + player = null; + } + if (player != null) { + final PlotPlayer pp = BukkitUtil.getPlayer(player); + if (victim instanceof Hanging) { // hanging + if (plot != null && (FlagManager.isPlotFlagTrue(plot, "hanging-break") || plot.isAdded(pp.getUUID()))) { + return true; + } + if (!Permissions.hasPermission(pp, "plots.admin.destroy." + stub)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.destroy." + stub); + return false; + } + } else if (victim.getEntityId() == 30) { + if (plot != null && (FlagManager.isPlotFlagTrue(plot, "misc-break") || plot.isAdded(pp.getUUID()))) { + return true; + } + if (!Permissions.hasPermission(pp, "plots.admin.destroy." + stub)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.destroy." + stub); + return false; + } + } else if (victim instanceof Monster || victim instanceof EnderDragon) { // victim is monster + if (plot != null && (FlagManager.isPlotFlagTrue(plot, "hostile-attack") || FlagManager.isPlotFlagTrue(plot, "pve") || plot + .isAdded(pp.getUUID()))) { + return true; + } + if (!Permissions.hasPermission(pp, "plots.admin.pve." + stub)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); + return false; + } + } else if (victim instanceof Tameable) { // victim is tameable + if (plot != null && (FlagManager.isPlotFlagTrue(plot, "tamed-attack") || FlagManager.isPlotFlagTrue(plot, "pve") || plot + .isAdded(pp.getUUID()))) { + return true; + } + if (!Permissions.hasPermission(pp, "plots.admin.pve." + stub)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); + return false; + } + } else if (victim instanceof Player) { + if (plot != null) { + final Flag pvp = FlagManager.getPlotFlagRaw(plot, C.FLAG_PVP.s()); + if (pvp == null) { + return true; + } else { + if ((Boolean) pvp.getValue()) { + return true; + } else if (!Permissions.hasPermission(pp, "plots.admin.pve." + stub)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); + return false; + } + } + } + if (!Permissions.hasPermission(pp, "plots.admin.pvp." + stub)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.pvp." + stub); + return false; + } + } else if (victim instanceof Creature) { // victim is animal + if (plot != null && (FlagManager.isPlotFlagTrue(plot, "animal-attack") || FlagManager.isPlotFlagTrue(plot, "pve") || plot + .isAdded(pp.getUUID()))) { + return true; + } + if (!Permissions.hasPermission(pp, "plots.admin.pve." + stub)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); + return false; + } + } else if (victim instanceof Vehicle) { // Vehicles are managed in vehicle destroy event + return true; + } else { // victim is something else + if (plot != null && (FlagManager.isPlotFlagTrue(plot, "pve") || plot.isAdded(pp.getUUID()))) { + return true; + } + if (!Permissions.hasPermission(pp, "plots.admin.pve." + stub)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); + return false; + } + } + return true; + } + // player is null + return !(damager instanceof Arrow && !(victim instanceof Creature)); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onPlayerEggThrow(final PlayerEggThrowEvent e) { + final Location l = BukkitUtil.getLocation(e.getEgg().getLocation()); + PlotArea area = l.getPlotArea(); + if (area == null) { + return; + } + final Player p = e.getPlayer(); + final PlotPlayer pp = BukkitUtil.getPlayer(p); + final Plot plot = area.getPlot(l); + if (plot == null) { + if (!Permissions.hasPermission(pp, "plots.admin.projectile.road")) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.projectile.road"); + e.setHatching(false); + } + } else { + if (!plot.hasOwner()) { + if (!Permissions.hasPermission(pp, "plots.admin.projectile.unowned")) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.projectile.unowned"); + e.setHatching(false); + } + } else if (!plot.isAdded(pp.getUUID())) { + if (!Permissions.hasPermission(pp, "plots.admin.projectile.other")) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.projectile.other"); + e.setHatching(false); + } + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void BlockCreate(final BlockPlaceEvent event) { + final Location loc = BukkitUtil.getLocation(event.getBlock().getLocation()); + PlotArea area = loc.getPlotArea(); + if (area == null) { + return; + } + final Player player = event.getPlayer(); + final PlotPlayer pp = BukkitUtil.getPlayer(player); + final Plot plot = area.getPlotAbs(loc); + if (plot != null) { + if (!plot.hasOwner()) { + if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); + event.setCancelled(true); + return; + } + } else if (!plot.isAdded(pp.getUUID())) { + final Flag place = FlagManager.getPlotFlagRaw(plot, C.FLAG_PLACE.s()); + final Block block = event.getBlock(); + if ((place == null || !((HashSet) place.getValue()).contains(new PlotBlock((short) block.getTypeId(), block.getData()))) + && !Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); + event.setCancelled(true); + return; + } + } else if (Settings.DONE_RESTRICTS_BUILDING && plot.getFlags().containsKey("done")) { + if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); + event.setCancelled(true); + return; + } + } + if (FlagManager.isPlotFlagTrue(plot, C.FLAG_DISABLE_PHYSICS.s())) { + final Block block = event.getBlockPlaced(); + if (block.getType().hasGravity()) { + sendBlockChange(block.getLocation(), block.getType(), block.getData()); + } + } + if (loc.getY() > area.MAX_BUILD_HEIGHT && loc.getY() < area.MIN_BUILD_HEIGHT && !Permissions + .hasPermission(pp, C.PERMISSION_ADMIN_BUILD_HEIGHTLIMIT)) { + event.setCancelled(true); + MainUtil.sendMessage(pp, C.HEIGHT_LIMIT.s().replace("{limit}", "" + area.MAX_BUILD_HEIGHT)); + } + } else if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_ROAD); + event.setCancelled(true); + } + } +} diff --git a/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents_1_8.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents_1_8.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents_1_8.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents_1_8.java diff --git a/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents_1_8_3.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents_1_8_3.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents_1_8_3.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents_1_8_3.java diff --git a/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener.java similarity index 97% rename from src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener.java index f1f1309ec..d0d616d18 100644 --- a/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener.java @@ -1,251 +1,251 @@ -//////////////////////////////////////////////////////////////////////////////////////////////////// -// PlotSquared - A plot manager and world generator for the Bukkit API / -// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / -// / -// This program is free software; you can redistribute it and/or modify / -// it under the terms of the GNU General Public License as published by / -// the Free Software Foundation; either version 3 of the License, or / -// (at your option) any later version. / -// / -// This program is distributed in the hope that it will be useful, / -// but WITHOUT ANY WARRANTY; without even the implied warranty of / -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / -// GNU General Public License for more details. / -// / -// You should have received a copy of the GNU General Public License / -// along with this program; if not, write to the Free Software Foundation, / -// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / -// / -// You can contact us via: support@intellectualsites.com / -//////////////////////////////////////////////////////////////////////////////////////////////////// -package com.plotsquared.bukkit.listeners; - -import com.intellectualcrafters.plot.flag.Flag; -import com.intellectualcrafters.plot.flag.FlagManager; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.plotsquared.bukkit.events.PlayerEnterPlotEvent; -import com.plotsquared.bukkit.events.PlayerLeavePlotEvent; -import com.plotsquared.bukkit.util.BukkitUtil; -import com.plotsquared.listener.PlotListener; -import org.bukkit.Bukkit; -import org.bukkit.GameMode; -import org.bukkit.Material; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.BlockDamageEvent; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.event.player.PlayerDropItemEvent; -import org.bukkit.event.player.PlayerPickupItemEvent; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.plugin.java.JavaPlugin; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map.Entry; -import java.util.UUID; - -/** - * Created 2014-10-30 for PlotSquared - * - - */ -@SuppressWarnings({ "deprecation" }) -public class PlotPlusListener extends PlotListener implements Listener { - private final static HashMap feedRunnable = new HashMap<>(); - private final static HashMap healRunnable = new HashMap<>(); - - public static void startRunnable(final JavaPlugin plugin) { - plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { - @Override - public void run() { - if (!healRunnable.isEmpty()) { - for (final Iterator> iter = healRunnable.entrySet().iterator(); iter.hasNext();) { - final Entry entry = iter.next(); - final Interval value = entry.getValue(); - ++value.count; - if (value.count == value.interval) { - value.count = 0; - final Player player = Bukkit.getPlayer(entry.getKey()); - if (player == null) { - iter.remove(); - continue; - } - final double level = player.getHealth(); - if (level != value.max) { - player.setHealth(Math.min(level + value.amount, value.max)); - } - } - } - } - if (!feedRunnable.isEmpty()) { - for (final Iterator> iter = feedRunnable.entrySet().iterator(); iter.hasNext();) { - final Entry entry = iter.next(); - final Interval value = entry.getValue(); - ++value.count; - if (value.count == value.interval) { - value.count = 0; - final Player player = Bukkit.getPlayer(entry.getKey()); - if (player == null) { - iter.remove(); - continue; - } - final int level = player.getFoodLevel(); - if (level != value.max) { - player.setFoodLevel(Math.min(level + value.amount, value.max)); - } - } - } - } - } - }, 0l, 20l); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onInteract(final BlockDamageEvent event) { - final Player player = event.getPlayer(); - if (player.getGameMode() != GameMode.SURVIVAL) { - return; - } - final Plot plot = BukkitUtil.getLocation(player).getOwnedPlot(); - if (plot == null) { - return; - } - if (FlagManager.isBooleanFlag(plot, "instabreak", false)) { - event.getBlock().breakNaturally(); - } - } - - @EventHandler(priority = EventPriority.HIGH) - public void onDamage(final EntityDamageEvent event) { - if (event.getEntityType() != EntityType.PLAYER) { - return; - } - final Player player = (Player) event.getEntity(); - final Plot plot = BukkitUtil.getLocation(player).getOwnedPlot(); - if (plot == null) { - return; - } - if (FlagManager.isBooleanFlag(plot, "invincible", false)) { - event.setCancelled(true); - } - } - - @EventHandler - public void onItemPickup(final PlayerPickupItemEvent event) { - final Player player = event.getPlayer(); - final PlotPlayer pp = BukkitUtil.getPlayer(player); - final Plot plot = BukkitUtil.getLocation(player).getOwnedPlot(); - if (plot == null) { - return; - } - final UUID uuid = pp.getUUID(); - if (plot.isAdded(uuid) && FlagManager.isBooleanFlag(plot, "drop-protection", false)) { - event.setCancelled(true); - } - } - - @EventHandler - public void onItemDrop(final PlayerDropItemEvent event) { - final Player player = event.getPlayer(); - final PlotPlayer pp = BukkitUtil.getPlayer(player); - final Plot plot = BukkitUtil.getLocation(player).getOwnedPlot(); - if (plot == null) { - return; - } - final UUID uuid = pp.getUUID(); - if (plot.isAdded(uuid) && FlagManager.isBooleanFlag(plot, "item-drop", false)) { - event.setCancelled(true); - } - } - - @EventHandler - public void onPlotEnter(final PlayerEnterPlotEvent event) { - final Player player = event.getPlayer(); - final Plot plot = event.getPlot(); - final Flag feed = FlagManager.getPlotFlagRaw(plot, "feed"); - if (feed != null) { - final Integer[] value = (Integer[]) feed.getValue(); - feedRunnable.put(player.getName(), new Interval(value[0], value[1], 20)); - } - final Flag heal = FlagManager.getPlotFlagRaw(plot, "heal"); - if (heal != null) { - final Integer[] value = (Integer[]) heal.getValue(); - healRunnable.put(player.getName(), new Interval(value[0], value[1], 20)); - } - } - - @EventHandler - public void onPlayerQuit(final PlayerQuitEvent event) { - final Player player = event.getPlayer(); - final String name = player.getName(); - feedRunnable.remove(name); - healRunnable.remove(name); - } - - @EventHandler - public void onPlotLeave(final PlayerLeavePlotEvent event) { - final Player leaver = event.getPlayer(); - final Plot plot = event.getPlot(); - if (!plot.hasOwner()) { - return; - } - BukkitUtil.getPlayer(leaver); - final String name = leaver.getName(); - feedRunnable.remove(name); - healRunnable.remove(name); - } - - public static class Interval { - public final int interval; - public final int amount; - public final int max; - public int count = 0; - - public Interval(final int interval, final int amount, final int max) { - this.interval = interval; - this.amount = amount; - this.max = max; - } - } - - /** - * Record Meta Class - * - - */ - public static class RecordMeta { - public final static List metaList = new ArrayList<>(); - static { - for (int x = 3; x < 12; x++) { - metaList.add(new RecordMeta(x + "", Material.valueOf("RECORD_" + x))); - } - } - private final String name; - private final Material material; - - public RecordMeta(final String name, final Material material) { - this.name = name; - this.material = material; - } - - @Override - public String toString() { - return name; - } - - @Override - public int hashCode() { - return name.hashCode(); - } - - public Material getMaterial() { - return material; - } - } -} +//////////////////////////////////////////////////////////////////////////////////////////////////// +// PlotSquared - A plot manager and world generator for the Bukkit API / +// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / +// / +// This program is free software; you can redistribute it and/or modify / +// it under the terms of the GNU General Public License as published by / +// the Free Software Foundation; either version 3 of the License, or / +// (at your option) any later version. / +// / +// This program is distributed in the hope that it will be useful, / +// but WITHOUT ANY WARRANTY; without even the implied warranty of / +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / +// GNU General Public License for more details. / +// / +// You should have received a copy of the GNU General Public License / +// along with this program; if not, write to the Free Software Foundation, / +// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / +// / +// You can contact us via: support@intellectualsites.com / +//////////////////////////////////////////////////////////////////////////////////////////////////// +package com.plotsquared.bukkit.listeners; + +import com.intellectualcrafters.plot.flag.Flag; +import com.intellectualcrafters.plot.flag.FlagManager; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotPlayer; +import com.plotsquared.bukkit.events.PlayerEnterPlotEvent; +import com.plotsquared.bukkit.events.PlayerLeavePlotEvent; +import com.plotsquared.bukkit.util.BukkitUtil; +import com.plotsquared.listener.PlotListener; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockDamageEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.player.PlayerDropItemEvent; +import org.bukkit.event.player.PlayerPickupItemEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map.Entry; +import java.util.UUID; + +/** + * Created 2014-10-30 for PlotSquared + * + + */ +@SuppressWarnings({ "deprecation" }) +public class PlotPlusListener extends PlotListener implements Listener { + private final static HashMap feedRunnable = new HashMap<>(); + private final static HashMap healRunnable = new HashMap<>(); + + public static void startRunnable(final JavaPlugin plugin) { + plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { + @Override + public void run() { + if (!healRunnable.isEmpty()) { + for (final Iterator> iter = healRunnable.entrySet().iterator(); iter.hasNext();) { + final Entry entry = iter.next(); + final Interval value = entry.getValue(); + ++value.count; + if (value.count == value.interval) { + value.count = 0; + final Player player = Bukkit.getPlayer(entry.getKey()); + if (player == null) { + iter.remove(); + continue; + } + final double level = player.getHealth(); + if (level != value.max) { + player.setHealth(Math.min(level + value.amount, value.max)); + } + } + } + } + if (!feedRunnable.isEmpty()) { + for (final Iterator> iter = feedRunnable.entrySet().iterator(); iter.hasNext();) { + final Entry entry = iter.next(); + final Interval value = entry.getValue(); + ++value.count; + if (value.count == value.interval) { + value.count = 0; + final Player player = Bukkit.getPlayer(entry.getKey()); + if (player == null) { + iter.remove(); + continue; + } + final int level = player.getFoodLevel(); + if (level != value.max) { + player.setFoodLevel(Math.min(level + value.amount, value.max)); + } + } + } + } + } + }, 0l, 20l); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onInteract(final BlockDamageEvent event) { + final Player player = event.getPlayer(); + if (player.getGameMode() != GameMode.SURVIVAL) { + return; + } + final Plot plot = BukkitUtil.getLocation(player).getOwnedPlot(); + if (plot == null) { + return; + } + if (FlagManager.isBooleanFlag(plot, "instabreak", false)) { + event.getBlock().breakNaturally(); + } + } + + @EventHandler(priority = EventPriority.HIGH) + public void onDamage(final EntityDamageEvent event) { + if (event.getEntityType() != EntityType.PLAYER) { + return; + } + final Player player = (Player) event.getEntity(); + final Plot plot = BukkitUtil.getLocation(player).getOwnedPlot(); + if (plot == null) { + return; + } + if (FlagManager.isBooleanFlag(plot, "invincible", false)) { + event.setCancelled(true); + } + } + + @EventHandler + public void onItemPickup(final PlayerPickupItemEvent event) { + final Player player = event.getPlayer(); + final PlotPlayer pp = BukkitUtil.getPlayer(player); + final Plot plot = BukkitUtil.getLocation(player).getOwnedPlot(); + if (plot == null) { + return; + } + final UUID uuid = pp.getUUID(); + if (plot.isAdded(uuid) && FlagManager.isBooleanFlag(plot, "drop-protection", false)) { + event.setCancelled(true); + } + } + + @EventHandler + public void onItemDrop(final PlayerDropItemEvent event) { + final Player player = event.getPlayer(); + final PlotPlayer pp = BukkitUtil.getPlayer(player); + final Plot plot = BukkitUtil.getLocation(player).getOwnedPlot(); + if (plot == null) { + return; + } + final UUID uuid = pp.getUUID(); + if (plot.isAdded(uuid) && FlagManager.isBooleanFlag(plot, "item-drop", false)) { + event.setCancelled(true); + } + } + + @EventHandler + public void onPlotEnter(final PlayerEnterPlotEvent event) { + final Player player = event.getPlayer(); + final Plot plot = event.getPlot(); + final Flag feed = FlagManager.getPlotFlagRaw(plot, "feed"); + if (feed != null) { + final Integer[] value = (Integer[]) feed.getValue(); + feedRunnable.put(player.getName(), new Interval(value[0], value[1], 20)); + } + final Flag heal = FlagManager.getPlotFlagRaw(plot, "heal"); + if (heal != null) { + final Integer[] value = (Integer[]) heal.getValue(); + healRunnable.put(player.getName(), new Interval(value[0], value[1], 20)); + } + } + + @EventHandler + public void onPlayerQuit(final PlayerQuitEvent event) { + final Player player = event.getPlayer(); + final String name = player.getName(); + feedRunnable.remove(name); + healRunnable.remove(name); + } + + @EventHandler + public void onPlotLeave(final PlayerLeavePlotEvent event) { + final Player leaver = event.getPlayer(); + final Plot plot = event.getPlot(); + if (!plot.hasOwner()) { + return; + } + BukkitUtil.getPlayer(leaver); + final String name = leaver.getName(); + feedRunnable.remove(name); + healRunnable.remove(name); + } + + public static class Interval { + public final int interval; + public final int amount; + public final int max; + public int count = 0; + + public Interval(final int interval, final int amount, final int max) { + this.interval = interval; + this.amount = amount; + this.max = max; + } + } + + /** + * Record Meta Class + * + + */ + public static class RecordMeta { + public final static List metaList = new ArrayList<>(); + static { + for (int x = 3; x < 12; x++) { + metaList.add(new RecordMeta(x + "", Material.valueOf("RECORD_" + x))); + } + } + private final String name; + private final Material material; + + public RecordMeta(final String name, final Material material) { + this.name = name; + this.material = material; + } + + @Override + public String toString() { + return name; + } + + @Override + public int hashCode() { + return name.hashCode(); + } + + public Material getMaterial() { + return material; + } + } +} diff --git a/src/main/java/com/plotsquared/bukkit/listeners/WorldEvents.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/WorldEvents.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/listeners/WorldEvents.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/listeners/WorldEvents.java diff --git a/src/main/java/com/plotsquared/bukkit/listeners/worldedit/WEListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/worldedit/WEListener.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/listeners/worldedit/WEListener.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/listeners/worldedit/WEListener.java diff --git a/src/main/java/com/plotsquared/bukkit/object/BukkitLazyBlock.java b/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitLazyBlock.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/object/BukkitLazyBlock.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitLazyBlock.java diff --git a/src/main/java/com/plotsquared/bukkit/object/BukkitOfflinePlayer.java b/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitOfflinePlayer.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/object/BukkitOfflinePlayer.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitOfflinePlayer.java diff --git a/src/main/java/com/plotsquared/bukkit/object/BukkitPlayer.java b/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitPlayer.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/object/BukkitPlayer.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitPlayer.java diff --git a/src/main/java/com/plotsquared/bukkit/object/entity/AgeableStats.java b/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/AgeableStats.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/object/entity/AgeableStats.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/AgeableStats.java diff --git a/src/main/java/com/plotsquared/bukkit/object/entity/ArmorStandStats.java b/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/ArmorStandStats.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/object/entity/ArmorStandStats.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/ArmorStandStats.java diff --git a/src/main/java/com/plotsquared/bukkit/object/entity/EntityBaseStats.java b/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/EntityBaseStats.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/object/entity/EntityBaseStats.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/EntityBaseStats.java diff --git a/src/main/java/com/plotsquared/bukkit/object/entity/EntityWrapper.java b/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/EntityWrapper.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/object/entity/EntityWrapper.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/EntityWrapper.java diff --git a/src/main/java/com/plotsquared/bukkit/object/entity/HorseStats.java b/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/HorseStats.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/object/entity/HorseStats.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/HorseStats.java diff --git a/src/main/java/com/plotsquared/bukkit/object/entity/LivingEntityStats.java b/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/LivingEntityStats.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/object/entity/LivingEntityStats.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/LivingEntityStats.java diff --git a/src/main/java/com/plotsquared/bukkit/object/entity/TameableStats.java b/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/TameableStats.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/object/entity/TameableStats.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/TameableStats.java diff --git a/src/main/java/com/plotsquared/bukkit/object/schematic/StateWrapper.java b/Bukkit/src/main/java/com/plotsquared/bukkit/object/schematic/StateWrapper.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/object/schematic/StateWrapper.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/object/schematic/StateWrapper.java diff --git a/src/main/java/com/plotsquared/bukkit/titles/DefaultTitle.java b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitle.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/titles/DefaultTitle.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitle.java diff --git a/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager.java diff --git a/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager_183.java b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager_183.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager_183.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager_183.java diff --git a/src/main/java/com/plotsquared/bukkit/titles/DefaultTitle_183.java b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitle_183.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/titles/DefaultTitle_183.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitle_183.java diff --git a/src/main/java/com/plotsquared/bukkit/titles/HackTitle.java b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/HackTitle.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/titles/HackTitle.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/titles/HackTitle.java diff --git a/src/main/java/com/plotsquared/bukkit/titles/HackTitleManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/HackTitleManager.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/titles/HackTitleManager.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/titles/HackTitleManager.java diff --git a/src/main/java/com/plotsquared/bukkit/util/BukkitChatManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChatManager.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/util/BukkitChatManager.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChatManager.java diff --git a/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java diff --git a/src/main/java/com/plotsquared/bukkit/util/BukkitCommand.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitCommand.java similarity index 97% rename from src/main/java/com/plotsquared/bukkit/util/BukkitCommand.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitCommand.java index d056ca211..f24dbd247 100644 --- a/src/main/java/com/plotsquared/bukkit/util/BukkitCommand.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitCommand.java @@ -1,108 +1,108 @@ -package com.plotsquared.bukkit.util; - -import com.intellectualcrafters.plot.commands.MainCommand; -import com.intellectualcrafters.plot.object.ConsolePlayer; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.StringComparison; -import com.plotsquared.bukkit.commands.DebugUUID; -import com.plotsquared.general.commands.Command; -import org.bukkit.Bukkit; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.command.TabCompleter; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * Created 2015-02-20 for PlotSquared - * - - */ -public class BukkitCommand implements CommandExecutor, TabCompleter { - - public BukkitCommand() { - MainCommand.getInstance().addCommand(new DebugUUID()); - } - - @Override - public boolean onCommand(final CommandSender commandSender, final org.bukkit.command.Command command, final String commandLabel, - final String[] args) { - if (commandSender instanceof Player) { - return MainCommand.onCommand(BukkitUtil.getPlayer((Player) commandSender), commandLabel, args); - } - if (commandSender == null || commandSender.getClass() == Bukkit.getConsoleSender().getClass()) { - return MainCommand.onCommand(ConsolePlayer.getConsole(), commandLabel, args); - } - @SuppressWarnings("deprecation") - ConsolePlayer sender = new ConsolePlayer() { - @Override - public void sendMessage(String message) { - commandSender.sendMessage(commandLabel); - } - - @Override - public boolean hasPermission(String perm) { - return commandSender.hasPermission(commandLabel); - } - - @Override - public String getName() { - if (commandSender.getName().equals("CONSOLE")) { - return "*"; - } - return commandSender.getName(); - } - }; - sender.teleport(ConsolePlayer.getConsole().getLocationFull()); - boolean result = MainCommand.onCommand(sender, commandLabel, args); - ConsolePlayer.getConsole().teleport(sender.getLocationFull()); - return result; - } - - @Override - public List onTabComplete(final CommandSender commandSender, final org.bukkit.command.Command command, final String s, - final String[] strings) { - if (!(commandSender instanceof Player)) { - return null; - } - final PlotPlayer player = BukkitUtil.getPlayer((Player) commandSender); - if (strings.length < 1) { - if ((strings.length == 0) || "plots".startsWith(s)) { - return Collections.singletonList("plots"); - } - } - if (strings.length > 1) { - return null; - } - final Set tabOptions = new HashSet<>(); - final String arg = strings[0].toLowerCase(); - ArrayList labels = new ArrayList<>(); - for (final Command cmd : MainCommand.getInstance().getCommands()) { - final String label = cmd.getCommand(); - HashSet aliases = new HashSet<>(cmd.getAliases()); - aliases.add(label); - for (String alias : aliases) { - labels.add(alias); - if (alias.startsWith(arg)) { - if (Permissions.hasPermission(player, cmd.getPermission())) { - tabOptions.add(label); - } else { - break; - } - } - } - } - String best = new StringComparison<>(arg, labels).getBestMatch(); - tabOptions.add(best); - if (!tabOptions.isEmpty()) { - return new ArrayList<>(tabOptions); - } - return null; - } -} +package com.plotsquared.bukkit.util; + +import com.intellectualcrafters.plot.commands.MainCommand; +import com.intellectualcrafters.plot.object.ConsolePlayer; +import com.intellectualcrafters.plot.object.PlotPlayer; +import com.intellectualcrafters.plot.util.Permissions; +import com.intellectualcrafters.plot.util.StringComparison; +import com.plotsquared.bukkit.commands.DebugUUID; +import com.plotsquared.general.commands.Command; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.command.TabCompleter; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * Created 2015-02-20 for PlotSquared + * + + */ +public class BukkitCommand implements CommandExecutor, TabCompleter { + + public BukkitCommand() { + MainCommand.getInstance().addCommand(new DebugUUID()); + } + + @Override + public boolean onCommand(final CommandSender commandSender, final org.bukkit.command.Command command, final String commandLabel, + final String[] args) { + if (commandSender instanceof Player) { + return MainCommand.onCommand(BukkitUtil.getPlayer((Player) commandSender), commandLabel, args); + } + if (commandSender == null || commandSender.getClass() == Bukkit.getConsoleSender().getClass()) { + return MainCommand.onCommand(ConsolePlayer.getConsole(), commandLabel, args); + } + @SuppressWarnings("deprecation") + ConsolePlayer sender = new ConsolePlayer() { + @Override + public void sendMessage(String message) { + commandSender.sendMessage(commandLabel); + } + + @Override + public boolean hasPermission(String perm) { + return commandSender.hasPermission(commandLabel); + } + + @Override + public String getName() { + if (commandSender.getName().equals("CONSOLE")) { + return "*"; + } + return commandSender.getName(); + } + }; + sender.teleport(ConsolePlayer.getConsole().getLocationFull()); + boolean result = MainCommand.onCommand(sender, commandLabel, args); + ConsolePlayer.getConsole().teleport(sender.getLocationFull()); + return result; + } + + @Override + public List onTabComplete(final CommandSender commandSender, final org.bukkit.command.Command command, final String s, + final String[] strings) { + if (!(commandSender instanceof Player)) { + return null; + } + final PlotPlayer player = BukkitUtil.getPlayer((Player) commandSender); + if (strings.length < 1) { + if ((strings.length == 0) || "plots".startsWith(s)) { + return Collections.singletonList("plots"); + } + } + if (strings.length > 1) { + return null; + } + final Set tabOptions = new HashSet<>(); + final String arg = strings[0].toLowerCase(); + ArrayList labels = new ArrayList<>(); + for (final Command cmd : MainCommand.getInstance().getCommands()) { + final String label = cmd.getCommand(); + HashSet aliases = new HashSet<>(cmd.getAliases()); + aliases.add(label); + for (String alias : aliases) { + labels.add(alias); + if (alias.startsWith(arg)) { + if (Permissions.hasPermission(player, cmd.getPermission())) { + tabOptions.add(label); + } else { + break; + } + } + } + } + String best = new StringComparison<>(arg, labels).getBestMatch(); + tabOptions.add(best); + if (!tabOptions.isEmpty()) { + return new ArrayList<>(tabOptions); + } + return null; + } +} diff --git a/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java diff --git a/src/main/java/com/plotsquared/bukkit/util/BukkitEventUtil.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEventUtil.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/util/BukkitEventUtil.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEventUtil.java diff --git a/src/main/java/com/plotsquared/bukkit/util/BukkitHybridUtils.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitHybridUtils.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/util/BukkitHybridUtils.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitHybridUtils.java diff --git a/src/main/java/com/plotsquared/bukkit/util/BukkitInventoryUtil.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitInventoryUtil.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/util/BukkitInventoryUtil.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitInventoryUtil.java diff --git a/src/main/java/com/plotsquared/bukkit/util/BukkitPlainChatManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitPlainChatManager.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/util/BukkitPlainChatManager.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitPlainChatManager.java diff --git a/src/main/java/com/plotsquared/bukkit/util/BukkitSchematicHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSchematicHandler.java similarity index 98% rename from src/main/java/com/plotsquared/bukkit/util/BukkitSchematicHandler.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSchematicHandler.java index a0d333cbe..eaa63d6a7 100644 --- a/src/main/java/com/plotsquared/bukkit/util/BukkitSchematicHandler.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSchematicHandler.java @@ -1,340 +1,340 @@ -//////////////////////////////////////////////////////////////////////////////////////////////////// -// PlotSquared - A plot manager and world generator for the Bukkit API / -// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / -// / -// This program is free software; you can redistribute it and/or modify / -// it under the terms of the GNU General Public License as published by / -// the Free Software Foundation; either version 3 of the License, or / -// (at your option) any later version. / -// / -// This program is distributed in the hope that it will be useful, / -// but WITHOUT ANY WARRANTY; without even the implied warranty of / -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / -// GNU General Public License for more details. / -// / -// You should have received a copy of the GNU General Public License / -// along with this program; if not, write to the Free Software Foundation, / -// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / -// / -// You can contact us via: support@intellectualsites.com / -//////////////////////////////////////////////////////////////////////////////////////////////////// -package com.plotsquared.bukkit.util; - -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import org.bukkit.Bukkit; -import org.bukkit.Chunk; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.block.BlockState; - -import com.intellectualcrafters.jnbt.ByteArrayTag; -import com.intellectualcrafters.jnbt.CompoundTag; -import com.intellectualcrafters.jnbt.IntTag; -import com.intellectualcrafters.jnbt.ListTag; -import com.intellectualcrafters.jnbt.ShortTag; -import com.intellectualcrafters.jnbt.StringTag; -import com.intellectualcrafters.jnbt.Tag; -import com.intellectualcrafters.plot.object.ChunkLoc; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.RegionWrapper; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.SchematicHandler; -import com.intellectualcrafters.plot.util.TaskManager; -import com.plotsquared.bukkit.object.schematic.StateWrapper; - -/** - * Schematic Handler - * - - - */ -public class BukkitSchematicHandler extends SchematicHandler { - - @Override - public void getCompoundTag(final String world, final Set regions, final RunnableVal whenDone) { - // async - TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { - // Main positions - Location[] corners = MainUtil.getCorners(world, regions); - final Location bot = corners[0]; - final Location top = corners[1]; - - final int width = (top.getX() - bot.getX()) + 1; - final int height = (top.getY() - bot.getY()) + 1; - final int length = (top.getZ() - bot.getZ()) + 1; - // Main Schematic tag - final HashMap schematic = new HashMap<>(); - schematic.put("Width", new ShortTag("Width", (short) width)); - schematic.put("Length", new ShortTag("Length", (short) length)); - schematic.put("Height", new ShortTag("Height", (short) height)); - schematic.put("Materials", new StringTag("Materials", "Alpha")); - schematic.put("WEOriginX", new IntTag("WEOriginX", 0)); - schematic.put("WEOriginY", new IntTag("WEOriginY", 0)); - schematic.put("WEOriginZ", new IntTag("WEOriginZ", 0)); - schematic.put("WEOffsetX", new IntTag("WEOffsetX", 0)); - schematic.put("WEOffsetY", new IntTag("WEOffsetY", 0)); - schematic.put("WEOffsetZ", new IntTag("WEOffsetZ", 0)); - // Arrays of data types - final List tileEntities = new ArrayList<>(); - final byte[] blocks = new byte[width * height * length]; - final byte[] blockData = new byte[width * height * length]; - // Queue - final ArrayDeque queue = new ArrayDeque<>(regions); - TaskManager.runTask(new Runnable() { - @Override - public void run() { - if (queue.isEmpty()) { - TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { - schematic.put("Blocks", new ByteArrayTag("Blocks", blocks)); - schematic.put("Data", new ByteArrayTag("Data", blockData)); - schematic.put("Entities", new ListTag("Entities", CompoundTag.class, new ArrayList())); - schematic.put("TileEntities", new ListTag("TileEntities", CompoundTag.class, tileEntities)); - whenDone.value = new CompoundTag("Schematic", schematic); - TaskManager.runTask(whenDone); - System.gc(); - System.gc(); - } - }); - return; - } - final Runnable regionTask = this; - RegionWrapper region = queue.poll(); - Location pos1 = new Location(world, region.minX, region.minY, region.minZ); - Location pos2 = new Location(world, region.maxX, region.maxY, region.maxZ); - final int bx = bot.getX(); - final int bz = bot.getZ(); - final int p1x = pos1.getX(); - final int p1z = pos1.getZ(); - final int p2x = pos2.getX(); - final int p2z = pos2.getZ(); - final int bcx = p1x >> 4; - final int bcz = p1z >> 4; - final int tcx = p2x >> 4; - final int tcz = p2z >> 4; - final int sy = pos1.getY(); - final int ey = pos2.getY(); - // Generate list of chunks - final ArrayList chunks = new ArrayList<>(); - for (int x = bcx; x <= tcx; x++) { - for (int z = bcz; z <= tcz; z++) { - chunks.add(new ChunkLoc(x, z)); - } - } - final World worldObj = Bukkit.getWorld(world); - // Main thread - TaskManager.runTask(new Runnable() { - @Override - public void run() { - final long start = System.currentTimeMillis(); - while ((!chunks.isEmpty()) && ((System.currentTimeMillis() - start) < 20)) { - // save schematics - final ChunkLoc chunk = chunks.remove(0); - final Chunk bc = worldObj.getChunkAt(chunk.x, chunk.z); - if (!bc.load(false)) { - continue; - } - final int X = chunk.x; - final int Z = chunk.z; - int xxb = X << 4; - int zzb = Z << 4; - int xxt = xxb + 15; - int zzt = zzb + 15; - - if (X == bcx) { - xxb = p1x; - } - if (X == tcx) { - xxt = p2x; - } - if (Z == bcz) { - zzb = p1z; - } - if (Z == tcz) { - zzt = p2z; - } - for (int y = sy; y <= Math.min(255, ey); y++) { - final int ry = y - sy; - final int i1 = (ry * width * length); - for (int z = zzb; z <= zzt; z++) { - final int rz = z - bz; - final int i2 = i1 + (rz * width); - for (int x = xxb; x <= xxt; x++) { - final int rx = x - bx; - final int index = i2 + rx; - final Block block = worldObj.getBlockAt(x, y, z); - final int id = block.getTypeId(); - switch (id) { - case 0: - case 2: - case 4: - case 13: - case 14: - case 15: - case 20: - case 21: - case 22: - case 24: - case 30: - case 32: - case 37: - case 39: - case 40: - case 41: - case 42: - case 45: - case 46: - case 47: - case 48: - case 49: - case 51: - case 55: - case 56: - case 57: - case 58: - case 60: - case 7: - case 8: - case 9: - case 10: - case 11: - case 73: - case 74: - case 78: - case 79: - case 80: - case 81: - case 82: - case 83: - case 85: - case 87: - case 88: - case 101: - case 102: - case 103: - case 110: - case 112: - case 113: - case 121: - case 122: - case 129: - case 133: - case 165: - case 166: - case 169: - case 170: - case 172: - case 173: - case 174: - case 181: - case 182: - case 188: - case 189: - case 190: - case 191: - case 192: { - break; - } - case 54: - case 130: - case 142: - case 27: - case 137: - case 52: - case 154: - case 84: - case 25: - case 144: - case 138: - case 176: - case 177: - case 63: - case 68: - case 323: - case 117: - case 116: - case 28: - case 66: - case 157: - case 61: - case 62: - case 140: - case 146: - case 149: - case 150: - case 158: - case 23: - case 123: - case 124: - case 29: - case 33: - case 151: - case 178: { - // TODO implement fully - final BlockState state = block.getState(); - if (state != null) { - final StateWrapper wrapper = new StateWrapper(state); - final CompoundTag rawTag = wrapper.getTag(); - if (rawTag != null) { - final Map values = new HashMap(); - for (final Entry entry : rawTag.getValue().entrySet()) { - values.put(entry.getKey(), entry.getValue()); - } - values.put("id", new StringTag("id", wrapper.getId())); - values.put("x", new IntTag("x", x)); - values.put("y", new IntTag("y", y)); - values.put("z", new IntTag("z", z)); - final CompoundTag tileEntityTag = new CompoundTag(values); - tileEntities.add(tileEntityTag); - } - } - } - default: { - blockData[index] = block.getData(); - } - } - // For optimization reasons, we are not supporting custom data types - // Especially since the most likely reason beyond this range is modded servers in which the blocks - // have NBT - // if (type > 255) { - // if (addBlocks == null) { - // addBlocks = new byte[(blocks.length >> 1) + 1]; - // } - // addBlocks[index >> 1] = (byte) (((index & 1) == 0) ? - // (addBlocks[index >> 1] & 0xF0) | ((type >> 8) & 0xF) : (addBlocks[index >> 1] & 0xF) | (((type - // >> 8) & 0xF) << 4)); - // } - blocks[index] = (byte) id; - } - } - } - } - if (!chunks.isEmpty()) { - TaskManager.runTaskLater(this, 1); - } else { - regionTask.run(); - } - } - }); - } - }); - } - }); - } - - @Override - public void restoreTag(CompoundTag ct, short x, short y, short z, Schematic schem) { - new StateWrapper(ct).restoreTag(x, y, z, schem); - } -} +//////////////////////////////////////////////////////////////////////////////////////////////////// +// PlotSquared - A plot manager and world generator for the Bukkit API / +// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / +// / +// This program is free software; you can redistribute it and/or modify / +// it under the terms of the GNU General Public License as published by / +// the Free Software Foundation; either version 3 of the License, or / +// (at your option) any later version. / +// / +// This program is distributed in the hope that it will be useful, / +// but WITHOUT ANY WARRANTY; without even the implied warranty of / +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / +// GNU General Public License for more details. / +// / +// You should have received a copy of the GNU General Public License / +// along with this program; if not, write to the Free Software Foundation, / +// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / +// / +// You can contact us via: support@intellectualsites.com / +//////////////////////////////////////////////////////////////////////////////////////////////////// +package com.plotsquared.bukkit.util; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import org.bukkit.Bukkit; +import org.bukkit.Chunk; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.BlockState; + +import com.intellectualcrafters.jnbt.ByteArrayTag; +import com.intellectualcrafters.jnbt.CompoundTag; +import com.intellectualcrafters.jnbt.IntTag; +import com.intellectualcrafters.jnbt.ListTag; +import com.intellectualcrafters.jnbt.ShortTag; +import com.intellectualcrafters.jnbt.StringTag; +import com.intellectualcrafters.jnbt.Tag; +import com.intellectualcrafters.plot.object.ChunkLoc; +import com.intellectualcrafters.plot.object.Location; +import com.intellectualcrafters.plot.object.RegionWrapper; +import com.intellectualcrafters.plot.object.RunnableVal; +import com.intellectualcrafters.plot.util.MainUtil; +import com.intellectualcrafters.plot.util.SchematicHandler; +import com.intellectualcrafters.plot.util.TaskManager; +import com.plotsquared.bukkit.object.schematic.StateWrapper; + +/** + * Schematic Handler + * + + + */ +public class BukkitSchematicHandler extends SchematicHandler { + + @Override + public void getCompoundTag(final String world, final Set regions, final RunnableVal whenDone) { + // async + TaskManager.runTaskAsync(new Runnable() { + @Override + public void run() { + // Main positions + Location[] corners = MainUtil.getCorners(world, regions); + final Location bot = corners[0]; + final Location top = corners[1]; + + final int width = (top.getX() - bot.getX()) + 1; + final int height = (top.getY() - bot.getY()) + 1; + final int length = (top.getZ() - bot.getZ()) + 1; + // Main Schematic tag + final HashMap schematic = new HashMap<>(); + schematic.put("Width", new ShortTag("Width", (short) width)); + schematic.put("Length", new ShortTag("Length", (short) length)); + schematic.put("Height", new ShortTag("Height", (short) height)); + schematic.put("Materials", new StringTag("Materials", "Alpha")); + schematic.put("WEOriginX", new IntTag("WEOriginX", 0)); + schematic.put("WEOriginY", new IntTag("WEOriginY", 0)); + schematic.put("WEOriginZ", new IntTag("WEOriginZ", 0)); + schematic.put("WEOffsetX", new IntTag("WEOffsetX", 0)); + schematic.put("WEOffsetY", new IntTag("WEOffsetY", 0)); + schematic.put("WEOffsetZ", new IntTag("WEOffsetZ", 0)); + // Arrays of data types + final List tileEntities = new ArrayList<>(); + final byte[] blocks = new byte[width * height * length]; + final byte[] blockData = new byte[width * height * length]; + // Queue + final ArrayDeque queue = new ArrayDeque<>(regions); + TaskManager.runTask(new Runnable() { + @Override + public void run() { + if (queue.isEmpty()) { + TaskManager.runTaskAsync(new Runnable() { + @Override + public void run() { + schematic.put("Blocks", new ByteArrayTag("Blocks", blocks)); + schematic.put("Data", new ByteArrayTag("Data", blockData)); + schematic.put("Entities", new ListTag("Entities", CompoundTag.class, new ArrayList())); + schematic.put("TileEntities", new ListTag("TileEntities", CompoundTag.class, tileEntities)); + whenDone.value = new CompoundTag("Schematic", schematic); + TaskManager.runTask(whenDone); + System.gc(); + System.gc(); + } + }); + return; + } + final Runnable regionTask = this; + RegionWrapper region = queue.poll(); + Location pos1 = new Location(world, region.minX, region.minY, region.minZ); + Location pos2 = new Location(world, region.maxX, region.maxY, region.maxZ); + final int bx = bot.getX(); + final int bz = bot.getZ(); + final int p1x = pos1.getX(); + final int p1z = pos1.getZ(); + final int p2x = pos2.getX(); + final int p2z = pos2.getZ(); + final int bcx = p1x >> 4; + final int bcz = p1z >> 4; + final int tcx = p2x >> 4; + final int tcz = p2z >> 4; + final int sy = pos1.getY(); + final int ey = pos2.getY(); + // Generate list of chunks + final ArrayList chunks = new ArrayList<>(); + for (int x = bcx; x <= tcx; x++) { + for (int z = bcz; z <= tcz; z++) { + chunks.add(new ChunkLoc(x, z)); + } + } + final World worldObj = Bukkit.getWorld(world); + // Main thread + TaskManager.runTask(new Runnable() { + @Override + public void run() { + final long start = System.currentTimeMillis(); + while ((!chunks.isEmpty()) && ((System.currentTimeMillis() - start) < 20)) { + // save schematics + final ChunkLoc chunk = chunks.remove(0); + final Chunk bc = worldObj.getChunkAt(chunk.x, chunk.z); + if (!bc.load(false)) { + continue; + } + final int X = chunk.x; + final int Z = chunk.z; + int xxb = X << 4; + int zzb = Z << 4; + int xxt = xxb + 15; + int zzt = zzb + 15; + + if (X == bcx) { + xxb = p1x; + } + if (X == tcx) { + xxt = p2x; + } + if (Z == bcz) { + zzb = p1z; + } + if (Z == tcz) { + zzt = p2z; + } + for (int y = sy; y <= Math.min(255, ey); y++) { + final int ry = y - sy; + final int i1 = (ry * width * length); + for (int z = zzb; z <= zzt; z++) { + final int rz = z - bz; + final int i2 = i1 + (rz * width); + for (int x = xxb; x <= xxt; x++) { + final int rx = x - bx; + final int index = i2 + rx; + final Block block = worldObj.getBlockAt(x, y, z); + final int id = block.getTypeId(); + switch (id) { + case 0: + case 2: + case 4: + case 13: + case 14: + case 15: + case 20: + case 21: + case 22: + case 24: + case 30: + case 32: + case 37: + case 39: + case 40: + case 41: + case 42: + case 45: + case 46: + case 47: + case 48: + case 49: + case 51: + case 55: + case 56: + case 57: + case 58: + case 60: + case 7: + case 8: + case 9: + case 10: + case 11: + case 73: + case 74: + case 78: + case 79: + case 80: + case 81: + case 82: + case 83: + case 85: + case 87: + case 88: + case 101: + case 102: + case 103: + case 110: + case 112: + case 113: + case 121: + case 122: + case 129: + case 133: + case 165: + case 166: + case 169: + case 170: + case 172: + case 173: + case 174: + case 181: + case 182: + case 188: + case 189: + case 190: + case 191: + case 192: { + break; + } + case 54: + case 130: + case 142: + case 27: + case 137: + case 52: + case 154: + case 84: + case 25: + case 144: + case 138: + case 176: + case 177: + case 63: + case 68: + case 323: + case 117: + case 116: + case 28: + case 66: + case 157: + case 61: + case 62: + case 140: + case 146: + case 149: + case 150: + case 158: + case 23: + case 123: + case 124: + case 29: + case 33: + case 151: + case 178: { + // TODO implement fully + final BlockState state = block.getState(); + if (state != null) { + final StateWrapper wrapper = new StateWrapper(state); + final CompoundTag rawTag = wrapper.getTag(); + if (rawTag != null) { + final Map values = new HashMap(); + for (final Entry entry : rawTag.getValue().entrySet()) { + values.put(entry.getKey(), entry.getValue()); + } + values.put("id", new StringTag("id", wrapper.getId())); + values.put("x", new IntTag("x", x)); + values.put("y", new IntTag("y", y)); + values.put("z", new IntTag("z", z)); + final CompoundTag tileEntityTag = new CompoundTag(values); + tileEntities.add(tileEntityTag); + } + } + } + default: { + blockData[index] = block.getData(); + } + } + // For optimization reasons, we are not supporting custom data types + // Especially since the most likely reason beyond this range is modded servers in which the blocks + // have NBT + // if (type > 255) { + // if (addBlocks == null) { + // addBlocks = new byte[(blocks.length >> 1) + 1]; + // } + // addBlocks[index >> 1] = (byte) (((index & 1) == 0) ? + // (addBlocks[index >> 1] & 0xF0) | ((type >> 8) & 0xF) : (addBlocks[index >> 1] & 0xF) | (((type + // >> 8) & 0xF) << 4)); + // } + blocks[index] = (byte) id; + } + } + } + } + if (!chunks.isEmpty()) { + TaskManager.runTaskLater(this, 1); + } else { + regionTask.run(); + } + } + }); + } + }); + } + }); + } + + @Override + public void restoreTag(CompoundTag ct, short x, short y, short z, Schematic schem) { + new StateWrapper(ct).restoreTag(x, y, z, schem); + } +} diff --git a/src/main/java/com/plotsquared/bukkit/util/BukkitSetupUtils.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSetupUtils.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/util/BukkitSetupUtils.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSetupUtils.java diff --git a/src/main/java/com/plotsquared/bukkit/util/BukkitTaskManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitTaskManager.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/util/BukkitTaskManager.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitTaskManager.java diff --git a/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java diff --git a/src/main/java/com/plotsquared/bukkit/util/Metrics.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/Metrics.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/util/Metrics.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/util/Metrics.java diff --git a/src/main/java/com/plotsquared/bukkit/util/NbtFactory.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/NbtFactory.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/util/NbtFactory.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/util/NbtFactory.java diff --git a/src/main/java/com/plotsquared/bukkit/util/OfflinePlayerUtil.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/OfflinePlayerUtil.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/util/OfflinePlayerUtil.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/util/OfflinePlayerUtil.java diff --git a/src/main/java/com/plotsquared/bukkit/util/SendChunk.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/SendChunk.java similarity index 97% rename from src/main/java/com/plotsquared/bukkit/util/SendChunk.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/util/SendChunk.java index a244a3c6b..e499b1bba 100644 --- a/src/main/java/com/plotsquared/bukkit/util/SendChunk.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/SendChunk.java @@ -1,193 +1,193 @@ -package com.plotsquared.bukkit.util; - -import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; - -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.object.ChunkLoc; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass; -import com.intellectualcrafters.plot.util.ReflectionUtils.RefConstructor; -import com.intellectualcrafters.plot.util.ReflectionUtils.RefField; -import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod; -import com.intellectualcrafters.plot.util.TaskManager; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.plotsquared.bukkit.object.BukkitPlayer; -import org.bukkit.Bukkit; -import org.bukkit.Chunk; -import org.bukkit.World; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map.Entry; - -/** - * An utility that can be used to send chunks, rather than using bukkit code to do so (uses heavy NMS) - * - - */ -public class SendChunk { - - // // Ref Class - private final RefClass classEntityPlayer = getRefClass("{nms}.EntityPlayer"); - private final RefClass classMapChunk = getRefClass("{nms}.PacketPlayOutMapChunk"); - private final RefClass classPacket = getRefClass("{nms}.Packet"); - private final RefClass classConnection = getRefClass("{nms}.PlayerConnection"); - private final RefClass classChunk = getRefClass("{nms}.Chunk"); - private final RefClass classCraftPlayer = getRefClass("{cb}.entity.CraftPlayer"); - private final RefClass classCraftChunk = getRefClass("{cb}.CraftChunk"); - private final RefMethod methodGetHandlePlayer; - private final RefMethod methodGetHandleChunk; - private final RefConstructor MapChunk; - private final RefField connection; - private final RefMethod send; - private final RefMethod methodInitLighting; - - /** - * Constructor - */ - public SendChunk() { - methodGetHandlePlayer = classCraftPlayer.getMethod("getHandle"); - methodGetHandleChunk = classCraftChunk.getMethod("getHandle"); - methodInitLighting = classChunk.getMethod("initLighting"); - MapChunk = classMapChunk.getConstructor(classChunk.getRealClass(), boolean.class, int.class); - connection = classEntityPlayer.getField("playerConnection"); - send = classConnection.getMethod("sendPacket", classPacket.getRealClass()); - } - - public void sendChunk(final Collection input) { - final HashSet chunks = new HashSet(input); - final HashMap> map = new HashMap<>(); - final int view = Bukkit.getServer().getViewDistance(); - for (final Chunk chunk : chunks) { - final String world = chunk.getWorld().getName(); - ArrayList list = map.get(world); - if (list == null) { - list = new ArrayList<>(); - map.put(world, list); - } - list.add(chunk); - final Object c = methodGetHandleChunk.of(chunk).call(); - methodInitLighting.of(c).call(); - } - for (Entry entry : UUIDHandler.getPlayers().entrySet()) { - PlotPlayer pp = entry.getValue(); - final Plot plot = pp.getCurrentPlot(); - Location loc = null; - String world; - if (plot != null) { - world = plot.getArea().worldname; - } else { - loc = pp.getLocation(); - world = loc.getWorld(); - } - final ArrayList list = map.get(world); - if (list == null) { - continue; - } - if (loc == null) { - loc = pp.getLocation(); - } - final int cx = loc.getX() >> 4; - final int cz = loc.getZ() >> 4; - final Player player = ((BukkitPlayer) pp).player; - final Object entity = methodGetHandlePlayer.of(player).call(); - - for (final Chunk chunk : list) { - final int dx = Math.abs(cx - chunk.getX()); - final int dz = Math.abs(cz - chunk.getZ()); - if ((dx > view) || (dz > view)) { - continue; - } - final Object c = methodGetHandleChunk.of(chunk).call(); - chunks.remove(chunk); - final Object con = connection.of(entity).get(); - // if (dx != 0 || dz != 0) { - // Object packet = MapChunk.create(c, true, 0); - // send.of(con).call(packet); - // } - final Object packet = MapChunk.create(c, true, 65535); - send.of(con).call(packet); - } - } - for (final Chunk chunk : chunks) { - TaskManager.runTask(new Runnable() { - @Override - public void run() { - try { - chunk.unload(true, false); - } catch (final Throwable e) { - final String worldname = chunk.getWorld().getName(); - PS.debug("$4Could not save chunk: " + worldname + ";" + chunk.getX() + ";" + chunk.getZ()); - PS.debug("$3 - $4File may be open in another process (e.g. MCEdit)"); - PS.debug("$3 - $4" + worldname + "/level.dat or " + worldname - + "/level_old.dat may be corrupt (try repairing or removing these)"); - } - } - }); - } - // - // - // int diffx, diffz; - // << 4; - // for (final Chunk chunk : chunks) { - // if (!chunk.isLoaded()) { - // continue; - // } - // boolean unload = true; - // final Object c = methodGetHandle.of(chunk).call(); - // final Object w = world.of(c).get(); - // final Object p = players.of(w).get(); - // for (final Object ep : (List) p) { - // final int x = ((Double) locX.of(ep).get()).intValue(); - // final int z = ((Double) locZ.of(ep).get()).intValue(); - // diffx = Math.abs(x - (chunk.getX() << 4)); - // diffz = Math.abs(z - (chunk.getZ() << 4)); - // if ((diffx <= view) && (diffz <= view)) { - // unload = false; - // if (v1_7_10) { - // chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ()); - // chunk.load(true); - // } - // else { - // final Object pair = ChunkCoordIntPairCon.create(chunk.getX(), chunk.getZ()); - // final Object pq = chunkCoordIntPairQueue.of(ep).get(); - // ((List) pq).add(pair); - // } - // } - // } - // if (unload) { - // TaskManager.runTask(new Runnable() { - // @Override - // public void run() { - // try { - // chunk.unload(true, true); - // } - // catch (Exception e) { - // String worldname = chunk.getWorld().getName(); - // PS.debug("$4Could not save chunk: " + worldname + ";" + chunk.getX() + ";" + chunk.getZ()); - // PS.debug("$3 - $4File may be open in another process (e.g. MCEdit)"); - // PS.debug("$3 - $4" + worldname + "/level.dat or " + worldname + "level_old.dat may be corrupt (try repairing - // or removing these)"); - // } - // } - // }); - // } - // - // } - } - - public void sendChunk(final String worldname, final List locs) { - final World myworld = Bukkit.getWorld(worldname); - final ArrayList chunks = new ArrayList<>(); - for (final ChunkLoc loc : locs) { - chunks.add(myworld.getChunkAt(loc.x, loc.z)); - } - sendChunk(chunks); - } -} +package com.plotsquared.bukkit.util; + +import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; + +import com.intellectualcrafters.plot.PS; +import com.intellectualcrafters.plot.object.ChunkLoc; +import com.intellectualcrafters.plot.object.Location; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotPlayer; +import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass; +import com.intellectualcrafters.plot.util.ReflectionUtils.RefConstructor; +import com.intellectualcrafters.plot.util.ReflectionUtils.RefField; +import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod; +import com.intellectualcrafters.plot.util.TaskManager; +import com.intellectualcrafters.plot.util.UUIDHandler; +import com.plotsquared.bukkit.object.BukkitPlayer; +import org.bukkit.Bukkit; +import org.bukkit.Chunk; +import org.bukkit.World; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map.Entry; + +/** + * An utility that can be used to send chunks, rather than using bukkit code to do so (uses heavy NMS) + * + + */ +public class SendChunk { + + // // Ref Class + private final RefClass classEntityPlayer = getRefClass("{nms}.EntityPlayer"); + private final RefClass classMapChunk = getRefClass("{nms}.PacketPlayOutMapChunk"); + private final RefClass classPacket = getRefClass("{nms}.Packet"); + private final RefClass classConnection = getRefClass("{nms}.PlayerConnection"); + private final RefClass classChunk = getRefClass("{nms}.Chunk"); + private final RefClass classCraftPlayer = getRefClass("{cb}.entity.CraftPlayer"); + private final RefClass classCraftChunk = getRefClass("{cb}.CraftChunk"); + private final RefMethod methodGetHandlePlayer; + private final RefMethod methodGetHandleChunk; + private final RefConstructor MapChunk; + private final RefField connection; + private final RefMethod send; + private final RefMethod methodInitLighting; + + /** + * Constructor + */ + public SendChunk() { + methodGetHandlePlayer = classCraftPlayer.getMethod("getHandle"); + methodGetHandleChunk = classCraftChunk.getMethod("getHandle"); + methodInitLighting = classChunk.getMethod("initLighting"); + MapChunk = classMapChunk.getConstructor(classChunk.getRealClass(), boolean.class, int.class); + connection = classEntityPlayer.getField("playerConnection"); + send = classConnection.getMethod("sendPacket", classPacket.getRealClass()); + } + + public void sendChunk(final Collection input) { + final HashSet chunks = new HashSet(input); + final HashMap> map = new HashMap<>(); + final int view = Bukkit.getServer().getViewDistance(); + for (final Chunk chunk : chunks) { + final String world = chunk.getWorld().getName(); + ArrayList list = map.get(world); + if (list == null) { + list = new ArrayList<>(); + map.put(world, list); + } + list.add(chunk); + final Object c = methodGetHandleChunk.of(chunk).call(); + methodInitLighting.of(c).call(); + } + for (Entry entry : UUIDHandler.getPlayers().entrySet()) { + PlotPlayer pp = entry.getValue(); + final Plot plot = pp.getCurrentPlot(); + Location loc = null; + String world; + if (plot != null) { + world = plot.getArea().worldname; + } else { + loc = pp.getLocation(); + world = loc.getWorld(); + } + final ArrayList list = map.get(world); + if (list == null) { + continue; + } + if (loc == null) { + loc = pp.getLocation(); + } + final int cx = loc.getX() >> 4; + final int cz = loc.getZ() >> 4; + final Player player = ((BukkitPlayer) pp).player; + final Object entity = methodGetHandlePlayer.of(player).call(); + + for (final Chunk chunk : list) { + final int dx = Math.abs(cx - chunk.getX()); + final int dz = Math.abs(cz - chunk.getZ()); + if ((dx > view) || (dz > view)) { + continue; + } + final Object c = methodGetHandleChunk.of(chunk).call(); + chunks.remove(chunk); + final Object con = connection.of(entity).get(); + // if (dx != 0 || dz != 0) { + // Object packet = MapChunk.create(c, true, 0); + // send.of(con).call(packet); + // } + final Object packet = MapChunk.create(c, true, 65535); + send.of(con).call(packet); + } + } + for (final Chunk chunk : chunks) { + TaskManager.runTask(new Runnable() { + @Override + public void run() { + try { + chunk.unload(true, false); + } catch (final Throwable e) { + final String worldname = chunk.getWorld().getName(); + PS.debug("$4Could not save chunk: " + worldname + ";" + chunk.getX() + ";" + chunk.getZ()); + PS.debug("$3 - $4File may be open in another process (e.g. MCEdit)"); + PS.debug("$3 - $4" + worldname + "/level.dat or " + worldname + + "/level_old.dat may be corrupt (try repairing or removing these)"); + } + } + }); + } + // + // + // int diffx, diffz; + // << 4; + // for (final Chunk chunk : chunks) { + // if (!chunk.isLoaded()) { + // continue; + // } + // boolean unload = true; + // final Object c = methodGetHandle.of(chunk).call(); + // final Object w = world.of(c).get(); + // final Object p = players.of(w).get(); + // for (final Object ep : (List) p) { + // final int x = ((Double) locX.of(ep).get()).intValue(); + // final int z = ((Double) locZ.of(ep).get()).intValue(); + // diffx = Math.abs(x - (chunk.getX() << 4)); + // diffz = Math.abs(z - (chunk.getZ() << 4)); + // if ((diffx <= view) && (diffz <= view)) { + // unload = false; + // if (v1_7_10) { + // chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ()); + // chunk.load(true); + // } + // else { + // final Object pair = ChunkCoordIntPairCon.create(chunk.getX(), chunk.getZ()); + // final Object pq = chunkCoordIntPairQueue.of(ep).get(); + // ((List) pq).add(pair); + // } + // } + // } + // if (unload) { + // TaskManager.runTask(new Runnable() { + // @Override + // public void run() { + // try { + // chunk.unload(true, true); + // } + // catch (Exception e) { + // String worldname = chunk.getWorld().getName(); + // PS.debug("$4Could not save chunk: " + worldname + ";" + chunk.getX() + ";" + chunk.getZ()); + // PS.debug("$3 - $4File may be open in another process (e.g. MCEdit)"); + // PS.debug("$3 - $4" + worldname + "/level.dat or " + worldname + "level_old.dat may be corrupt (try repairing + // or removing these)"); + // } + // } + // }); + // } + // + // } + } + + public void sendChunk(final String worldname, final List locs) { + final World myworld = Bukkit.getWorld(worldname); + final ArrayList chunks = new ArrayList<>(); + for (final ChunkLoc loc : locs) { + chunks.add(myworld.getChunkAt(loc.x, loc.z)); + } + sendChunk(chunks); + } +} diff --git a/src/main/java/com/plotsquared/bukkit/util/SetGenCB.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/SetGenCB.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/util/SetGenCB.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/util/SetGenCB.java diff --git a/src/main/java/com/plotsquared/bukkit/util/block/FastChunk_1_8_3.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastChunk_1_8_3.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/util/block/FastChunk_1_8_3.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastChunk_1_8_3.java diff --git a/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_7.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_7.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_7.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_7.java diff --git a/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8.java diff --git a/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8_3.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8_3.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8_3.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8_3.java diff --git a/src/main/java/com/plotsquared/bukkit/util/block/GenChunk.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/GenChunk.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/util/block/GenChunk.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/util/block/GenChunk.java diff --git a/src/main/java/com/plotsquared/bukkit/util/block/SlowChunk.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/SlowChunk.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/util/block/SlowChunk.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/util/block/SlowChunk.java diff --git a/src/main/java/com/plotsquared/bukkit/util/block/SlowQueue.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/SlowQueue.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/util/block/SlowQueue.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/util/block/SlowQueue.java diff --git a/src/main/java/com/plotsquared/bukkit/uuid/DefaultUUIDWrapper.java b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/DefaultUUIDWrapper.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/uuid/DefaultUUIDWrapper.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/uuid/DefaultUUIDWrapper.java diff --git a/src/main/java/com/plotsquared/bukkit/uuid/FileUUIDHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/FileUUIDHandler.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/uuid/FileUUIDHandler.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/uuid/FileUUIDHandler.java diff --git a/src/main/java/com/plotsquared/bukkit/uuid/LowerOfflineUUIDWrapper.java b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/LowerOfflineUUIDWrapper.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/uuid/LowerOfflineUUIDWrapper.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/uuid/LowerOfflineUUIDWrapper.java diff --git a/src/main/java/com/plotsquared/bukkit/uuid/OfflineUUIDWrapper.java b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/OfflineUUIDWrapper.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/uuid/OfflineUUIDWrapper.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/uuid/OfflineUUIDWrapper.java diff --git a/src/main/java/com/plotsquared/bukkit/uuid/SQLUUIDHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/SQLUUIDHandler.java similarity index 100% rename from src/main/java/com/plotsquared/bukkit/uuid/SQLUUIDHandler.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/uuid/SQLUUIDHandler.java diff --git a/src/main/resources/plugin.yml b/Bukkit/src/main/resources/plugin.yml similarity index 98% rename from src/main/resources/plugin.yml rename to Bukkit/src/main/resources/plugin.yml index 4e6bc0902..b9ea44b4c 100644 --- a/src/main/resources/plugin.yml +++ b/Bukkit/src/main/resources/plugin.yml @@ -1,6 +1,6 @@ -name: ${project.name} +name: $name main: com.plotsquared.bukkit.BukkitMain -version: ${project.version} +version: $version load: STARTUP description: > Easy, yet powerful Plot World generation and management. diff --git a/Core/build.gradle b/Core/build.gradle new file mode 100644 index 000000000..f2770800b --- /dev/null +++ b/Core/build.gradle @@ -0,0 +1,2 @@ +apply plugin: 'eclipse' +apply plugin: 'idea' \ No newline at end of file diff --git a/src/main/java/com/intellectualcrafters/configuration/Configuration.java b/Core/src/main/java/com/intellectualcrafters/configuration/Configuration.java similarity index 100% rename from src/main/java/com/intellectualcrafters/configuration/Configuration.java rename to Core/src/main/java/com/intellectualcrafters/configuration/Configuration.java diff --git a/src/main/java/com/intellectualcrafters/configuration/ConfigurationOptions.java b/Core/src/main/java/com/intellectualcrafters/configuration/ConfigurationOptions.java similarity index 100% rename from src/main/java/com/intellectualcrafters/configuration/ConfigurationOptions.java rename to Core/src/main/java/com/intellectualcrafters/configuration/ConfigurationOptions.java diff --git a/src/main/java/com/intellectualcrafters/configuration/ConfigurationSection.java b/Core/src/main/java/com/intellectualcrafters/configuration/ConfigurationSection.java similarity index 100% rename from src/main/java/com/intellectualcrafters/configuration/ConfigurationSection.java rename to Core/src/main/java/com/intellectualcrafters/configuration/ConfigurationSection.java diff --git a/src/main/java/com/intellectualcrafters/configuration/InvalidConfigurationException.java b/Core/src/main/java/com/intellectualcrafters/configuration/InvalidConfigurationException.java similarity index 100% rename from src/main/java/com/intellectualcrafters/configuration/InvalidConfigurationException.java rename to Core/src/main/java/com/intellectualcrafters/configuration/InvalidConfigurationException.java diff --git a/src/main/java/com/intellectualcrafters/configuration/MemoryConfiguration.java b/Core/src/main/java/com/intellectualcrafters/configuration/MemoryConfiguration.java similarity index 100% rename from src/main/java/com/intellectualcrafters/configuration/MemoryConfiguration.java rename to Core/src/main/java/com/intellectualcrafters/configuration/MemoryConfiguration.java diff --git a/src/main/java/com/intellectualcrafters/configuration/MemoryConfigurationOptions.java b/Core/src/main/java/com/intellectualcrafters/configuration/MemoryConfigurationOptions.java similarity index 100% rename from src/main/java/com/intellectualcrafters/configuration/MemoryConfigurationOptions.java rename to Core/src/main/java/com/intellectualcrafters/configuration/MemoryConfigurationOptions.java diff --git a/src/main/java/com/intellectualcrafters/configuration/MemorySection.java b/Core/src/main/java/com/intellectualcrafters/configuration/MemorySection.java similarity index 100% rename from src/main/java/com/intellectualcrafters/configuration/MemorySection.java rename to Core/src/main/java/com/intellectualcrafters/configuration/MemorySection.java diff --git a/src/main/java/com/intellectualcrafters/configuration/file/FileConfiguration.java b/Core/src/main/java/com/intellectualcrafters/configuration/file/FileConfiguration.java similarity index 100% rename from src/main/java/com/intellectualcrafters/configuration/file/FileConfiguration.java rename to Core/src/main/java/com/intellectualcrafters/configuration/file/FileConfiguration.java diff --git a/src/main/java/com/intellectualcrafters/configuration/file/FileConfigurationOptions.java b/Core/src/main/java/com/intellectualcrafters/configuration/file/FileConfigurationOptions.java similarity index 100% rename from src/main/java/com/intellectualcrafters/configuration/file/FileConfigurationOptions.java rename to Core/src/main/java/com/intellectualcrafters/configuration/file/FileConfigurationOptions.java diff --git a/src/main/java/com/intellectualcrafters/configuration/file/YamlConfiguration.java b/Core/src/main/java/com/intellectualcrafters/configuration/file/YamlConfiguration.java similarity index 100% rename from src/main/java/com/intellectualcrafters/configuration/file/YamlConfiguration.java rename to Core/src/main/java/com/intellectualcrafters/configuration/file/YamlConfiguration.java diff --git a/src/main/java/com/intellectualcrafters/configuration/file/YamlConfigurationOptions.java b/Core/src/main/java/com/intellectualcrafters/configuration/file/YamlConfigurationOptions.java similarity index 100% rename from src/main/java/com/intellectualcrafters/configuration/file/YamlConfigurationOptions.java rename to Core/src/main/java/com/intellectualcrafters/configuration/file/YamlConfigurationOptions.java diff --git a/src/main/java/com/intellectualcrafters/configuration/file/YamlConstructor.java b/Core/src/main/java/com/intellectualcrafters/configuration/file/YamlConstructor.java similarity index 100% rename from src/main/java/com/intellectualcrafters/configuration/file/YamlConstructor.java rename to Core/src/main/java/com/intellectualcrafters/configuration/file/YamlConstructor.java diff --git a/src/main/java/com/intellectualcrafters/configuration/file/YamlRepresenter.java b/Core/src/main/java/com/intellectualcrafters/configuration/file/YamlRepresenter.java similarity index 100% rename from src/main/java/com/intellectualcrafters/configuration/file/YamlRepresenter.java rename to Core/src/main/java/com/intellectualcrafters/configuration/file/YamlRepresenter.java diff --git a/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerializable.java b/Core/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerializable.java similarity index 100% rename from src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerializable.java rename to Core/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerializable.java diff --git a/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerialization.java b/Core/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerialization.java similarity index 100% rename from src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerialization.java rename to Core/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerialization.java diff --git a/src/main/java/com/intellectualcrafters/configuration/serialization/DelegateDeserialization.java b/Core/src/main/java/com/intellectualcrafters/configuration/serialization/DelegateDeserialization.java similarity index 100% rename from src/main/java/com/intellectualcrafters/configuration/serialization/DelegateDeserialization.java rename to Core/src/main/java/com/intellectualcrafters/configuration/serialization/DelegateDeserialization.java diff --git a/src/main/java/com/intellectualcrafters/configuration/serialization/SerializableAs.java b/Core/src/main/java/com/intellectualcrafters/configuration/serialization/SerializableAs.java similarity index 100% rename from src/main/java/com/intellectualcrafters/configuration/serialization/SerializableAs.java rename to Core/src/main/java/com/intellectualcrafters/configuration/serialization/SerializableAs.java diff --git a/src/main/java/com/intellectualcrafters/jnbt/ByteArrayTag.java b/Core/src/main/java/com/intellectualcrafters/jnbt/ByteArrayTag.java similarity index 100% rename from src/main/java/com/intellectualcrafters/jnbt/ByteArrayTag.java rename to Core/src/main/java/com/intellectualcrafters/jnbt/ByteArrayTag.java diff --git a/src/main/java/com/intellectualcrafters/jnbt/ByteTag.java b/Core/src/main/java/com/intellectualcrafters/jnbt/ByteTag.java similarity index 100% rename from src/main/java/com/intellectualcrafters/jnbt/ByteTag.java rename to Core/src/main/java/com/intellectualcrafters/jnbt/ByteTag.java diff --git a/src/main/java/com/intellectualcrafters/jnbt/CompoundTag.java b/Core/src/main/java/com/intellectualcrafters/jnbt/CompoundTag.java similarity index 100% rename from src/main/java/com/intellectualcrafters/jnbt/CompoundTag.java rename to Core/src/main/java/com/intellectualcrafters/jnbt/CompoundTag.java diff --git a/src/main/java/com/intellectualcrafters/jnbt/CompoundTagBuilder.java b/Core/src/main/java/com/intellectualcrafters/jnbt/CompoundTagBuilder.java similarity index 100% rename from src/main/java/com/intellectualcrafters/jnbt/CompoundTagBuilder.java rename to Core/src/main/java/com/intellectualcrafters/jnbt/CompoundTagBuilder.java diff --git a/src/main/java/com/intellectualcrafters/jnbt/DoubleTag.java b/Core/src/main/java/com/intellectualcrafters/jnbt/DoubleTag.java similarity index 100% rename from src/main/java/com/intellectualcrafters/jnbt/DoubleTag.java rename to Core/src/main/java/com/intellectualcrafters/jnbt/DoubleTag.java diff --git a/src/main/java/com/intellectualcrafters/jnbt/EndTag.java b/Core/src/main/java/com/intellectualcrafters/jnbt/EndTag.java similarity index 100% rename from src/main/java/com/intellectualcrafters/jnbt/EndTag.java rename to Core/src/main/java/com/intellectualcrafters/jnbt/EndTag.java diff --git a/src/main/java/com/intellectualcrafters/jnbt/FloatTag.java b/Core/src/main/java/com/intellectualcrafters/jnbt/FloatTag.java similarity index 100% rename from src/main/java/com/intellectualcrafters/jnbt/FloatTag.java rename to Core/src/main/java/com/intellectualcrafters/jnbt/FloatTag.java diff --git a/src/main/java/com/intellectualcrafters/jnbt/IntArrayTag.java b/Core/src/main/java/com/intellectualcrafters/jnbt/IntArrayTag.java similarity index 100% rename from src/main/java/com/intellectualcrafters/jnbt/IntArrayTag.java rename to Core/src/main/java/com/intellectualcrafters/jnbt/IntArrayTag.java diff --git a/src/main/java/com/intellectualcrafters/jnbt/IntTag.java b/Core/src/main/java/com/intellectualcrafters/jnbt/IntTag.java similarity index 100% rename from src/main/java/com/intellectualcrafters/jnbt/IntTag.java rename to Core/src/main/java/com/intellectualcrafters/jnbt/IntTag.java diff --git a/src/main/java/com/intellectualcrafters/jnbt/ListTag.java b/Core/src/main/java/com/intellectualcrafters/jnbt/ListTag.java similarity index 100% rename from src/main/java/com/intellectualcrafters/jnbt/ListTag.java rename to Core/src/main/java/com/intellectualcrafters/jnbt/ListTag.java diff --git a/src/main/java/com/intellectualcrafters/jnbt/ListTagBuilder.java b/Core/src/main/java/com/intellectualcrafters/jnbt/ListTagBuilder.java similarity index 100% rename from src/main/java/com/intellectualcrafters/jnbt/ListTagBuilder.java rename to Core/src/main/java/com/intellectualcrafters/jnbt/ListTagBuilder.java diff --git a/src/main/java/com/intellectualcrafters/jnbt/LongTag.java b/Core/src/main/java/com/intellectualcrafters/jnbt/LongTag.java similarity index 100% rename from src/main/java/com/intellectualcrafters/jnbt/LongTag.java rename to Core/src/main/java/com/intellectualcrafters/jnbt/LongTag.java diff --git a/src/main/java/com/intellectualcrafters/jnbt/NBTConstants.java b/Core/src/main/java/com/intellectualcrafters/jnbt/NBTConstants.java similarity index 100% rename from src/main/java/com/intellectualcrafters/jnbt/NBTConstants.java rename to Core/src/main/java/com/intellectualcrafters/jnbt/NBTConstants.java diff --git a/src/main/java/com/intellectualcrafters/jnbt/NBTInputStream.java b/Core/src/main/java/com/intellectualcrafters/jnbt/NBTInputStream.java similarity index 100% rename from src/main/java/com/intellectualcrafters/jnbt/NBTInputStream.java rename to Core/src/main/java/com/intellectualcrafters/jnbt/NBTInputStream.java diff --git a/src/main/java/com/intellectualcrafters/jnbt/NBTOutputStream.java b/Core/src/main/java/com/intellectualcrafters/jnbt/NBTOutputStream.java similarity index 100% rename from src/main/java/com/intellectualcrafters/jnbt/NBTOutputStream.java rename to Core/src/main/java/com/intellectualcrafters/jnbt/NBTOutputStream.java diff --git a/src/main/java/com/intellectualcrafters/jnbt/NBTUtils.java b/Core/src/main/java/com/intellectualcrafters/jnbt/NBTUtils.java similarity index 100% rename from src/main/java/com/intellectualcrafters/jnbt/NBTUtils.java rename to Core/src/main/java/com/intellectualcrafters/jnbt/NBTUtils.java diff --git a/src/main/java/com/intellectualcrafters/jnbt/ShortTag.java b/Core/src/main/java/com/intellectualcrafters/jnbt/ShortTag.java similarity index 100% rename from src/main/java/com/intellectualcrafters/jnbt/ShortTag.java rename to Core/src/main/java/com/intellectualcrafters/jnbt/ShortTag.java diff --git a/src/main/java/com/intellectualcrafters/jnbt/StringTag.java b/Core/src/main/java/com/intellectualcrafters/jnbt/StringTag.java similarity index 100% rename from src/main/java/com/intellectualcrafters/jnbt/StringTag.java rename to Core/src/main/java/com/intellectualcrafters/jnbt/StringTag.java diff --git a/src/main/java/com/intellectualcrafters/jnbt/Tag.java b/Core/src/main/java/com/intellectualcrafters/jnbt/Tag.java similarity index 100% rename from src/main/java/com/intellectualcrafters/jnbt/Tag.java rename to Core/src/main/java/com/intellectualcrafters/jnbt/Tag.java diff --git a/src/main/java/com/intellectualcrafters/json/CDL.java b/Core/src/main/java/com/intellectualcrafters/json/CDL.java similarity index 100% rename from src/main/java/com/intellectualcrafters/json/CDL.java rename to Core/src/main/java/com/intellectualcrafters/json/CDL.java diff --git a/src/main/java/com/intellectualcrafters/json/Cookie.java b/Core/src/main/java/com/intellectualcrafters/json/Cookie.java similarity index 100% rename from src/main/java/com/intellectualcrafters/json/Cookie.java rename to Core/src/main/java/com/intellectualcrafters/json/Cookie.java diff --git a/src/main/java/com/intellectualcrafters/json/CookieList.java b/Core/src/main/java/com/intellectualcrafters/json/CookieList.java similarity index 100% rename from src/main/java/com/intellectualcrafters/json/CookieList.java rename to Core/src/main/java/com/intellectualcrafters/json/CookieList.java diff --git a/src/main/java/com/intellectualcrafters/json/HTTP.java b/Core/src/main/java/com/intellectualcrafters/json/HTTP.java similarity index 100% rename from src/main/java/com/intellectualcrafters/json/HTTP.java rename to Core/src/main/java/com/intellectualcrafters/json/HTTP.java diff --git a/src/main/java/com/intellectualcrafters/json/HTTPTokener.java b/Core/src/main/java/com/intellectualcrafters/json/HTTPTokener.java similarity index 100% rename from src/main/java/com/intellectualcrafters/json/HTTPTokener.java rename to Core/src/main/java/com/intellectualcrafters/json/HTTPTokener.java diff --git a/src/main/java/com/intellectualcrafters/json/JSONArray.java b/Core/src/main/java/com/intellectualcrafters/json/JSONArray.java similarity index 100% rename from src/main/java/com/intellectualcrafters/json/JSONArray.java rename to Core/src/main/java/com/intellectualcrafters/json/JSONArray.java diff --git a/src/main/java/com/intellectualcrafters/json/JSONException.java b/Core/src/main/java/com/intellectualcrafters/json/JSONException.java similarity index 100% rename from src/main/java/com/intellectualcrafters/json/JSONException.java rename to Core/src/main/java/com/intellectualcrafters/json/JSONException.java diff --git a/src/main/java/com/intellectualcrafters/json/JSONML.java b/Core/src/main/java/com/intellectualcrafters/json/JSONML.java similarity index 100% rename from src/main/java/com/intellectualcrafters/json/JSONML.java rename to Core/src/main/java/com/intellectualcrafters/json/JSONML.java diff --git a/src/main/java/com/intellectualcrafters/json/JSONObject.java b/Core/src/main/java/com/intellectualcrafters/json/JSONObject.java similarity index 100% rename from src/main/java/com/intellectualcrafters/json/JSONObject.java rename to Core/src/main/java/com/intellectualcrafters/json/JSONObject.java diff --git a/src/main/java/com/intellectualcrafters/json/JSONString.java b/Core/src/main/java/com/intellectualcrafters/json/JSONString.java similarity index 100% rename from src/main/java/com/intellectualcrafters/json/JSONString.java rename to Core/src/main/java/com/intellectualcrafters/json/JSONString.java diff --git a/src/main/java/com/intellectualcrafters/json/JSONStringer.java b/Core/src/main/java/com/intellectualcrafters/json/JSONStringer.java similarity index 100% rename from src/main/java/com/intellectualcrafters/json/JSONStringer.java rename to Core/src/main/java/com/intellectualcrafters/json/JSONStringer.java diff --git a/src/main/java/com/intellectualcrafters/json/JSONTokener.java b/Core/src/main/java/com/intellectualcrafters/json/JSONTokener.java similarity index 100% rename from src/main/java/com/intellectualcrafters/json/JSONTokener.java rename to Core/src/main/java/com/intellectualcrafters/json/JSONTokener.java diff --git a/src/main/java/com/intellectualcrafters/json/JSONWriter.java b/Core/src/main/java/com/intellectualcrafters/json/JSONWriter.java similarity index 100% rename from src/main/java/com/intellectualcrafters/json/JSONWriter.java rename to Core/src/main/java/com/intellectualcrafters/json/JSONWriter.java diff --git a/src/main/java/com/intellectualcrafters/json/Kim.java b/Core/src/main/java/com/intellectualcrafters/json/Kim.java similarity index 100% rename from src/main/java/com/intellectualcrafters/json/Kim.java rename to Core/src/main/java/com/intellectualcrafters/json/Kim.java diff --git a/src/main/java/com/intellectualcrafters/json/Property.java b/Core/src/main/java/com/intellectualcrafters/json/Property.java similarity index 100% rename from src/main/java/com/intellectualcrafters/json/Property.java rename to Core/src/main/java/com/intellectualcrafters/json/Property.java diff --git a/src/main/java/com/intellectualcrafters/json/XML.java b/Core/src/main/java/com/intellectualcrafters/json/XML.java similarity index 100% rename from src/main/java/com/intellectualcrafters/json/XML.java rename to Core/src/main/java/com/intellectualcrafters/json/XML.java diff --git a/src/main/java/com/intellectualcrafters/json/XMLTokener.java b/Core/src/main/java/com/intellectualcrafters/json/XMLTokener.java similarity index 100% rename from src/main/java/com/intellectualcrafters/json/XMLTokener.java rename to Core/src/main/java/com/intellectualcrafters/json/XMLTokener.java diff --git a/src/main/java/com/intellectualcrafters/plot/IPlotMain.java b/Core/src/main/java/com/intellectualcrafters/plot/IPlotMain.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/IPlotMain.java rename to Core/src/main/java/com/intellectualcrafters/plot/IPlotMain.java diff --git a/src/main/java/com/intellectualcrafters/plot/PS.java b/Core/src/main/java/com/intellectualcrafters/plot/PS.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/PS.java rename to Core/src/main/java/com/intellectualcrafters/plot/PS.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Add.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Add.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Add.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Add.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Alias.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Alias.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Alias.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Alias.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Area.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Area.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Area.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Area.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Auto.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Auto.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Auto.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Auto.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/BO3.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/BO3.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/BO3.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/BO3.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Biome.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Biome.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Biome.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Biome.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Buy.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Buy.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Buy.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Buy.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Chat.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Chat.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Chat.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Chat.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Claim.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Claim.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Claim.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Claim.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Clear.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Clear.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Clear.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Clear.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Cluster.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Cluster.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Cluster.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Cluster.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/CommandCategory.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/CommandCategory.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/CommandCategory.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/CommandCategory.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/CommandPermission.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/CommandPermission.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/CommandPermission.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/CommandPermission.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Comment.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Comment.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Comment.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Comment.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Condense.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Condense.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Condense.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Condense.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Confirm.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Confirm.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Confirm.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Confirm.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Continue.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Continue.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Continue.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Continue.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Copy.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Copy.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Copy.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Copy.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/CreateRoadSchematic.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/CreateRoadSchematic.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/CreateRoadSchematic.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/CreateRoadSchematic.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Database.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Database.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Database.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Database.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Debug.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Debug.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Debug.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Debug.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/DebugAllowUnsafe.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugAllowUnsafe.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/DebugAllowUnsafe.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/DebugAllowUnsafe.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/DebugFixFlags.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugFixFlags.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/DebugFixFlags.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/DebugFixFlags.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/DebugLoadTest.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugLoadTest.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/DebugLoadTest.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/DebugLoadTest.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/DebugPaste.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugPaste.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/DebugPaste.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/DebugPaste.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/DebugRoadRegen.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugRoadRegen.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/DebugRoadRegen.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/DebugRoadRegen.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/DebugSaveTest.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugSaveTest.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/DebugSaveTest.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/DebugSaveTest.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Delete.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Delete.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Delete.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Delete.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Deny.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Deny.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Deny.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Deny.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Desc.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Desc.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Desc.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Desc.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Done.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Done.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Done.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Done.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Download.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Download.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Download.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Download.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/FlagCmd.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/FlagCmd.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/FlagCmd.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/FlagCmd.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/GenerateDocs.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/GenerateDocs.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/GenerateDocs.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/GenerateDocs.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Grant.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Grant.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Grant.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Grant.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Help.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Help.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Help.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Help.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Home.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Home.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Home.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Home.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Inbox.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Inbox.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Inbox.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Inbox.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Info.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Info.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Info.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Info.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Kick.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Kick.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Kick.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Kick.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Load.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Load.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Load.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Load.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java similarity index 97% rename from src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java index 889ecea32..31e5e708d 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java @@ -1,468 +1,468 @@ -//////////////////////////////////////////////////////////////////////////////////////////////////// -// PlotSquared - A plot manager and world generator for the Bukkit API / -// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / -// / -// This program is free software; you can redistribute it and/or modify / -// it under the terms of the GNU General Public License as published by / -// the Free Software Foundation; either version 3 of the License, or / -// (at your option) any later version. / -// / -// This program is distributed in the hope that it will be useful, / -// but WITHOUT ANY WARRANTY; without even the implied warranty of / -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / -// GNU General Public License for more details. / -// / -// You should have received a copy of the GNU General Public License / -// along with this program; if not, write to the Free Software Foundation, / -// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / -// / -// You can contact us via: support@intellectualsites.com / -//////////////////////////////////////////////////////////////////////////////////////////////////// -package com.intellectualcrafters.plot.commands; - -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.object.ConsolePlayer; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.MathMan; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.StringComparison; -import com.intellectualcrafters.plot.util.StringMan; -import com.intellectualcrafters.plot.util.helpmenu.HelpMenu; -import com.plotsquared.general.commands.Argument; -import com.plotsquared.general.commands.Command; -import com.plotsquared.general.commands.CommandHandlingOutput; -import com.plotsquared.general.commands.CommandManager; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; - -/** - * PlotSquared command class - * - - */ -public class MainCommand extends CommandManager { - - private static MainCommand instance; - private HashMap> setCommands; - - private MainCommand() { - super(null, new ArrayList>()); - instance = this; - createCommand(new Buy()); - createCommand(new Save()); - createCommand(new Load()); - createCommand(new Confirm()); - createCommand(new Template()); - createCommand(new Download()); - createCommand(new Update()); - createCommand(new Template()); - createCommand(new Setup()); - createCommand(new Area()); - createCommand(new DebugSaveTest()); - createCommand(new DebugLoadTest()); - createCommand(new CreateRoadSchematic()); - createCommand(new DebugAllowUnsafe()); - createCommand(new RegenAllRoads()); - createCommand(new Claim()); - createCommand(new Auto()); - createCommand(new Visit()); - createCommand(new Home()); - createCommand(new Set()); - createCommand(new Toggle()); - createCommand(new Clear()); - createCommand(new Delete()); - createCommand(new Trust()); - createCommand(new Add()); - createCommand(new Deny()); - createCommand(new Untrust()); - createCommand(new Remove()); - createCommand(new Undeny()); - createCommand(new Info()); - createCommand(new list()); - createCommand(new Help()); - createCommand(new Debug()); - createCommand(new SchematicCmd()); - createCommand(new plugin()); - createCommand(new Purge()); - createCommand(new Reload()); - createCommand(new Merge()); - createCommand(new DebugPaste()); - createCommand(new Unlink()); - createCommand(new Kick()); - createCommand(new Rate()); - createCommand(new DebugClaimTest()); - createCommand(new Inbox()); - createCommand(new Comment()); - createCommand(new Database()); - createCommand(new Swap()); - createCommand(new MusicSubcommand()); - createCommand(new DebugRoadRegen()); - createCommand(new Trust()); - createCommand(new DebugExec()); - createCommand(new FlagCmd()); - createCommand(new Target()); - createCommand(new DebugFixFlags()); - createCommand(new Move()); - createCommand(new Condense()); - createCommand(new Condense()); - createCommand(new Copy()); - createCommand(new Chat()); - createCommand(new Trim()); - createCommand(new Done()); - createCommand(new Continue()); - createCommand(new BO3()); - createCommand(new Middle()); - createCommand(new Grant()); - // set commands - createCommand(new Owner()); - createCommand(new Desc()); - createCommand(new Biome()); - createCommand(new Alias()); - createCommand(new SetHome()); - if (Settings.ENABLE_CLUSTERS) { - MainCommand.getInstance().addCommand(new Cluster()); - } - } - - public static MainCommand getInstance() { - if (instance == null) { - instance = new MainCommand(); - } - return instance; - } - - public static boolean no_permission(final PlotPlayer player, final String permission) { - MainUtil.sendMessage(player, C.NO_PERMISSION, permission); - return false; - } - - public static List> getCommandAndAliases(final CommandCategory category, final PlotPlayer player) { - final List> commands = new ArrayList<>(); - for (final Command command : getInstance().getCommands()) { - if ((category != null) && !command.getCategory().equals(category)) { - continue; - } - if ((player != null) && !Permissions.hasPermission(player, command.getPermission())) { - continue; - } - commands.add(command); - } - return commands; - } - - public static List> getCommands(final CommandCategory category, final PlotPlayer player) { - final List> commands = new ArrayList<>(); - for (final Command command : new HashSet<>(getInstance().getCommands())) { - if ((category != null) && !command.getCategory().equals(category)) { - continue; - } - if ((player != null) && !Permissions.hasPermission(player, command.getPermission())) { - continue; - } - commands.add(command); - } - return commands; - } - - public static void displayHelp(final PlotPlayer player, String cat, int page, final String label) { - CommandCategory catEnum = null; - if (cat != null) { - if (StringMan.isEqualIgnoreCase(cat, "all")) { - catEnum = null; - } else { - for (final CommandCategory c : CommandCategory.values()) { - if (StringMan.isEqualIgnoreCaseToAny(cat, c.name(), c.toString())) { - catEnum = c; - cat = c.name(); - break; - } - } - if (catEnum == null) { - cat = null; - } - } - } - if ((cat == null) && (page == 0)) { - final StringBuilder builder = new StringBuilder(); - builder.append(C.HELP_HEADER.s()); - for (final CommandCategory c : CommandCategory.values()) { - builder.append("\n" + StringMan.replaceAll(C.HELP_INFO_ITEM.s(), "%category%", c.toString().toLowerCase(), "%category_desc%", c.toString())); - } - builder.append("\n").append(C.HELP_INFO_ITEM.s().replaceAll("%category%", "all").replaceAll("%category_desc%", "Display all commands")); - builder.append("\n" + C.HELP_FOOTER.s()); - MainUtil.sendMessage(player, builder.toString(), false); - return; - } - page--; - new HelpMenu(player).setCategory(catEnum).getCommands().generateMaxPages().generatePage(page, label).render(); - } - - public static boolean onCommand(final PlotPlayer player, final String cmd, String... args) { - // Clear perm caching // - player.deleteMeta("perm"); - //////////////////////// - int help_index = -1; - String category = null; - Location loc = null; - Plot plot = null; - boolean tp = false; - switch (args.length) { - case 0: { - help_index = 0; - break; - } - case 1: { - if (MathMan.isInteger(args[0])) { - try { - help_index = Integer.parseInt(args[args.length - 1]); - } catch (final NumberFormatException e) {} - break; - } - } - default: { - switch (args[0].toLowerCase()) { - case "he": - case "help": - case "?": { - switch (args.length) { - case 1: { - help_index = 0; - break; - } - case 2: { - if (MathMan.isInteger(args[1])) { - category = null; - try { - help_index = Integer.parseInt(args[1]); - } catch (final NumberFormatException e) { - help_index = 1; - } - } else { - help_index = 1; - category = args[1]; - } - break; - } - case 3: { - category = args[1]; - if (MathMan.isInteger(args[2])) { - try { - help_index = Integer.parseInt(args[2]); - } catch (final NumberFormatException e) { - help_index = 1; - } - } - break; - } - default: { - C.COMMAND_SYNTAX.send(player, "/" + cmd + "? [#||category [#]]"); - return true; - } - } - break; - } - default: { - if (args.length >= 2) { - PlotArea area = player.getApplicablePlotArea(); - Plot newPlot = Plot.fromString(area, args[0]); - if (newPlot == null) { - break; - } - if (!ConsolePlayer.isConsole(player) && (!newPlot.getArea().equals(area) || newPlot.isDenied(player.getUUID())) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN)) { - break; - } - // Save meta - loc = (Location) player.getMeta("location"); - plot = (Plot) player.getMeta("lastplot"); - tp = true; - // Set loc - player.setMeta("location", newPlot.getBottomAbs()); - player.setMeta("lastplot", newPlot); - // Trim command - args = Arrays.copyOfRange(args, 1, args.length); - } - } - } - } - } - if (help_index != -1) { - displayHelp(player, category, help_index, cmd); - return true; - } - if (args[0].contains(":")) { - args[0] = args[0].replaceFirst(":", " "); - } - String fullCmd = StringMan.join(args, " "); - getInstance().handle(player, cmd + " " + fullCmd); - // Restore location - if (tp) { - if (loc == null) { - player.deleteMeta("location"); - } else { - player.setMeta("location", loc); - } - if (plot == null) { - player.deleteMeta("lastplot"); - } else { - player.setMeta("lastplot", plot); - } - } - return true; - } - - public int getMatch(String[] args, Command cmd) { - int count = 0; - String perm = cmd.getPermission(); - HashSet desc = new HashSet(); - for (String alias : cmd.getAliases()) { - if (alias.startsWith(args[0])) { - count += 5; - } - } - Collections.addAll(desc, cmd.getDescription().split(" ")); - for (String arg : args) { - if (perm.startsWith(arg)) { - count++; - } - if (desc.contains(arg)) { - count++; - } - } - String[] usage = cmd.getUsage().split(" "); - for (int i = 0; i < Math.min(4 , usage.length); i++) { - int require; - if (usage[i].startsWith("<")) { - require = 1; - } else { - require = 0; - } - String[] split = usage[i].split("\\|| |\\>|\\<|\\[|\\]|\\{|\\}|\\_|\\/"); - for (String aSplit : split) { - for (String arg : args) { - if (StringMan.isEqualIgnoreCase(arg, aSplit)) { - count += 5 - i + require; - } - } - } - } - count += StringMan.intersection(desc, args); - return count; - } - - @Override - public int handle(final PlotPlayer plr, final String input) { - final String[] parts = input.split(" "); - String[] args; - String label; - if (parts.length == 1) { - label = null; - args = new String[0]; - } else { - label = parts[1]; - args = new String[parts.length - 2]; - System.arraycopy(parts, 2, args, 0, args.length); - } - Command cmd; - if (label != null) { - if (label.contains(":")) { - // Ref: c:v, this will push value to the last spot in the array - // ex. /p h:2 SomeUsername - // > /p h SomeUsername 2 - String[] temp = label.split(":"); - label = temp[0]; - - String[] tempArgs = new String[args.length + 1]; - System.arraycopy(args, 0, tempArgs, 0, args.length); - tempArgs[tempArgs.length - 1] = temp[1]; - - args = tempArgs; - } - cmd = getInstance().commands.get(label.toLowerCase()); - } else { - cmd = null; - } - if (cmd == null) { - MainUtil.sendMessage(plr, C.NOT_VALID_SUBCOMMAND); - { - final List> cmds = getCommands(null, plr); - if ((label == null) || (cmds.isEmpty())) { - MainUtil.sendMessage(plr, C.DID_YOU_MEAN, "/plot help"); - } else { - final HashSet setargs = new HashSet<>(args.length + 1); - for (final String arg : args) { - setargs.add(arg.toLowerCase()); - } - setargs.add(label); - final String[] allargs = setargs.toArray(new String[setargs.size()]); - int best = 0; - for (final Command current : cmds) { - int match = getMatch(allargs, current); - if (match > best) { - cmd = current; - } - } - if (cmd == null) { - cmd = new StringComparison<>(label, getCommandAndAliases(null, plr)).getMatchObject(); - } - MainUtil.sendMessage(plr, C.DID_YOU_MEAN, cmd.getUsage().replaceAll("\\{label\\}", parts[0])); - } - } - return CommandHandlingOutput.NOT_FOUND; - } - if (!cmd.getRequiredType().allows(plr)) { - if (ConsolePlayer.isConsole(plr)) { - MainUtil.sendMessage(plr, C.IS_CONSOLE); - } else { - MainUtil.sendMessage(plr, C.NOT_CONSOLE); - } - return CommandHandlingOutput.CALLER_OF_WRONG_TYPE; - } - if (!Permissions.hasPermission(plr, cmd.getPermission())) { - MainUtil.sendMessage(plr, C.NO_PERMISSION, cmd.getPermission()); - return CommandHandlingOutput.NOT_PERMITTED; - } - final Argument[] requiredArguments = cmd.getRequiredArguments(); - if ((requiredArguments != null) && (requiredArguments.length > 0)) { - boolean success = true; - if (args.length < requiredArguments.length) { - success = false; - } else { - for (int i = 0; i < requiredArguments.length; i++) { - if (requiredArguments[i].parse(args[i]) == null) { - success = false; - break; - } - } - } - if (!success) { - C.COMMAND_SYNTAX.send(plr, cmd.getUsage()); - return CommandHandlingOutput.WRONG_USAGE; - } - } - try { - final boolean result = cmd.onCommand(plr, args); - if (!result) { - cmd.getUsage(); - // Unecessary! - // if (usage != null && !usage.isEmpty()) { - // MainUtil.sendMessage(plr, usage); - // } - return CommandHandlingOutput.WRONG_USAGE; - } - } catch (final Throwable t) { - t.printStackTrace(); - return CommandHandlingOutput.ERROR; - } - return CommandHandlingOutput.SUCCESS; - } -} +//////////////////////////////////////////////////////////////////////////////////////////////////// +// PlotSquared - A plot manager and world generator for the Bukkit API / +// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / +// / +// This program is free software; you can redistribute it and/or modify / +// it under the terms of the GNU General Public License as published by / +// the Free Software Foundation; either version 3 of the License, or / +// (at your option) any later version. / +// / +// This program is distributed in the hope that it will be useful, / +// but WITHOUT ANY WARRANTY; without even the implied warranty of / +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / +// GNU General Public License for more details. / +// / +// You should have received a copy of the GNU General Public License / +// along with this program; if not, write to the Free Software Foundation, / +// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / +// / +// You can contact us via: support@intellectualsites.com / +//////////////////////////////////////////////////////////////////////////////////////////////////// +package com.intellectualcrafters.plot.commands; + +import com.intellectualcrafters.plot.config.C; +import com.intellectualcrafters.plot.config.Settings; +import com.intellectualcrafters.plot.object.ConsolePlayer; +import com.intellectualcrafters.plot.object.Location; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotArea; +import com.intellectualcrafters.plot.object.PlotPlayer; +import com.intellectualcrafters.plot.util.MainUtil; +import com.intellectualcrafters.plot.util.MathMan; +import com.intellectualcrafters.plot.util.Permissions; +import com.intellectualcrafters.plot.util.StringComparison; +import com.intellectualcrafters.plot.util.StringMan; +import com.intellectualcrafters.plot.util.helpmenu.HelpMenu; +import com.plotsquared.general.commands.Argument; +import com.plotsquared.general.commands.Command; +import com.plotsquared.general.commands.CommandHandlingOutput; +import com.plotsquared.general.commands.CommandManager; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; + +/** + * PlotSquared command class + * + + */ +public class MainCommand extends CommandManager { + + private static MainCommand instance; + private HashMap> setCommands; + + private MainCommand() { + super(null, new ArrayList>()); + instance = this; + createCommand(new Buy()); + createCommand(new Save()); + createCommand(new Load()); + createCommand(new Confirm()); + createCommand(new Template()); + createCommand(new Download()); + createCommand(new Update()); + createCommand(new Template()); + createCommand(new Setup()); + createCommand(new Area()); + createCommand(new DebugSaveTest()); + createCommand(new DebugLoadTest()); + createCommand(new CreateRoadSchematic()); + createCommand(new DebugAllowUnsafe()); + createCommand(new RegenAllRoads()); + createCommand(new Claim()); + createCommand(new Auto()); + createCommand(new Visit()); + createCommand(new Home()); + createCommand(new Set()); + createCommand(new Toggle()); + createCommand(new Clear()); + createCommand(new Delete()); + createCommand(new Trust()); + createCommand(new Add()); + createCommand(new Deny()); + createCommand(new Untrust()); + createCommand(new Remove()); + createCommand(new Undeny()); + createCommand(new Info()); + createCommand(new list()); + createCommand(new Help()); + createCommand(new Debug()); + createCommand(new SchematicCmd()); + createCommand(new plugin()); + createCommand(new Purge()); + createCommand(new Reload()); + createCommand(new Merge()); + createCommand(new DebugPaste()); + createCommand(new Unlink()); + createCommand(new Kick()); + createCommand(new Rate()); + createCommand(new DebugClaimTest()); + createCommand(new Inbox()); + createCommand(new Comment()); + createCommand(new Database()); + createCommand(new Swap()); + createCommand(new MusicSubcommand()); + createCommand(new DebugRoadRegen()); + createCommand(new Trust()); + createCommand(new DebugExec()); + createCommand(new FlagCmd()); + createCommand(new Target()); + createCommand(new DebugFixFlags()); + createCommand(new Move()); + createCommand(new Condense()); + createCommand(new Condense()); + createCommand(new Copy()); + createCommand(new Chat()); + createCommand(new Trim()); + createCommand(new Done()); + createCommand(new Continue()); + createCommand(new BO3()); + createCommand(new Middle()); + createCommand(new Grant()); + // set commands + createCommand(new Owner()); + createCommand(new Desc()); + createCommand(new Biome()); + createCommand(new Alias()); + createCommand(new SetHome()); + if (Settings.ENABLE_CLUSTERS) { + MainCommand.getInstance().addCommand(new Cluster()); + } + } + + public static MainCommand getInstance() { + if (instance == null) { + instance = new MainCommand(); + } + return instance; + } + + public static boolean no_permission(final PlotPlayer player, final String permission) { + MainUtil.sendMessage(player, C.NO_PERMISSION, permission); + return false; + } + + public static List> getCommandAndAliases(final CommandCategory category, final PlotPlayer player) { + final List> commands = new ArrayList<>(); + for (final Command command : getInstance().getCommands()) { + if ((category != null) && !command.getCategory().equals(category)) { + continue; + } + if ((player != null) && !Permissions.hasPermission(player, command.getPermission())) { + continue; + } + commands.add(command); + } + return commands; + } + + public static List> getCommands(final CommandCategory category, final PlotPlayer player) { + final List> commands = new ArrayList<>(); + for (final Command command : new HashSet<>(getInstance().getCommands())) { + if ((category != null) && !command.getCategory().equals(category)) { + continue; + } + if ((player != null) && !Permissions.hasPermission(player, command.getPermission())) { + continue; + } + commands.add(command); + } + return commands; + } + + public static void displayHelp(final PlotPlayer player, String cat, int page, final String label) { + CommandCategory catEnum = null; + if (cat != null) { + if (StringMan.isEqualIgnoreCase(cat, "all")) { + catEnum = null; + } else { + for (final CommandCategory c : CommandCategory.values()) { + if (StringMan.isEqualIgnoreCaseToAny(cat, c.name(), c.toString())) { + catEnum = c; + cat = c.name(); + break; + } + } + if (catEnum == null) { + cat = null; + } + } + } + if ((cat == null) && (page == 0)) { + final StringBuilder builder = new StringBuilder(); + builder.append(C.HELP_HEADER.s()); + for (final CommandCategory c : CommandCategory.values()) { + builder.append("\n" + StringMan.replaceAll(C.HELP_INFO_ITEM.s(), "%category%", c.toString().toLowerCase(), "%category_desc%", c.toString())); + } + builder.append("\n").append(C.HELP_INFO_ITEM.s().replaceAll("%category%", "all").replaceAll("%category_desc%", "Display all commands")); + builder.append("\n" + C.HELP_FOOTER.s()); + MainUtil.sendMessage(player, builder.toString(), false); + return; + } + page--; + new HelpMenu(player).setCategory(catEnum).getCommands().generateMaxPages().generatePage(page, label).render(); + } + + public static boolean onCommand(final PlotPlayer player, final String cmd, String... args) { + // Clear perm caching // + player.deleteMeta("perm"); + //////////////////////// + int help_index = -1; + String category = null; + Location loc = null; + Plot plot = null; + boolean tp = false; + switch (args.length) { + case 0: { + help_index = 0; + break; + } + case 1: { + if (MathMan.isInteger(args[0])) { + try { + help_index = Integer.parseInt(args[args.length - 1]); + } catch (final NumberFormatException e) {} + break; + } + } + default: { + switch (args[0].toLowerCase()) { + case "he": + case "help": + case "?": { + switch (args.length) { + case 1: { + help_index = 0; + break; + } + case 2: { + if (MathMan.isInteger(args[1])) { + category = null; + try { + help_index = Integer.parseInt(args[1]); + } catch (final NumberFormatException e) { + help_index = 1; + } + } else { + help_index = 1; + category = args[1]; + } + break; + } + case 3: { + category = args[1]; + if (MathMan.isInteger(args[2])) { + try { + help_index = Integer.parseInt(args[2]); + } catch (final NumberFormatException e) { + help_index = 1; + } + } + break; + } + default: { + C.COMMAND_SYNTAX.send(player, "/" + cmd + "? [#||category [#]]"); + return true; + } + } + break; + } + default: { + if (args.length >= 2) { + PlotArea area = player.getApplicablePlotArea(); + Plot newPlot = Plot.fromString(area, args[0]); + if (newPlot == null) { + break; + } + if (!ConsolePlayer.isConsole(player) && (!newPlot.getArea().equals(area) || newPlot.isDenied(player.getUUID())) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN)) { + break; + } + // Save meta + loc = (Location) player.getMeta("location"); + plot = (Plot) player.getMeta("lastplot"); + tp = true; + // Set loc + player.setMeta("location", newPlot.getBottomAbs()); + player.setMeta("lastplot", newPlot); + // Trim command + args = Arrays.copyOfRange(args, 1, args.length); + } + } + } + } + } + if (help_index != -1) { + displayHelp(player, category, help_index, cmd); + return true; + } + if (args[0].contains(":")) { + args[0] = args[0].replaceFirst(":", " "); + } + String fullCmd = StringMan.join(args, " "); + getInstance().handle(player, cmd + " " + fullCmd); + // Restore location + if (tp) { + if (loc == null) { + player.deleteMeta("location"); + } else { + player.setMeta("location", loc); + } + if (plot == null) { + player.deleteMeta("lastplot"); + } else { + player.setMeta("lastplot", plot); + } + } + return true; + } + + public int getMatch(String[] args, Command cmd) { + int count = 0; + String perm = cmd.getPermission(); + HashSet desc = new HashSet(); + for (String alias : cmd.getAliases()) { + if (alias.startsWith(args[0])) { + count += 5; + } + } + Collections.addAll(desc, cmd.getDescription().split(" ")); + for (String arg : args) { + if (perm.startsWith(arg)) { + count++; + } + if (desc.contains(arg)) { + count++; + } + } + String[] usage = cmd.getUsage().split(" "); + for (int i = 0; i < Math.min(4 , usage.length); i++) { + int require; + if (usage[i].startsWith("<")) { + require = 1; + } else { + require = 0; + } + String[] split = usage[i].split("\\|| |\\>|\\<|\\[|\\]|\\{|\\}|\\_|\\/"); + for (String aSplit : split) { + for (String arg : args) { + if (StringMan.isEqualIgnoreCase(arg, aSplit)) { + count += 5 - i + require; + } + } + } + } + count += StringMan.intersection(desc, args); + return count; + } + + @Override + public int handle(final PlotPlayer plr, final String input) { + final String[] parts = input.split(" "); + String[] args; + String label; + if (parts.length == 1) { + label = null; + args = new String[0]; + } else { + label = parts[1]; + args = new String[parts.length - 2]; + System.arraycopy(parts, 2, args, 0, args.length); + } + Command cmd; + if (label != null) { + if (label.contains(":")) { + // Ref: c:v, this will push value to the last spot in the array + // ex. /p h:2 SomeUsername + // > /p h SomeUsername 2 + String[] temp = label.split(":"); + label = temp[0]; + + String[] tempArgs = new String[args.length + 1]; + System.arraycopy(args, 0, tempArgs, 0, args.length); + tempArgs[tempArgs.length - 1] = temp[1]; + + args = tempArgs; + } + cmd = getInstance().commands.get(label.toLowerCase()); + } else { + cmd = null; + } + if (cmd == null) { + MainUtil.sendMessage(plr, C.NOT_VALID_SUBCOMMAND); + { + final List> cmds = getCommands(null, plr); + if ((label == null) || (cmds.isEmpty())) { + MainUtil.sendMessage(plr, C.DID_YOU_MEAN, "/plot help"); + } else { + final HashSet setargs = new HashSet<>(args.length + 1); + for (final String arg : args) { + setargs.add(arg.toLowerCase()); + } + setargs.add(label); + final String[] allargs = setargs.toArray(new String[setargs.size()]); + int best = 0; + for (final Command current : cmds) { + int match = getMatch(allargs, current); + if (match > best) { + cmd = current; + } + } + if (cmd == null) { + cmd = new StringComparison<>(label, getCommandAndAliases(null, plr)).getMatchObject(); + } + MainUtil.sendMessage(plr, C.DID_YOU_MEAN, cmd.getUsage().replaceAll("\\{label\\}", parts[0])); + } + } + return CommandHandlingOutput.NOT_FOUND; + } + if (!cmd.getRequiredType().allows(plr)) { + if (ConsolePlayer.isConsole(plr)) { + MainUtil.sendMessage(plr, C.IS_CONSOLE); + } else { + MainUtil.sendMessage(plr, C.NOT_CONSOLE); + } + return CommandHandlingOutput.CALLER_OF_WRONG_TYPE; + } + if (!Permissions.hasPermission(plr, cmd.getPermission())) { + MainUtil.sendMessage(plr, C.NO_PERMISSION, cmd.getPermission()); + return CommandHandlingOutput.NOT_PERMITTED; + } + final Argument[] requiredArguments = cmd.getRequiredArguments(); + if ((requiredArguments != null) && (requiredArguments.length > 0)) { + boolean success = true; + if (args.length < requiredArguments.length) { + success = false; + } else { + for (int i = 0; i < requiredArguments.length; i++) { + if (requiredArguments[i].parse(args[i]) == null) { + success = false; + break; + } + } + } + if (!success) { + C.COMMAND_SYNTAX.send(plr, cmd.getUsage()); + return CommandHandlingOutput.WRONG_USAGE; + } + } + try { + final boolean result = cmd.onCommand(plr, args); + if (!result) { + cmd.getUsage(); + // Unecessary! + // if (usage != null && !usage.isEmpty()) { + // MainUtil.sendMessage(plr, usage); + // } + return CommandHandlingOutput.WRONG_USAGE; + } + } catch (final Throwable t) { + t.printStackTrace(); + return CommandHandlingOutput.ERROR; + } + return CommandHandlingOutput.SUCCESS; + } +} diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Merge.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Merge.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Merge.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Merge.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Middle.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Middle.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Middle.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Middle.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Move.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Move.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Move.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Move.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/MusicSubcommand.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/MusicSubcommand.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/MusicSubcommand.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/MusicSubcommand.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Owner.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Owner.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Owner.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Owner.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Purge.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Purge.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Purge.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Purge.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Rate.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Rate.java similarity index 95% rename from src/main/java/com/intellectualcrafters/plot/commands/Rate.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Rate.java index 6edd81a0d..b4fcd2f49 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/Rate.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Rate.java @@ -27,8 +27,6 @@ import java.util.HashMap; import java.util.Map.Entry; import java.util.UUID; -import org.apache.commons.lang.mutable.MutableInt; - import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; @@ -125,11 +123,11 @@ public class Rate extends SubCommand { final PlotInventory inventory = new PlotInventory(player, 1, title) { @Override public boolean onClick(final int i) { - rating.add((i + 1) * Math.pow(10, index.intValue())); + rating.add((i + 1) * Math.pow(10, index.getValue())); index.increment(); - if (index.intValue() >= Settings.RATING_CATEGORIES.size()) { + if (index.getValue() >= Settings.RATING_CATEGORIES.size()) { close(); - final int rV = rating.intValue(); + final int rV = rating.getValue(); final Rating result = EventUtil.manager.callRating(player, plot, new Rating(rV)); plot.getSettings().ratings.put(player.getUUID(), result.getAggregate()); DBFunc.setRating(plot, player.getUUID(), rV); @@ -137,7 +135,7 @@ public class Rate extends SubCommand { sendMessage(player, C.RATING_APPLIED, plot.getId().toString()); return false; } - setTitle(Settings.RATING_CATEGORIES.get(index.intValue())); + setTitle(Settings.RATING_CATEGORIES.get(index.getValue())); if (Permissions.hasPermission(player, "plots.comment")) { final Command command = MainCommand.getInstance().getCommand("comment"); if (command != null) { @@ -222,4 +220,27 @@ public class Rate extends SubCommand { run.run(); return true; } + + private class MutableInt { + + private int value; + + public MutableInt(int i) { + value = i; + } + public void increment() { + value++; + } + public void decrement() { + value--; + } + + public int getValue() { + return value; + } + + public void add(Number v) { + this.value += v.intValue(); + } + } } diff --git a/src/main/java/com/intellectualcrafters/plot/commands/RegenAllRoads.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/RegenAllRoads.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/RegenAllRoads.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/RegenAllRoads.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Reload.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Reload.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Reload.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Reload.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Remove.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Remove.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Remove.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Remove.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/RequiredType.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/RequiredType.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/RequiredType.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/RequiredType.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Save.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Save.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Save.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Save.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/SchematicCmd.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/SchematicCmd.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/SchematicCmd.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/SchematicCmd.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Set.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Set.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Set.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Set.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/SetCommand.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/SetCommand.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/SetCommand.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/SetCommand.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/SetHome.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/SetHome.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/SetHome.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/SetHome.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Setup.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Setup.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Setup.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Setup.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/SubCommand.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/SubCommand.java similarity index 98% rename from src/main/java/com/intellectualcrafters/plot/commands/SubCommand.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/SubCommand.java index 0b7fdd49b..4e00accf1 100644 --- a/src/main/java/com/intellectualcrafters/plot/commands/SubCommand.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/SubCommand.java @@ -1,99 +1,99 @@ -//////////////////////////////////////////////////////////////////////////////////////////////////// -// PlotSquared - A plot manager and world generator for the Bukkit API / -// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / -// / -// This program is free software; you can redistribute it and/or modify / -// it under the terms of the GNU General Public License as published by / -// the Free Software Foundation; either version 3 of the License, or / -// (at your option) any later version. / -// / -// This program is distributed in the hope that it will be useful, / -// but WITHOUT ANY WARRANTY; without even the implied warranty of / -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / -// GNU General Public License for more details. / -// / -// You should have received a copy of the GNU General Public License / -// along with this program; if not, write to the Free Software Foundation, / -// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / -// / -// You can contact us via: support@intellectualsites.com / -//////////////////////////////////////////////////////////////////////////////////////////////////// -package com.intellectualcrafters.plot.commands; - -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.object.PlotMessage; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal3; -import com.intellectualcrafters.plot.util.MainUtil; - -import java.util.List; - -/** - * SubCommand class - * - - */ -public abstract class SubCommand extends com.plotsquared.general.commands.Command { - - /** - * The category - */ - public CommandCategory category; - - /** - * Send a message - * - * @param plr Player who will receive the message - * @param c Caption - * @param args Arguments (%s's) - * - * @see MainUtil#sendMessage(PlotPlayer, C, String...) - */ - public boolean sendMessage(final PlotPlayer plr, final C c, final String... args) { - c.send(plr, args); - return true; - } - - public void paginate(PlotPlayer player, List c, int size, int page, RunnableVal3 add, String baseCommand, String header) { - // Calculate pages & index - if (page < 0) { - page = 0; - } - final int totalPages = (int) Math.ceil(c.size() / size); - if (page > totalPages) { - page = totalPages; - } - int max = page * size + size; - if (max > c.size()) { - max = c.size(); - } - // Send the header - header = header.replaceAll("%cur", page + 1 + "").replaceAll("%max", totalPages + 1 + "").replaceAll("%amount%", totalPages + "").replaceAll("%word%", "all"); - MainUtil.sendMessage(player, header); - // Send the page content - final List subList = c.subList(page * size, max); - int i = page * size; - for (final T obj : subList) { - i++; - PlotMessage msg = new PlotMessage(); - add.run(i, obj, msg); - msg.send(player); - } - // Send the footer - if (page < totalPages && page > 0) { // Back | Next - new PlotMessage().text("<-").color("$1").command(baseCommand + " " + page).text(" | ").color("$3").text("->").color("$1") - .command(baseCommand + " " + (page + 2)) - .text(C.CLICKABLE.s()).color("$2").send(player); - return; - } - if (page == 0 && totalPages != 0) { // Next - new PlotMessage().text("<-").color("$3").text(" | ").color("$3").text("->").color("$1").command(baseCommand + " " + (page + 2)).text(C.CLICKABLE.s()).color("$2").send(player); - return; - } - if (page == totalPages && totalPages != 0) { // Back - new PlotMessage().text("<-").color("$1").command(baseCommand + " " + page).text(" | ").color("$3").text("->").color("$3") - .text(C.CLICKABLE.s()).color("$2").send(player); - - } - } -} +//////////////////////////////////////////////////////////////////////////////////////////////////// +// PlotSquared - A plot manager and world generator for the Bukkit API / +// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / +// / +// This program is free software; you can redistribute it and/or modify / +// it under the terms of the GNU General Public License as published by / +// the Free Software Foundation; either version 3 of the License, or / +// (at your option) any later version. / +// / +// This program is distributed in the hope that it will be useful, / +// but WITHOUT ANY WARRANTY; without even the implied warranty of / +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / +// GNU General Public License for more details. / +// / +// You should have received a copy of the GNU General Public License / +// along with this program; if not, write to the Free Software Foundation, / +// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / +// / +// You can contact us via: support@intellectualsites.com / +//////////////////////////////////////////////////////////////////////////////////////////////////// +package com.intellectualcrafters.plot.commands; + +import com.intellectualcrafters.plot.config.C; +import com.intellectualcrafters.plot.object.PlotMessage; +import com.intellectualcrafters.plot.object.PlotPlayer; +import com.intellectualcrafters.plot.object.RunnableVal3; +import com.intellectualcrafters.plot.util.MainUtil; + +import java.util.List; + +/** + * SubCommand class + * + + */ +public abstract class SubCommand extends com.plotsquared.general.commands.Command { + + /** + * The category + */ + public CommandCategory category; + + /** + * Send a message + * + * @param plr Player who will receive the message + * @param c Caption + * @param args Arguments (%s's) + * + * @see MainUtil#sendMessage(PlotPlayer, C, String...) + */ + public boolean sendMessage(final PlotPlayer plr, final C c, final String... args) { + c.send(plr, args); + return true; + } + + public void paginate(PlotPlayer player, List c, int size, int page, RunnableVal3 add, String baseCommand, String header) { + // Calculate pages & index + if (page < 0) { + page = 0; + } + final int totalPages = (int) Math.ceil(c.size() / size); + if (page > totalPages) { + page = totalPages; + } + int max = page * size + size; + if (max > c.size()) { + max = c.size(); + } + // Send the header + header = header.replaceAll("%cur", page + 1 + "").replaceAll("%max", totalPages + 1 + "").replaceAll("%amount%", totalPages + "").replaceAll("%word%", "all"); + MainUtil.sendMessage(player, header); + // Send the page content + final List subList = c.subList(page * size, max); + int i = page * size; + for (final T obj : subList) { + i++; + PlotMessage msg = new PlotMessage(); + add.run(i, obj, msg); + msg.send(player); + } + // Send the footer + if (page < totalPages && page > 0) { // Back | Next + new PlotMessage().text("<-").color("$1").command(baseCommand + " " + page).text(" | ").color("$3").text("->").color("$1") + .command(baseCommand + " " + (page + 2)) + .text(C.CLICKABLE.s()).color("$2").send(player); + return; + } + if (page == 0 && totalPages != 0) { // Next + new PlotMessage().text("<-").color("$3").text(" | ").color("$3").text("->").color("$1").command(baseCommand + " " + (page + 2)).text(C.CLICKABLE.s()).color("$2").send(player); + return; + } + if (page == totalPages && totalPages != 0) { // Back + new PlotMessage().text("<-").color("$1").command(baseCommand + " " + page).text(" | ").color("$3").text("->").color("$3") + .text(C.CLICKABLE.s()).color("$2").send(player); + + } + } +} diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Swap.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Swap.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Swap.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Swap.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Target.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Target.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Target.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Target.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Template.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Template.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Template.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Template.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Toggle.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Toggle.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Toggle.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Toggle.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Trim.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Trim.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Trim.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Trim.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Trust.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Trust.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Trust.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Trust.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Undeny.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Undeny.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Undeny.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Undeny.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Unlink.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Unlink.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Unlink.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Unlink.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Untrust.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Untrust.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Untrust.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Untrust.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Update.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Update.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Update.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Update.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/Visit.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Visit.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/Visit.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/Visit.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/WE_Anywhere.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/WE_Anywhere.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/WE_Anywhere.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/WE_Anywhere.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/list.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/list.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/list.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/list.java diff --git a/src/main/java/com/intellectualcrafters/plot/commands/plugin.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/plugin.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/commands/plugin.java rename to Core/src/main/java/com/intellectualcrafters/plot/commands/plugin.java diff --git a/src/main/java/com/intellectualcrafters/plot/config/C.java b/Core/src/main/java/com/intellectualcrafters/plot/config/C.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/config/C.java rename to Core/src/main/java/com/intellectualcrafters/plot/config/C.java diff --git a/src/main/java/com/intellectualcrafters/plot/config/Configuration.java b/Core/src/main/java/com/intellectualcrafters/plot/config/Configuration.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/config/Configuration.java rename to Core/src/main/java/com/intellectualcrafters/plot/config/Configuration.java diff --git a/src/main/java/com/intellectualcrafters/plot/config/ConfigurationNode.java b/Core/src/main/java/com/intellectualcrafters/plot/config/ConfigurationNode.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/config/ConfigurationNode.java rename to Core/src/main/java/com/intellectualcrafters/plot/config/ConfigurationNode.java diff --git a/src/main/java/com/intellectualcrafters/plot/config/Settings.java b/Core/src/main/java/com/intellectualcrafters/plot/config/Settings.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/config/Settings.java rename to Core/src/main/java/com/intellectualcrafters/plot/config/Settings.java diff --git a/src/main/java/com/intellectualcrafters/plot/database/AbstractDB.java b/Core/src/main/java/com/intellectualcrafters/plot/database/AbstractDB.java similarity index 96% rename from src/main/java/com/intellectualcrafters/plot/database/AbstractDB.java rename to Core/src/main/java/com/intellectualcrafters/plot/database/AbstractDB.java index 2fe968e3c..d983f9b95 100644 --- a/src/main/java/com/intellectualcrafters/plot/database/AbstractDB.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/database/AbstractDB.java @@ -1,356 +1,356 @@ -//////////////////////////////////////////////////////////////////////////////////////////////////// -// PlotSquared - A plot manager and world generator for the Bukkit API / -// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / -// / -// This program is free software; you can redistribute it and/or modify / -// it under the terms of the GNU General Public License as published by / -// the Free Software Foundation; either version 3 of the License, or / -// (at your option) any later version. / -// / -// This program is distributed in the hope that it will be useful, / -// but WITHOUT ANY WARRANTY; without even the implied warranty of / -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / -// GNU General Public License for more details. / -// / -// You should have received a copy of the GNU General Public License / -// along with this program; if not, write to the Free Software Foundation, / -// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / -// / -// You can contact us via: support@intellectualsites.com / -//////////////////////////////////////////////////////////////////////////////////////////////////// -package com.intellectualcrafters.plot.database; - -import com.intellectualcrafters.plot.flag.Flag; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotCluster; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.object.comment.PlotComment; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -/** - - - */ -public interface AbstractDB { - - /** - * The UUID that will count as everyone - */ - UUID everyone = UUID.fromString("1-1-3-3-7"); - - /** - * Set Plot owner - * - * @param plot Plot in which the owner should be set - * @param uuid The uuid of the new owner - */ - void setOwner(final Plot plot, final UUID uuid); - - /** - * Create all settings, and create default helpers, trusted + denied lists - * - * @param plots Plots for which the default table entries should be created - */ - void createPlotsAndData(final ArrayList plots, final Runnable whenDone); - - /** - * Create a plot - * - * @param plot That should be created - */ - void createPlot(final Plot plot); - - /** - * Create tables - * - * @throws SQLException If the database manager is unable to create the tables - */ - void createTables() throws Exception; - - /** - * Delete a plot - * - * @param plot Plot that should be deleted - */ - void delete(final Plot plot); - - void deleteSettings(Plot plot); - - void deleteHelpers(Plot plot); - - void deleteTrusted(Plot plot); - - void deleteDenied(Plot plot); - - void deleteComments(Plot plot); - - void deleteRatings(Plot plot); - - void delete(final PlotCluster cluster); - - void addPersistentMeta(UUID uuid, String key, byte[] meta, boolean delete); - - void removePersistentMeta(UUID uuid, String key); - - void getPersistentMeta(UUID uuid, RunnableVal> result); - - /** - * Create plot settings - * - * @param id Plot Entry ID - * @param plot Plot Object - */ - void createPlotSettings(final int id, final Plot plot); - - /** - * Get the table entry ID - * - * @param plot Plot Object - * - * @return Integer = Plot Entry Id - */ - int getId(final Plot plot); - - /** - * Get the id of a given plot cluster - * - * @param cluster PlotCluster Object - * - * @return Integer = Cluster Entry Id - */ - int getClusterId(final PlotCluster cluster); - - /** - * @return A linked hashmap containing all plots - */ - HashMap> getPlots(); - - /** - * - */ - void validateAllPlots(final Set toValidate); - - /** - * @return A hashmap containing all plot clusters - */ - HashMap> getClusters(); - - /** - * Set the merged status for a plot - * - * @param plot Plot Object - * @param merged boolean[] - */ - void setMerged(final Plot plot, final boolean[] merged); - - /** - * Swap the settings, helpers etc. of two plots - * @param p1 Plot1 - * @param p2 Plot2 - */ - void swapPlots(final Plot p1, final Plot p2); - - /** - * Set plot flags - * - * @param plot Plot Object - * @param flags flags to set (flag[]) - */ - void setFlags(final Plot plot, final Collection flags); - - /** - * Set cluster flags - * - * @param cluster PlotCluster Object - * @param flags flags to set (flag[]) - */ - void setFlags(final PlotCluster cluster, final Collection flags); - - /** - * Rename a cluster - */ - void setClusterName(final PlotCluster cluster, final String name); - - /** - * Set the plot alias - * - * @param plot Plot for which the alias should be set - * @param alias Plot Alias - */ - void setAlias(final Plot plot, final String alias); - - /** - * Purge a plot - * - * @param uniqueIds list of plot id (db) to be purged - */ - void purgeIds(final Set uniqueIds); - - /** - * Purge a whole world - * - * @param area World in which the plots should be purged - */ - void purge(final PlotArea area, final Set plotIds); - - /** - * Set Plot Home Position - * - * @param plot Plot Object - * @param position Plot Home Position - */ - void setPosition(final Plot plot, final String position); - - /** - * - * @param cluster - * @param position - */ - void setPosition(final PlotCluster cluster, final String position); - - /** - * @param plot Plot Object - * @param uuid Player that should be removed - */ - void removeTrusted(final Plot plot, final UUID uuid); - - /** - * @param cluster PlotCluster Object - * @param uuid Player that should be removed - */ - void removeHelper(final PlotCluster cluster, final UUID uuid); - - /** - * @param plot Plot Object - * @param uuid Player that should be removed - */ - void removeMember(final Plot plot, final UUID uuid); - - /** - * - * @param cluster - * @param uuid - */ - void removeInvited(final PlotCluster cluster, final UUID uuid); - - /** - * @param plot Plot Object - * @param uuid Player that should be removed - */ - void setTrusted(final Plot plot, final UUID uuid); - - /** - * @param cluster PlotCluster Object - * @param uuid Player that should be removed - */ - void setHelper(final PlotCluster cluster, final UUID uuid); - - /** - * @param plot Plot Object - * @param uuid Player that should be added - */ - void setMember(final Plot plot, final UUID uuid); - - /** - * - * @param cluster - * @param uuid - */ - void setInvited(final PlotCluster cluster, final UUID uuid); - - /** - * @param plot Plot Object - * @param uuid Player uuid - */ - void removeDenied(final Plot plot, final UUID uuid); - - /** - * @param plot Plot Object - * @param uuid Player uuid that should be added - */ - void setDenied(final Plot plot, final UUID uuid); - - /** - * Get Plots ratings - * - * @param plot Plot Object - * - * @return Plot Ratings (pre-calculated) - */ - HashMap getRatings(final Plot plot); - - /** - * Set a rating for a plot - * @param plot - * @param rater - * @param value - */ - void setRating(final Plot plot, final UUID rater, final int value); - - /** - * Remove a plot comment - * - * @param plot Plot Object - * @param comment Comment to remove - */ - void removeComment(final Plot plot, final PlotComment comment); - - /** - * Clear an inbox - * @param plot - * @param inbox - */ - void clearInbox(final Plot plot, final String inbox); - - /** - * Set a plot comment - * - * @param plot Plot Object - * @param comment Comment to add - */ - void setComment(final Plot plot, final PlotComment comment); - - /** - * Get Plot Comments - * - * @param plot Plot Object - * @return Plot Comments within the specified tier - */ - void getComments(final Plot plot, final String inbox, final RunnableVal> whenDone); - - void createPlotAndSettings(final Plot plot, final Runnable whenDone); - - void createCluster(final PlotCluster cluster); - - void resizeCluster(final PlotCluster current, PlotId min, PlotId max); - - void movePlot(final Plot originalPlot, final Plot newPlot); - - /** - * Replace a old uuid with a new one in the database
- * - Useful for replacing a few uuids (not the entire database)
- * - For entire conversion, the uuidconvert command scales better - * @param old - * @param now - */ - void replaceUUID(final UUID old, final UUID now); - - /** - * Don't fuck with this one, unless you enjoy it rough - */ - boolean deleteTables(); - - void close(); - - void replaceWorld(String oldWorld, String newWorld, PlotId min, PlotId max); -} +//////////////////////////////////////////////////////////////////////////////////////////////////// +// PlotSquared - A plot manager and world generator for the Bukkit API / +// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / +// / +// This program is free software; you can redistribute it and/or modify / +// it under the terms of the GNU General Public License as published by / +// the Free Software Foundation; either version 3 of the License, or / +// (at your option) any later version. / +// / +// This program is distributed in the hope that it will be useful, / +// but WITHOUT ANY WARRANTY; without even the implied warranty of / +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / +// GNU General Public License for more details. / +// / +// You should have received a copy of the GNU General Public License / +// along with this program; if not, write to the Free Software Foundation, / +// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / +// / +// You can contact us via: support@intellectualsites.com / +//////////////////////////////////////////////////////////////////////////////////////////////////// +package com.intellectualcrafters.plot.database; + +import com.intellectualcrafters.plot.flag.Flag; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotArea; +import com.intellectualcrafters.plot.object.PlotCluster; +import com.intellectualcrafters.plot.object.PlotId; +import com.intellectualcrafters.plot.object.RunnableVal; +import com.intellectualcrafters.plot.object.comment.PlotComment; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +/** + + + */ +public interface AbstractDB { + + /** + * The UUID that will count as everyone + */ + UUID everyone = UUID.fromString("1-1-3-3-7"); + + /** + * Set Plot owner + * + * @param plot Plot in which the owner should be set + * @param uuid The uuid of the new owner + */ + void setOwner(final Plot plot, final UUID uuid); + + /** + * Create all settings, and create default helpers, trusted + denied lists + * + * @param plots Plots for which the default table entries should be created + */ + void createPlotsAndData(final ArrayList plots, final Runnable whenDone); + + /** + * Create a plot + * + * @param plot That should be created + */ + void createPlot(final Plot plot); + + /** + * Create tables + * + * @throws SQLException If the database manager is unable to create the tables + */ + void createTables() throws Exception; + + /** + * Delete a plot + * + * @param plot Plot that should be deleted + */ + void delete(final Plot plot); + + void deleteSettings(Plot plot); + + void deleteHelpers(Plot plot); + + void deleteTrusted(Plot plot); + + void deleteDenied(Plot plot); + + void deleteComments(Plot plot); + + void deleteRatings(Plot plot); + + void delete(final PlotCluster cluster); + + void addPersistentMeta(UUID uuid, String key, byte[] meta, boolean delete); + + void removePersistentMeta(UUID uuid, String key); + + void getPersistentMeta(UUID uuid, RunnableVal> result); + + /** + * Create plot settings + * + * @param id Plot Entry ID + * @param plot Plot Object + */ + void createPlotSettings(final int id, final Plot plot); + + /** + * Get the table entry ID + * + * @param plot Plot Object + * + * @return Integer = Plot Entry Id + */ + int getId(final Plot plot); + + /** + * Get the id of a given plot cluster + * + * @param cluster PlotCluster Object + * + * @return Integer = Cluster Entry Id + */ + int getClusterId(final PlotCluster cluster); + + /** + * @return A linked hashmap containing all plots + */ + HashMap> getPlots(); + + /** + * + */ + void validateAllPlots(final Set toValidate); + + /** + * @return A hashmap containing all plot clusters + */ + HashMap> getClusters(); + + /** + * Set the merged status for a plot + * + * @param plot Plot Object + * @param merged boolean[] + */ + void setMerged(final Plot plot, final boolean[] merged); + + /** + * Swap the settings, helpers etc. of two plots + * @param p1 Plot1 + * @param p2 Plot2 + */ + void swapPlots(final Plot p1, final Plot p2); + + /** + * Set plot flags + * + * @param plot Plot Object + * @param flags flags to set (flag[]) + */ + void setFlags(final Plot plot, final Collection flags); + + /** + * Set cluster flags + * + * @param cluster PlotCluster Object + * @param flags flags to set (flag[]) + */ + void setFlags(final PlotCluster cluster, final Collection flags); + + /** + * Rename a cluster + */ + void setClusterName(final PlotCluster cluster, final String name); + + /** + * Set the plot alias + * + * @param plot Plot for which the alias should be set + * @param alias Plot Alias + */ + void setAlias(final Plot plot, final String alias); + + /** + * Purge a plot + * + * @param uniqueIds list of plot id (db) to be purged + */ + void purgeIds(final Set uniqueIds); + + /** + * Purge a whole world + * + * @param area World in which the plots should be purged + */ + void purge(final PlotArea area, final Set plotIds); + + /** + * Set Plot Home Position + * + * @param plot Plot Object + * @param position Plot Home Position + */ + void setPosition(final Plot plot, final String position); + + /** + * + * @param cluster + * @param position + */ + void setPosition(final PlotCluster cluster, final String position); + + /** + * @param plot Plot Object + * @param uuid Player that should be removed + */ + void removeTrusted(final Plot plot, final UUID uuid); + + /** + * @param cluster PlotCluster Object + * @param uuid Player that should be removed + */ + void removeHelper(final PlotCluster cluster, final UUID uuid); + + /** + * @param plot Plot Object + * @param uuid Player that should be removed + */ + void removeMember(final Plot plot, final UUID uuid); + + /** + * + * @param cluster + * @param uuid + */ + void removeInvited(final PlotCluster cluster, final UUID uuid); + + /** + * @param plot Plot Object + * @param uuid Player that should be removed + */ + void setTrusted(final Plot plot, final UUID uuid); + + /** + * @param cluster PlotCluster Object + * @param uuid Player that should be removed + */ + void setHelper(final PlotCluster cluster, final UUID uuid); + + /** + * @param plot Plot Object + * @param uuid Player that should be added + */ + void setMember(final Plot plot, final UUID uuid); + + /** + * + * @param cluster + * @param uuid + */ + void setInvited(final PlotCluster cluster, final UUID uuid); + + /** + * @param plot Plot Object + * @param uuid Player uuid + */ + void removeDenied(final Plot plot, final UUID uuid); + + /** + * @param plot Plot Object + * @param uuid Player uuid that should be added + */ + void setDenied(final Plot plot, final UUID uuid); + + /** + * Get Plots ratings + * + * @param plot Plot Object + * + * @return Plot Ratings (pre-calculated) + */ + HashMap getRatings(final Plot plot); + + /** + * Set a rating for a plot + * @param plot + * @param rater + * @param value + */ + void setRating(final Plot plot, final UUID rater, final int value); + + /** + * Remove a plot comment + * + * @param plot Plot Object + * @param comment Comment to remove + */ + void removeComment(final Plot plot, final PlotComment comment); + + /** + * Clear an inbox + * @param plot + * @param inbox + */ + void clearInbox(final Plot plot, final String inbox); + + /** + * Set a plot comment + * + * @param plot Plot Object + * @param comment Comment to add + */ + void setComment(final Plot plot, final PlotComment comment); + + /** + * Get Plot Comments + * + * @param plot Plot Object + * @return Plot Comments within the specified tier + */ + void getComments(final Plot plot, final String inbox, final RunnableVal> whenDone); + + void createPlotAndSettings(final Plot plot, final Runnable whenDone); + + void createCluster(final PlotCluster cluster); + + void resizeCluster(final PlotCluster current, PlotId min, PlotId max); + + void movePlot(final Plot originalPlot, final Plot newPlot); + + /** + * Replace a old uuid with a new one in the database
+ * - Useful for replacing a few uuids (not the entire database)
+ * - For entire conversion, the uuidconvert command scales better + * @param old + * @param now + */ + void replaceUUID(final UUID old, final UUID now); + + /** + * Don't fuck with this one, unless you enjoy it rough + */ + boolean deleteTables(); + + void close(); + + void replaceWorld(String oldWorld, String newWorld, PlotId min, PlotId max); +} diff --git a/src/main/java/com/intellectualcrafters/plot/database/DBFunc.java b/Core/src/main/java/com/intellectualcrafters/plot/database/DBFunc.java similarity index 96% rename from src/main/java/com/intellectualcrafters/plot/database/DBFunc.java rename to Core/src/main/java/com/intellectualcrafters/plot/database/DBFunc.java index c4448eacc..49c21ce9d 100644 --- a/src/main/java/com/intellectualcrafters/plot/database/DBFunc.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/database/DBFunc.java @@ -1,492 +1,492 @@ -//////////////////////////////////////////////////////////////////////////////////////////////////// -// PlotSquared - A plot manager and world generator for the Bukkit API / -// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / -// / -// This program is free software; you can redistribute it and/or modify / -// it under the terms of the GNU General Public License as published by / -// the Free Software Foundation; either version 3 of the License, or / -// (at your option) any later version. / -// / -// This program is distributed in the hope that it will be useful, / -// but WITHOUT ANY WARRANTY; without even the implied warranty of / -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / -// GNU General Public License for more details. / -// / -// You should have received a copy of the GNU General Public License / -// along with this program; if not, write to the Free Software Foundation, / -// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / -// / -// You can contact us via: support@intellectualsites.com / -//////////////////////////////////////////////////////////////////////////////////////////////////// -package com.intellectualcrafters.plot.database; - -import com.intellectualcrafters.plot.flag.Flag; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotCluster; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.object.comment.PlotComment; - -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Set; -import java.util.UUID; - -/** - * Database Functions - * - These functions do not update the local plot objects and only make changes to the DB - */ -public class DBFunc { - /** - * The "global" uuid - */ - public static final UUID everyone = UUID.fromString("1-1-3-3-7"); - /** - * Abstract Database Manager - */ - public static AbstractDB dbManager; - - public static void movePlot(final Plot originalPlot, final Plot newPlot) { - if ((originalPlot.temp == -1) || (newPlot.temp == -1)) { - return; - } - dbManager.movePlot(originalPlot, newPlot); - } - - public static void validatePlots(final Set plots) { - dbManager.validateAllPlots(plots); - } - - /** - * Check if a resultset contains a column - * @param r - * @param name - * @return - */ - public static boolean hasColumn(final ResultSet r, final String name) { - try { - final ResultSetMetaData meta = r.getMetaData(); - final int count = meta.getColumnCount(); - for (int x = 1; x <= count; x++) { - if (name.equals(meta.getColumnName(x))) { - return true; - } - } - return false; - } catch (final SQLException e) { - return false; - } - } - - /** - * Set the owner of a plot - * - * @param plot Plot Object - * @param uuid New Owner - */ - public static void setOwner(final Plot plot, final UUID uuid) { - if (plot.temp == -1) { - return; - } - dbManager.setOwner(plot, uuid); - } - - /** - * Create all settings + (trusted, denied, members) - * - * @param plots List containing all plot objects - */ - public static void createPlotsAndData(final ArrayList plots, final Runnable whenDone) { - dbManager.createPlotsAndData(plots, whenDone); - } - - /** - * Create a plot - * - * @param plot Plot to create - */ - public static void createPlot(final Plot plot) { - if (plot.temp == -1) { - return; - } - dbManager.createPlot(plot); - } - - /** - * Create a plot - * - * @param plot Plot to create - */ - public static void createPlotAndSettings(final Plot plot, final Runnable whenDone) { - if (plot.temp == -1) { - return; - } - dbManager.createPlotAndSettings(plot, whenDone); - } - - /** - * Create tables - * - * @throws Exception - */ - public static void createTables(final String database) throws Exception { - dbManager.createTables(); - } - - /** - * Delete a plot - * - * @param plot Plot to delete - */ - public static void delete(final Plot plot) { - if (plot.temp == -1) { - return; - } - dbManager.delete(plot); - plot.temp = -1; - } - - /** - * Delete the ratings for a plot - * @param plot - */ - public static void deleteRatings(final Plot plot) { - if (plot.temp == -1) { - return; - } - dbManager.deleteRatings(plot); - } - - /** - * Delete the trusted list for a plot - * @param plot - */ - public static void deleteTrusted(final Plot plot) { - if (plot.temp == -1) { - return; - } - dbManager.deleteHelpers(plot); - } - - /** - * Delete the members list for a plot - * @param plot - */ - public static void deleteMembers(final Plot plot) { - if (plot.temp == -1) { - return; - } - dbManager.deleteTrusted(plot); - } - - /** - * Delete the denied list for a plot - * @param plot - */ - public static void deleteDenied(final Plot plot) { - if (plot.temp == -1) { - return; - } - dbManager.deleteDenied(plot); - } - - /** - * Delete the comments in a plot - * @param plot - */ - public static void deleteComments(final Plot plot) { - if (plot.temp == -1) { - return; - } - dbManager.deleteComments(plot); - } - - /** - * Deleting settings will - * 1) Delete any settings (flags and such) associated with the plot - * 2) Prevent any local changes to the plot from saving properly to the db - * - * This shouldn't ever be needed - * @param plot - */ - public static void deleteSettings(final Plot plot) { - if (plot.temp == -1) { - return; - } - dbManager.deleteSettings(plot); - } - - public static void delete(final PlotCluster toDelete) { - dbManager.delete(toDelete); - } - - /** - * Create plot settings - * - * @param id Plot ID - * @param plot Plot Object - */ - public static void createPlotSettings(final int id, final Plot plot) { - if (plot.temp == -1) { - return; - } - dbManager.createPlotSettings(id, plot); - } - - /** - * Get a plot id - * - * @param plot Plot Object - * - * @return ID - */ - public static int getId(final Plot plot) { - return dbManager.getId(plot); - } - - /** - * @return Plots - */ - public static HashMap> getPlots() { - return dbManager.getPlots(); - } - - public static void setMerged(final Plot plot, final boolean[] merged) { - if (plot.temp == -1) { - return; - } - dbManager.setMerged(plot, merged); - } - - public static void setFlags(final Plot plot, final Collection flags) { - if (plot.temp == -1) { - return; - } - dbManager.setFlags(plot, flags); - } - - public static void setFlags(final PlotCluster cluster, final Collection flags) { - dbManager.setFlags(cluster, flags); - } - - /** - * @param plot - * @param alias - */ - public static void setAlias(final Plot plot, final String alias) { - if (plot.temp == -1) { - return; - } - dbManager.setAlias(plot, alias); - } - - public static void purgeIds(final Set uniqueIds) { - dbManager.purgeIds(uniqueIds); - } - - public static void purge(final PlotArea area, final Set plotIds) { - dbManager.purge(area, plotIds); - } - - /** - * @param plot - * @param position - */ - public static void setPosition(final Plot plot, final String position) { - if (plot.temp == -1) { - return; - } - dbManager.setPosition(plot, position); - } - - /** - * @param plot - * @param comment - */ - public static void removeComment(final Plot plot, final PlotComment comment) { - if ((plot != null) && (plot.temp == -1)) { - return; - } - dbManager.removeComment(plot, comment); - } - - public static void clearInbox(final Plot plot, final String inbox) { - if ((plot != null) && (plot.temp == -1)) { - return; - } - dbManager.clearInbox(plot, inbox); - } - - /** - * @param plot - * @param comment - */ - public static void setComment(final Plot plot, final PlotComment comment) { - if ((plot != null) && (plot.temp == -1)) { - return; - } - dbManager.setComment(plot, comment); - } - - /** - * @param plot - */ - public static void getComments(final Plot plot, final String inbox, final RunnableVal> whenDone) { - if ((plot != null) && (plot.temp == -1)) { - return; - } - dbManager.getComments(plot, inbox, whenDone); - } - - /** - * @param plot - * @param uuid - */ - public static void removeTrusted(final Plot plot, final UUID uuid) { - if (plot.temp == -1) { - return; - } - dbManager.removeTrusted(plot, uuid); - } - - /** - * @param cluster - * @param uuid - */ - public static void removeHelper(final PlotCluster cluster, final UUID uuid) { - dbManager.removeHelper(cluster, uuid); - } - - /** - * @param cluster - */ - public static void createCluster(final PlotCluster cluster) { - dbManager.createCluster(cluster); - } - - /** - * @param current - * @param min - * @param max - */ - public static void resizeCluster(final PlotCluster current, final PlotId min, PlotId max) { - dbManager.resizeCluster(current, min, max); - } - - /** - * @param plot - * @param uuid - */ - public static void removeMember(final Plot plot, final UUID uuid) { - if (plot.temp == -1) { - return; - } - dbManager.removeMember(plot, uuid); - } - - /** - * - * @param cluster - * @param uuid - */ - public static void removeInvited(final PlotCluster cluster, final UUID uuid) { - dbManager.removeInvited(cluster, uuid); - } - - /** - * @param plot - * @param uuid - */ - public static void setTrusted(final Plot plot, final UUID uuid) { - if (plot.temp == -1) { - return; - } - dbManager.setTrusted(plot, uuid); - } - - public static void setHelper(final PlotCluster cluster, final UUID uuid) { - dbManager.setHelper(cluster, uuid); - } - - /** - * @param plot - * @param uuid - */ - public static void setMember(final Plot plot, final UUID uuid) { - if (plot.temp == -1) { - return; - } - dbManager.setMember(plot, uuid); - } - - public static void setInvited(final PlotCluster cluster, final UUID uuid) { - dbManager.setInvited(cluster, uuid); - } - - /** - * @param plot - * @param uuid - */ - public static void removeDenied(final Plot plot, final UUID uuid) { - if (plot.temp == -1) { - return; - } - dbManager.removeDenied(plot, uuid); - } - - /** - * @param plot - * @param uuid - */ - public static void setDenied(final Plot plot, final UUID uuid) { - if (plot.temp == -1) { - return; - } - dbManager.setDenied(plot, uuid); - } - - public static HashMap getRatings(final Plot plot) { - if (plot.temp == -1) { - return new HashMap<>(0); - } - return dbManager.getRatings(plot); - } - - public static void setRating(final Plot plot, final UUID rater, final int value) { - if (plot.temp == -1) { - return; - } - dbManager.setRating(plot, rater, value); - } - - public static HashMap> getClusters() { - return dbManager.getClusters(); - } - - public static void setPosition(final PlotCluster cluster, final String position) { - dbManager.setPosition(cluster, position); - } - - public static void replaceWorld(String oldWorld, String newWorld, PlotId min, PlotId max) { - dbManager.replaceWorld(oldWorld, newWorld, min, max); - } - - /** - * Replace all occurrences of a uuid in the database with another one - * @param old - * @param now - */ - public static void replaceUUID(final UUID old, final UUID now) { - dbManager.replaceUUID(old, now); - } - - public static void close() { - dbManager.close(); - } -} +//////////////////////////////////////////////////////////////////////////////////////////////////// +// PlotSquared - A plot manager and world generator for the Bukkit API / +// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / +// / +// This program is free software; you can redistribute it and/or modify / +// it under the terms of the GNU General Public License as published by / +// the Free Software Foundation; either version 3 of the License, or / +// (at your option) any later version. / +// / +// This program is distributed in the hope that it will be useful, / +// but WITHOUT ANY WARRANTY; without even the implied warranty of / +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / +// GNU General Public License for more details. / +// / +// You should have received a copy of the GNU General Public License / +// along with this program; if not, write to the Free Software Foundation, / +// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / +// / +// You can contact us via: support@intellectualsites.com / +//////////////////////////////////////////////////////////////////////////////////////////////////// +package com.intellectualcrafters.plot.database; + +import com.intellectualcrafters.plot.flag.Flag; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotArea; +import com.intellectualcrafters.plot.object.PlotCluster; +import com.intellectualcrafters.plot.object.PlotId; +import com.intellectualcrafters.plot.object.RunnableVal; +import com.intellectualcrafters.plot.object.comment.PlotComment; + +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Set; +import java.util.UUID; + +/** + * Database Functions + * - These functions do not update the local plot objects and only make changes to the DB + */ +public class DBFunc { + /** + * The "global" uuid + */ + public static final UUID everyone = UUID.fromString("1-1-3-3-7"); + /** + * Abstract Database Manager + */ + public static AbstractDB dbManager; + + public static void movePlot(final Plot originalPlot, final Plot newPlot) { + if ((originalPlot.temp == -1) || (newPlot.temp == -1)) { + return; + } + dbManager.movePlot(originalPlot, newPlot); + } + + public static void validatePlots(final Set plots) { + dbManager.validateAllPlots(plots); + } + + /** + * Check if a resultset contains a column + * @param r + * @param name + * @return + */ + public static boolean hasColumn(final ResultSet r, final String name) { + try { + final ResultSetMetaData meta = r.getMetaData(); + final int count = meta.getColumnCount(); + for (int x = 1; x <= count; x++) { + if (name.equals(meta.getColumnName(x))) { + return true; + } + } + return false; + } catch (final SQLException e) { + return false; + } + } + + /** + * Set the owner of a plot + * + * @param plot Plot Object + * @param uuid New Owner + */ + public static void setOwner(final Plot plot, final UUID uuid) { + if (plot.temp == -1) { + return; + } + dbManager.setOwner(plot, uuid); + } + + /** + * Create all settings + (trusted, denied, members) + * + * @param plots List containing all plot objects + */ + public static void createPlotsAndData(final ArrayList plots, final Runnable whenDone) { + dbManager.createPlotsAndData(plots, whenDone); + } + + /** + * Create a plot + * + * @param plot Plot to create + */ + public static void createPlot(final Plot plot) { + if (plot.temp == -1) { + return; + } + dbManager.createPlot(plot); + } + + /** + * Create a plot + * + * @param plot Plot to create + */ + public static void createPlotAndSettings(final Plot plot, final Runnable whenDone) { + if (plot.temp == -1) { + return; + } + dbManager.createPlotAndSettings(plot, whenDone); + } + + /** + * Create tables + * + * @throws Exception + */ + public static void createTables(final String database) throws Exception { + dbManager.createTables(); + } + + /** + * Delete a plot + * + * @param plot Plot to delete + */ + public static void delete(final Plot plot) { + if (plot.temp == -1) { + return; + } + dbManager.delete(plot); + plot.temp = -1; + } + + /** + * Delete the ratings for a plot + * @param plot + */ + public static void deleteRatings(final Plot plot) { + if (plot.temp == -1) { + return; + } + dbManager.deleteRatings(plot); + } + + /** + * Delete the trusted list for a plot + * @param plot + */ + public static void deleteTrusted(final Plot plot) { + if (plot.temp == -1) { + return; + } + dbManager.deleteHelpers(plot); + } + + /** + * Delete the members list for a plot + * @param plot + */ + public static void deleteMembers(final Plot plot) { + if (plot.temp == -1) { + return; + } + dbManager.deleteTrusted(plot); + } + + /** + * Delete the denied list for a plot + * @param plot + */ + public static void deleteDenied(final Plot plot) { + if (plot.temp == -1) { + return; + } + dbManager.deleteDenied(plot); + } + + /** + * Delete the comments in a plot + * @param plot + */ + public static void deleteComments(final Plot plot) { + if (plot.temp == -1) { + return; + } + dbManager.deleteComments(plot); + } + + /** + * Deleting settings will + * 1) Delete any settings (flags and such) associated with the plot + * 2) Prevent any local changes to the plot from saving properly to the db + * + * This shouldn't ever be needed + * @param plot + */ + public static void deleteSettings(final Plot plot) { + if (plot.temp == -1) { + return; + } + dbManager.deleteSettings(plot); + } + + public static void delete(final PlotCluster toDelete) { + dbManager.delete(toDelete); + } + + /** + * Create plot settings + * + * @param id Plot ID + * @param plot Plot Object + */ + public static void createPlotSettings(final int id, final Plot plot) { + if (plot.temp == -1) { + return; + } + dbManager.createPlotSettings(id, plot); + } + + /** + * Get a plot id + * + * @param plot Plot Object + * + * @return ID + */ + public static int getId(final Plot plot) { + return dbManager.getId(plot); + } + + /** + * @return Plots + */ + public static HashMap> getPlots() { + return dbManager.getPlots(); + } + + public static void setMerged(final Plot plot, final boolean[] merged) { + if (plot.temp == -1) { + return; + } + dbManager.setMerged(plot, merged); + } + + public static void setFlags(final Plot plot, final Collection flags) { + if (plot.temp == -1) { + return; + } + dbManager.setFlags(plot, flags); + } + + public static void setFlags(final PlotCluster cluster, final Collection flags) { + dbManager.setFlags(cluster, flags); + } + + /** + * @param plot + * @param alias + */ + public static void setAlias(final Plot plot, final String alias) { + if (plot.temp == -1) { + return; + } + dbManager.setAlias(plot, alias); + } + + public static void purgeIds(final Set uniqueIds) { + dbManager.purgeIds(uniqueIds); + } + + public static void purge(final PlotArea area, final Set plotIds) { + dbManager.purge(area, plotIds); + } + + /** + * @param plot + * @param position + */ + public static void setPosition(final Plot plot, final String position) { + if (plot.temp == -1) { + return; + } + dbManager.setPosition(plot, position); + } + + /** + * @param plot + * @param comment + */ + public static void removeComment(final Plot plot, final PlotComment comment) { + if ((plot != null) && (plot.temp == -1)) { + return; + } + dbManager.removeComment(plot, comment); + } + + public static void clearInbox(final Plot plot, final String inbox) { + if ((plot != null) && (plot.temp == -1)) { + return; + } + dbManager.clearInbox(plot, inbox); + } + + /** + * @param plot + * @param comment + */ + public static void setComment(final Plot plot, final PlotComment comment) { + if ((plot != null) && (plot.temp == -1)) { + return; + } + dbManager.setComment(plot, comment); + } + + /** + * @param plot + */ + public static void getComments(final Plot plot, final String inbox, final RunnableVal> whenDone) { + if ((plot != null) && (plot.temp == -1)) { + return; + } + dbManager.getComments(plot, inbox, whenDone); + } + + /** + * @param plot + * @param uuid + */ + public static void removeTrusted(final Plot plot, final UUID uuid) { + if (plot.temp == -1) { + return; + } + dbManager.removeTrusted(plot, uuid); + } + + /** + * @param cluster + * @param uuid + */ + public static void removeHelper(final PlotCluster cluster, final UUID uuid) { + dbManager.removeHelper(cluster, uuid); + } + + /** + * @param cluster + */ + public static void createCluster(final PlotCluster cluster) { + dbManager.createCluster(cluster); + } + + /** + * @param current + * @param min + * @param max + */ + public static void resizeCluster(final PlotCluster current, final PlotId min, PlotId max) { + dbManager.resizeCluster(current, min, max); + } + + /** + * @param plot + * @param uuid + */ + public static void removeMember(final Plot plot, final UUID uuid) { + if (plot.temp == -1) { + return; + } + dbManager.removeMember(plot, uuid); + } + + /** + * + * @param cluster + * @param uuid + */ + public static void removeInvited(final PlotCluster cluster, final UUID uuid) { + dbManager.removeInvited(cluster, uuid); + } + + /** + * @param plot + * @param uuid + */ + public static void setTrusted(final Plot plot, final UUID uuid) { + if (plot.temp == -1) { + return; + } + dbManager.setTrusted(plot, uuid); + } + + public static void setHelper(final PlotCluster cluster, final UUID uuid) { + dbManager.setHelper(cluster, uuid); + } + + /** + * @param plot + * @param uuid + */ + public static void setMember(final Plot plot, final UUID uuid) { + if (plot.temp == -1) { + return; + } + dbManager.setMember(plot, uuid); + } + + public static void setInvited(final PlotCluster cluster, final UUID uuid) { + dbManager.setInvited(cluster, uuid); + } + + /** + * @param plot + * @param uuid + */ + public static void removeDenied(final Plot plot, final UUID uuid) { + if (plot.temp == -1) { + return; + } + dbManager.removeDenied(plot, uuid); + } + + /** + * @param plot + * @param uuid + */ + public static void setDenied(final Plot plot, final UUID uuid) { + if (plot.temp == -1) { + return; + } + dbManager.setDenied(plot, uuid); + } + + public static HashMap getRatings(final Plot plot) { + if (plot.temp == -1) { + return new HashMap<>(0); + } + return dbManager.getRatings(plot); + } + + public static void setRating(final Plot plot, final UUID rater, final int value) { + if (plot.temp == -1) { + return; + } + dbManager.setRating(plot, rater, value); + } + + public static HashMap> getClusters() { + return dbManager.getClusters(); + } + + public static void setPosition(final PlotCluster cluster, final String position) { + dbManager.setPosition(cluster, position); + } + + public static void replaceWorld(String oldWorld, String newWorld, PlotId min, PlotId max) { + dbManager.replaceWorld(oldWorld, newWorld, min, max); + } + + /** + * Replace all occurrences of a uuid in the database with another one + * @param old + * @param now + */ + public static void replaceUUID(final UUID old, final UUID now) { + dbManager.replaceUUID(old, now); + } + + public static void close() { + dbManager.close(); + } +} diff --git a/src/main/java/com/intellectualcrafters/plot/database/Database.java b/Core/src/main/java/com/intellectualcrafters/plot/database/Database.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/database/Database.java rename to Core/src/main/java/com/intellectualcrafters/plot/database/Database.java diff --git a/src/main/java/com/intellectualcrafters/plot/database/MySQL.java b/Core/src/main/java/com/intellectualcrafters/plot/database/MySQL.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/database/MySQL.java rename to Core/src/main/java/com/intellectualcrafters/plot/database/MySQL.java diff --git a/src/main/java/com/intellectualcrafters/plot/database/SQLManager.java b/Core/src/main/java/com/intellectualcrafters/plot/database/SQLManager.java similarity index 97% rename from src/main/java/com/intellectualcrafters/plot/database/SQLManager.java rename to Core/src/main/java/com/intellectualcrafters/plot/database/SQLManager.java index 9576db609..f2fa954b2 100644 --- a/src/main/java/com/intellectualcrafters/plot/database/SQLManager.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/database/SQLManager.java @@ -1,3172 +1,3172 @@ -//////////////////////////////////////////////////////////////////////////////////////////////////// -// PlotSquared - A plot manager and world generator for the Bukkit API / -// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / -// / -// This program is free software; you can redistribute it and/or modify / -// it under the terms of the GNU General Public License as published by / -// the Free Software Foundation; either version 3 of the License, or / -// (at your option) any later version. / -// / -// This program is distributed in the hope that it will be useful, / -// but WITHOUT ANY WARRANTY; without even the implied warranty of / -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / -// GNU General Public License for more details. / -// / -// You should have received a copy of the GNU General Public License / -// along with this program; if not, write to the Free Software Foundation, / -// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / -// / -// You can contact us via: support@intellectualsites.com / -//////////////////////////////////////////////////////////////////////////////////////////////////// -package com.intellectualcrafters.plot.database; - -import com.intellectualcrafters.configuration.ConfigurationSection; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.flag.Flag; -import com.intellectualcrafters.plot.flag.FlagManager; -import com.intellectualcrafters.plot.object.BlockLoc; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotCluster; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotSettings; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.object.comment.PlotComment; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.StringMan; -import com.intellectualcrafters.plot.util.TaskManager; - -import java.sql.Blob; -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Queue; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.atomic.AtomicInteger; - -/** - - */ -public class SQLManager implements AbstractDB { - // Public final - public final String SET_OWNER; - public final String GET_ALL_PLOTS; - public final String CREATE_PLOTS; - public final String CREATE_SETTINGS; - public final String CREATE_TIERS; - public final String CREATE_PLOT; - public final String CREATE_CLUSTER; - private final String prefix; - // Private Final - private final Database database; - private final boolean MYSQL; - /** - * important tasks - */ - public volatile Queue globalTasks; - /** - * Notify tasks - */ - public volatile Queue notifyTasks; - /** - * plot - * plot_denied - * plot_helpers - * plot_trusted - * plot_comments - * plot_settings - * plot_rating - */ - public volatile ConcurrentHashMap> plotTasks; - /** - * player_meta - */ - public volatile ConcurrentHashMap> playerTasks; - /** - * cluster - * cluster_helpers - * cluster_invited - * cluster_settings - */ - public volatile ConcurrentHashMap> clusterTasks; - // Private - private Connection connection; - private boolean CLOSED = false; - - /** - * Constructor - * - * @param database - * @param p prefix - * @throws SQLException - * @throws ClassNotFoundException - */ - public SQLManager(final Database database, final String p, final boolean debug) throws SQLException, ClassNotFoundException { - // Private final - this.database = database; - connection = database.openConnection(); - MYSQL = database instanceof MySQL; - globalTasks = new ConcurrentLinkedQueue<>(); - notifyTasks = new ConcurrentLinkedQueue<>(); - plotTasks = new ConcurrentHashMap<>(); - playerTasks = new ConcurrentHashMap<>(); - clusterTasks = new ConcurrentHashMap<>(); - TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { - long last = System.currentTimeMillis(); - while (true) { - if (CLOSED) { - break; - } - // schedule reconnect - if (MYSQL && ((System.currentTimeMillis() - last) > 550000)) { - last = System.currentTimeMillis(); - try { - close(); - CLOSED = false; - connection = database.forceConnection(); - } catch (SQLException | ClassNotFoundException e) { - e.printStackTrace(); - } - } - if (!sendBatch()) { - try { - if (!getNotifyTasks().isEmpty()) { - for (final Runnable task : getNotifyTasks()) { - TaskManager.runTask(task); - } - getNotifyTasks().clear(); - } - Thread.sleep(50); - } catch (final InterruptedException e) { - e.printStackTrace(); - } - } - } - } - }); - prefix = p; - // Set timout - // setTimout(); - // Public final - SET_OWNER = "UPDATE `" + prefix + "plot` SET `owner` = ? WHERE `plot_id_x` = ? AND `plot_id_z` = ? AND `world` = ?"; - GET_ALL_PLOTS = "SELECT `id`, `plot_id_x`, `plot_id_z`, `world` FROM `" + prefix + "plot`"; - CREATE_PLOTS = "INSERT INTO `" + prefix + "plot`(`plot_id_x`, `plot_id_z`, `owner`, `world`, `timestamp`) values "; - CREATE_SETTINGS = "INSERT INTO `" + prefix + "plot_settings` (`plot_plot_id`) values "; - CREATE_TIERS = "INSERT INTO `" + prefix + "plot_%tier%` (`plot_plot_id`, `user_uuid`) values "; - CREATE_PLOT = "INSERT INTO `" + prefix + "plot`(`plot_id_x`, `plot_id_z`, `owner`, `world`, `timestamp`) VALUES(?, ?, ?, ?, ?)"; - CREATE_CLUSTER = "INSERT INTO `" + prefix + "cluster`(`pos1_x`, `pos1_z`, `pos2_x`, `pos2_z`, `owner`, `world`) VALUES(?, ?, ?, ?, ?, ?)"; - updateTables(); - createTables(); - } - - public synchronized Queue getGlobalTasks() { - return globalTasks; - } - - public synchronized Queue getNotifyTasks() { - return notifyTasks; - } - - public synchronized void addPlotTask(Plot plot, UniqueStatement task) { - if (plot == null) { - plot = new Plot(null, new PlotId(Integer.MAX_VALUE, Integer.MAX_VALUE)); - } - Queue tasks = plotTasks.get(plot); - if (tasks == null) { - tasks = new ConcurrentLinkedQueue<>(); - plotTasks.put(plot, tasks); - } - if (task == null) { - task = new UniqueStatement(plot.hashCode() + "") { - - @Override - public PreparedStatement get() { - return null; - } - - @Override - public void set(final PreparedStatement stmt) {} - - @Override - public void addBatch(final PreparedStatement stmt) {} - - @Override - public void execute(final PreparedStatement stmt) {} - - }; - } - tasks.add(task); - } - - public synchronized void addPlayerTask(UUID uuid, UniqueStatement task) { - if (uuid == null) { - return; - } - Queue tasks = playerTasks.get(uuid); - if (tasks == null) { - tasks = new ConcurrentLinkedQueue<>(); - playerTasks.put(uuid, tasks); - } - if (task == null) { - task = new UniqueStatement(uuid.hashCode() + "") { - - @Override - public PreparedStatement get() { - return null; - } - - @Override - public void set(final PreparedStatement stmt) {} - - @Override - public void addBatch(final PreparedStatement stmt) {} - - @Override - public void execute(final PreparedStatement stmt) {} - - }; - } - tasks.add(task); - } - - public synchronized void addClusterTask(final PlotCluster cluster, UniqueStatement task) { - Queue tasks = clusterTasks.get(cluster); - if (tasks == null) { - tasks = new ConcurrentLinkedQueue<>(); - clusterTasks.put(cluster, tasks); - } - if (task == null) { - task = new UniqueStatement(cluster.hashCode() + "") { - - @Override - public PreparedStatement get() { - return null; - } - - @Override - public void set(final PreparedStatement stmt) {} - - @Override - public void addBatch(final PreparedStatement stmt) {} - - @Override - public void execute(final PreparedStatement stmt) {} - - }; - } - tasks.add(task); - } - - public synchronized void addGlobalTask(final Runnable task) { - getGlobalTasks().add(task); - } - - public synchronized void addNotifyTask(final Runnable task) { - if (task != null) { - getNotifyTasks().add(task); - } - } - - public boolean sendBatch() { - try { - if (!getGlobalTasks().isEmpty()) { - if (connection.getAutoCommit()) { - connection.setAutoCommit(false); - } - final Runnable task = getGlobalTasks().remove(); - if (task != null) { - task.run(); - } - commit(); - return true; - } - int count = -1; - if (!plotTasks.isEmpty()) { - count = 0; - if (connection.getAutoCommit()) { - connection.setAutoCommit(false); - } - String method = null; - PreparedStatement stmt = null; - UniqueStatement task = null; - UniqueStatement lastTask = null; - for (final Entry> entry : plotTasks.entrySet()) { - final Plot plot = entry.getKey(); - if (plotTasks.get(plot).isEmpty()) { - plotTasks.remove(plot); - continue; - } - task = plotTasks.get(plot).remove(); - count++; - if (task != null) { - if (task._method == null || !task._method.equals(method)) { - if (stmt != null) { - lastTask.execute(stmt); - stmt.close(); - } - method = task._method; - stmt = task.get(); - } - task.set(stmt); - task.addBatch(stmt); - } - lastTask = task; - } - if (stmt != null && task != null) { - task.execute(stmt); - stmt.close(); - } - } - if (!playerTasks.isEmpty()) { - count = 0; - if (connection.getAutoCommit()) { - connection.setAutoCommit(false); - } - String method = null; - PreparedStatement stmt = null; - UniqueStatement task = null; - UniqueStatement lastTask = null; - for (final Entry> entry : playerTasks.entrySet()) { - final UUID uuid = entry.getKey(); - if (playerTasks.get(uuid).isEmpty()) { - playerTasks.remove(uuid); - continue; - } - task = playerTasks.get(uuid).remove(); - count++; - if (task != null) { - if (task._method == null || !task._method.equals(method)) { - if (stmt != null) { - lastTask.execute(stmt); - stmt.close(); - } - method = task._method; - stmt = task.get(); - } - task.set(stmt); - task.addBatch(stmt); - } - lastTask = task; - } - if (stmt != null && task != null) { - task.execute(stmt); - stmt.close(); - } - } - if (!clusterTasks.isEmpty()) { - count = 0; - if (connection.getAutoCommit()) { - connection.setAutoCommit(false); - } - String method = null; - PreparedStatement stmt = null; - UniqueStatement task = null; - UniqueStatement lastTask = null; - for (final Entry> entry : clusterTasks.entrySet()) { - final PlotCluster cluster = entry.getKey(); - if (clusterTasks.get(cluster).isEmpty()) { - clusterTasks.remove(cluster); - continue; - } - task = clusterTasks.get(cluster).remove(); - count++; - if (task != null) { - if (task._method == null || !task._method.equals(method)) { - if (stmt != null) { - lastTask.execute(stmt); - stmt.close(); - } - method = task._method; - stmt = task.get(); - } - task.set(stmt); - task.addBatch(stmt); - } - lastTask = task; - } - if (stmt != null && task != null) { - task.execute(stmt); - stmt.close(); - } - } - if (count > 0) { - commit(); - return true; - } else if (count != -1) { - if (!connection.getAutoCommit()) { - connection.setAutoCommit(true); - } - } - if (!clusterTasks.isEmpty()) { - clusterTasks.clear(); - } - if (!plotTasks.isEmpty()) { - plotTasks.clear(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - return false; - } - - public Connection getConnection() { - return connection; - } - - /** - * Set Plot owner - * - * @param plot Plot Object - * @param uuid Owner UUID - */ - @Override - public void setOwner(final Plot plot, final UUID uuid) { - addPlotTask(plot, new UniqueStatement("setOwner") { - @Override - public void set(final PreparedStatement statement) throws SQLException { - statement.setString(1, uuid.toString()); - statement.setInt(2, plot.getId().x); - statement.setInt(3, plot.getId().y); - statement.setString(4, plot.getArea().toString()); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement(SET_OWNER); - } - }); - } - - @Override - public void createPlotsAndData(final ArrayList myList, final Runnable whenDone) { - addGlobalTask(new Runnable() { - @Override - public void run() { - try { - // Create the plots - createPlots(myList, new Runnable() { - @Override - public void run() { - try { - // Creating datastructures - final HashMap plotMap = new HashMap<>(); - for (final Plot plot : myList) { - plotMap.put(plot.getId(), plot); - } - final ArrayList settings = new ArrayList<>(); - final ArrayList helpers = new ArrayList<>(); - final ArrayList trusted = new ArrayList<>(); - final ArrayList denied = new ArrayList<>(); - - // Populating structures - try (PreparedStatement stmt = connection.prepareStatement(GET_ALL_PLOTS); ResultSet result = stmt.executeQuery()) { - while (result.next()) { - final int id = result.getInt("id"); - final int x = result.getInt("plot_id_x"); - final int y = result.getInt("plot_id_z"); - final PlotId plotId = new PlotId(x, y); - final Plot plot = plotMap.get(plotId); - if (plot != null) { - settings.add(new SettingsPair(id, plot.getSettings())); - if (plot.getDenied() != null) { - for (final UUID uuid : plot.getDenied()) { - denied.add(new UUIDPair(id, uuid)); - } - } - if (plot.getMembers() != null) { - for (final UUID uuid : plot.getMembers()) { - trusted.add(new UUIDPair(id, uuid)); - } - } - if (plot.getTrusted() != null) { - for (final UUID uuid : plot.getTrusted()) { - helpers.add(new UUIDPair(id, uuid)); - } - } - } - } - } - createSettings(settings, new Runnable() { - @Override - public void run() { - createTiers(helpers, "helpers", new Runnable() { - @Override - public void run() { - createTiers(trusted, "trusted", new Runnable() { - @Override - public void run() { - createTiers(denied, "denied", new Runnable() { - @Override - public void run() { - try { - connection.commit(); - } catch (final SQLException e) { - e.printStackTrace(); - } - if (whenDone != null) { - whenDone.run(); - } - } - }); - } - }); - } - }); - } - }); - } catch (final SQLException e) { - e.printStackTrace(); - PS.debug("&7[WARN] " + "Failed to set all helpers for plots"); - try { - connection.commit(); - } catch (final SQLException e1) { - e1.printStackTrace(); - } - } - } - }); - } catch (final Exception e) { - e.printStackTrace(); - PS.debug("&7[WARN] " + "Failed to set all helpers for plots"); - try { - connection.commit(); - } catch (final SQLException e1) { - e1.printStackTrace(); - } - } - } - }); - } - - /** - * Create a plot - * - * @param myList list of plots to be created - */ - public void createTiers(final ArrayList myList, final String tier, final Runnable whenDone) { - final StmtMod mod = new StmtMod() { - @Override - public String getCreateMySQL(final int size) { - return getCreateMySQL(size, CREATE_TIERS.replaceAll("%tier%", tier), 2); - } - - @Override - public String getCreateSQLite(final int size) { - return getCreateSQLite(size, "INSERT INTO `" + prefix + "plot_" + tier + "` SELECT ? AS `plot_plot_id`, ? AS `user_uuid`", 2); - } - - @Override - public String getCreateSQL() { - return "INSERT INTO `" + prefix + "plot_" + tier + "` (`plot_plot_id`, `user_uuid`) VALUES(?,?)"; - } - - @Override - public void setMySQL(final PreparedStatement stmt, final int i, final UUIDPair pair) throws SQLException { - stmt.setInt((i * 2) + 1, pair.id); - stmt.setString((i * 2) + 2, pair.uuid.toString()); - } - - @Override - public void setSQLite(final PreparedStatement stmt, final int i, final UUIDPair pair) throws SQLException { - stmt.setInt((i * 2) + 1, pair.id); - stmt.setString((i * 2) + 2, pair.uuid.toString()); - } - - @Override - public void setSQL(final PreparedStatement stmt, final UUIDPair pair) throws SQLException { - stmt.setInt(1, pair.id); - stmt.setString(2, pair.uuid.toString()); - } - }; - setBulk(myList, mod, whenDone); - } - - /** - * Create a plot - * - * @param myList list of plots to be created - */ - public void createPlots(final ArrayList myList, final Runnable whenDone) { - final StmtMod mod = new StmtMod() { - @Override - public String getCreateMySQL(final int size) { - return getCreateMySQL(size, CREATE_PLOTS, 5); - } - - @Override - public String getCreateSQLite(final int size) { - return getCreateSQLite(size, "INSERT INTO `" + prefix - + "plot` SELECT ? AS `id`, ? AS `plot_id_x`, ? AS `plot_id_z`, ? AS `owner`, ? AS `world`, ? AS `timestamp` ", 6); - } - - @Override - public String getCreateSQL() { - return CREATE_PLOT; - } - - @Override - public void setMySQL(final PreparedStatement stmt, final int i, final Plot plot) throws SQLException { - stmt.setInt((i * 5) + 1, plot.getId().x); - stmt.setInt((i * 5) + 2, plot.getId().y); - try { - stmt.setString((i * 5) + 3, plot.owner.toString()); - } catch (SQLException e) { - stmt.setString((i * 5) + 3, everyone.toString()); - } - stmt.setString((i * 5) + 4, plot.getArea().toString()); - stmt.setTimestamp((i * 5) + 5, new Timestamp(plot.getTimestamp())); - } - - @Override - public void setSQLite(final PreparedStatement stmt, final int i, final Plot plot) throws SQLException { - stmt.setNull((i * 6) + 1, 4); - stmt.setInt((i * 6) + 2, plot.getId().x); - stmt.setInt((i * 6) + 3, plot.getId().y); - try { - stmt.setString((i * 6) + 4, plot.owner.toString()); - } catch (SQLException e1) { - stmt.setString((i * 6) + 4, everyone.toString()); - } - stmt.setString((i * 6) + 5, plot.getArea().toString()); - stmt.setTimestamp((i * 6) + 6, new Timestamp(plot.getTimestamp())); - } - - @Override - public void setSQL(final PreparedStatement stmt, final Plot plot) throws SQLException { - stmt.setInt(1, plot.getId().x); - stmt.setInt(2, plot.getId().y); - stmt.setString(3, plot.owner.toString()); - stmt.setString(4, plot.getArea().toString()); - stmt.setTimestamp(5, new Timestamp(plot.getTimestamp())); - - } - }; - setBulk(myList, mod, whenDone); - } - - public void setBulk(final ArrayList objList, final StmtMod mod, final Runnable whenDone) { - final int size = objList.size(); - if (size == 0) { - if (whenDone != null) { - whenDone.run(); - } - return; - } - int packet; - if (MYSQL) { - packet = Math.min(size, 5000); - } else { - packet = Math.min(size, 50); - } - final int amount = size / packet; - try { - int count = 0; - PreparedStatement preparedStmt = null; - int last = -1; - for (int j = 0; j <= amount; j++) { - final List subList = objList.subList(j * packet, Math.min(size, (j + 1) * packet)); - if (subList.isEmpty()) { - break; - } - String statement; - if (last == -1) { - last = subList.size(); - statement = mod.getCreateMySQL(subList.size()); - preparedStmt = connection.prepareStatement(statement); - } - if ((subList.size() != last) || (((count % 5000) == 0) && (count > 0))) { - preparedStmt.executeBatch(); - preparedStmt.close(); - statement = mod.getCreateMySQL(subList.size()); - preparedStmt = connection.prepareStatement(statement); - } - for (int i = 0; i < subList.size(); i++) { - count++; - final T obj = subList.get(i); - mod.setMySQL(preparedStmt, i, obj); - } - last = subList.size(); - preparedStmt.addBatch(); - } - PS.debug("&aBatch 1: " + count + " | " + objList.get(0).getClass().getCanonicalName()); - preparedStmt.executeBatch(); - preparedStmt.clearParameters(); - preparedStmt.close(); - if (whenDone != null) { - whenDone.run(); - } - return; - } catch (SQLException e) { - if (MYSQL) { - e.printStackTrace(); - PS.debug("&cERROR 1: " + " | " + objList.get(0).getClass().getCanonicalName()); - } - } - try { - int count = 0; - PreparedStatement preparedStmt = null; - int last = -1; - for (int j = 0; j <= amount; j++) { - final List subList = objList.subList(j * packet, Math.min(size, (j + 1) * packet)); - if (subList.isEmpty()) { - break; - } - String statement; - if (last == -1) { - last = subList.size(); - statement = mod.getCreateSQLite(subList.size()); - preparedStmt = connection.prepareStatement(statement); - } - if ((subList.size() != last) || (((count % 5000) == 0) && (count > 0))) { - preparedStmt.executeBatch(); - preparedStmt.clearParameters(); - statement = mod.getCreateSQLite(subList.size()); - preparedStmt = connection.prepareStatement(statement); - } - for (int i = 0; i < subList.size(); i++) { - count++; - final T obj = subList.get(i); - mod.setSQLite(preparedStmt, i, obj); - } - last = subList.size(); - preparedStmt.addBatch(); - } - PS.debug("&aBatch 2: " + count + " | " + objList.get(0).getClass().getCanonicalName()); - preparedStmt.executeBatch(); - preparedStmt.clearParameters(); - preparedStmt.close(); - } catch (SQLException e) { - e.printStackTrace(); - PS.debug("&cERROR 2: " + " | " + objList.get(0).getClass().getCanonicalName()); - PS.debug("&6[WARN] " + "Could not bulk save!"); - try { - final String nonBulk = mod.getCreateSQL(); - PreparedStatement preparedStmt = connection.prepareStatement(nonBulk); - for (final T obj : objList) { - try { - mod.setSQL(preparedStmt, obj); - preparedStmt.addBatch(); - } catch (SQLException e3) { - PS.debug("&c[ERROR] " + "Failed to save " + obj + "!"); - } - } - PS.debug("&aBatch 3"); - preparedStmt.executeBatch(); - preparedStmt.close(); - } catch (SQLException e3) { - e3.printStackTrace(); - PS.debug("&c[ERROR] " + "Failed to save all!"); - } - } - if (whenDone != null) { - whenDone.run(); - } - } - - public void createSettings(final ArrayList myList, final Runnable whenDone) { - final StmtMod mod = new StmtMod() { - @Override - public String getCreateMySQL(final int size) { - return getCreateMySQL(size, "INSERT INTO `" + prefix + "plot_settings`(`plot_plot_id`,`biome`,`rain`,`custom_time`,`time`,`deny_entry`,`alias`,`flags`,`merged`,`position`) VALUES ", - 10); - } - - @Override - public String getCreateSQLite(final int size) { - return getCreateSQLite( - size, - "INSERT INTO `" - + prefix - + "plot_settings` SELECT ? AS `plot_plot_id`, ? AS `biome`, ? AS `rain`, ? AS `custom_time`, ? AS `time`, ? AS `deny_entry`, ? AS `alias`, ? AS `flags`, ? AS `merged`, ? AS `position`", - 10); - } - - @Override - public String getCreateSQL() { - return "INSERT INTO `" + prefix + "plot_settings`(`plot_plot_id`) VALUES(?)"; - } - - @Override - public void setMySQL(final PreparedStatement stmt, final int i, final SettingsPair pair) throws SQLException { - stmt.setInt((i * 10) + 1, pair.id); // id - stmt.setNull((i * 10) + 2, 4); // biome - stmt.setNull((i * 10) + 3, 4); // rain - stmt.setNull((i * 10) + 4, 4); // custom_time - stmt.setNull((i * 10) + 5, 4); // time - stmt.setNull((i * 10) + 6, 4); // deny_entry - if (pair.settings.getAlias().equals("")) { - stmt.setNull((i * 10) + 7, 4); - } else { - stmt.setString((i * 10) + 7, pair.settings.getAlias()); - } - if (pair.settings.flags == null) { - stmt.setNull((i * 10) + 8, 4); - } else { - final StringBuilder flag_string = new StringBuilder(); - int k = 0; - for (final Flag flag : pair.settings.flags.values()) { - if (k != 0) { - flag_string.append(","); - } - flag_string.append(flag.getKey() + ":" + flag.getValueString().replaceAll(":", "\u00AF").replaceAll(",", "\u00B4")); - k++; - } - stmt.setString((i * 10) + 8, flag_string.toString()); - } - final boolean[] merged = pair.settings.getMerged(); - int hash = MainUtil.hash(merged); - stmt.setInt((i * 10) + 9, hash); - final BlockLoc loc = pair.settings.getPosition(); - String position; - if (loc.y == 0) { - position = "DEFAULT"; - } else { - position = loc.x + "," + loc.y + "," + loc.z; - } - stmt.setString((i * 10) + 10, position); - } - - @Override - public void setSQLite(final PreparedStatement stmt, final int i, final SettingsPair pair) throws SQLException { - stmt.setInt((i * 10) + 1, pair.id); // id - stmt.setNull((i * 10) + 2, 4); // biome - stmt.setNull((i * 10) + 3, 4); // rain - stmt.setNull((i * 10) + 4, 4); // custom_time - stmt.setNull((i * 10) + 5, 4); // time - stmt.setNull((i * 10) + 6, 4); // deny_entry - if (pair.settings.getAlias().equals("")) { - stmt.setNull((i * 10) + 7, 4); - } else { - stmt.setString((i * 10) + 7, pair.settings.getAlias()); - } - if (pair.settings.flags == null) { - stmt.setNull((i * 10) + 8, 4); - } else { - final StringBuilder flag_string = new StringBuilder(); - int k = 0; - for (final Flag flag : pair.settings.flags.values()) { - if (k != 0) { - flag_string.append(","); - } - flag_string.append(flag.getKey() + ":" + flag.getValueString().replaceAll(":", "\u00AF").replaceAll(",", "\u00B4")); - k++; - } - stmt.setString((i * 10) + 8, flag_string.toString()); - } - final boolean[] merged = pair.settings.getMerged(); - int n = 0; - for (int j = 0; j < 4; ++j) { - n = (n << 1) + (merged[j] ? 1 : 0); - } - stmt.setInt((i * 10) + 9, n); - final BlockLoc loc = pair.settings.getPosition(); - String position; - if (loc.y == 0) { - position = "DEFAULT"; - } else { - position = loc.x + "," + loc.y + "," + loc.z; - } - stmt.setString((i * 10) + 10, position); - } - - @Override - public void setSQL(final PreparedStatement stmt, final SettingsPair pair) throws SQLException { - stmt.setInt(1, pair.id); - } - }; - addGlobalTask(new Runnable() { - @Override - public void run() { - setBulk(myList, mod, whenDone); - } - }); - } - - public void createEmptySettings(final ArrayList myList, final Runnable whenDone) { - final StmtMod mod = new StmtMod() { - @Override - public String getCreateMySQL(final int size) { - return getCreateMySQL(size, CREATE_SETTINGS, 1); - } - - @Override - public String getCreateSQLite(final int size) { - return getCreateSQLite( - size, - "INSERT INTO `" - + prefix - + "plot_settings` SELECT ? AS `plot_plot_id`, ? AS `biome`, ? AS `rain`, ? AS `custom_time`, ? AS `time`, ? AS `deny_entry`, ? AS `alias`, ? AS `flags`, ? AS `merged`, ? AS `position` ", - 10); - } - - @Override - public String getCreateSQL() { - return "INSERT INTO `" + prefix + "plot_settings`(`plot_plot_id`) VALUES(?)"; - } - - @Override - public void setMySQL(final PreparedStatement stmt, final int i, final Integer id) throws SQLException { - stmt.setInt((i) + 1, id); - } - - @Override - public void setSQLite(final PreparedStatement stmt, final int i, final Integer id) throws SQLException { - stmt.setInt((i * 10) + 1, id); - stmt.setNull((i * 10) + 2, 4); - stmt.setNull((i * 10) + 3, 4); - stmt.setNull((i * 10) + 4, 4); - stmt.setNull((i * 10) + 5, 4); - stmt.setNull((i * 10) + 6, 4); - stmt.setNull((i * 10) + 7, 4); - stmt.setNull((i * 10) + 8, 4); - stmt.setNull((i * 10) + 9, 4); - stmt.setString((i * 10) + 10, "DEFAULT"); - } - - @Override - public void setSQL(final PreparedStatement stmt, final Integer id) throws SQLException { - stmt.setInt(1, id); - } - }; - addGlobalTask(new Runnable() { - @Override - public void run() { - setBulk(myList, mod, whenDone); - } - }); - } - - /** - * Create a plot - * - * @param plot - */ - @Override - public void createPlot(final Plot plot) { - addPlotTask(plot, new UniqueStatement("createPlot") { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - stmt.setInt(1, plot.getId().x); - stmt.setInt(2, plot.getId().y); - stmt.setString(3, plot.owner.toString()); - stmt.setString(4, plot.getArea().toString()); - stmt.setTimestamp(5, new Timestamp(plot.getTimestamp())); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement(CREATE_PLOT); - } - }); - } - - public void commit() { - try { - if (CLOSED) { - return; - } - if (!connection.getAutoCommit()) { - connection.commit(); - connection.setAutoCommit(true); - } - } catch (final SQLException e) { - e.printStackTrace(); - } - } - - @Override - public void createPlotAndSettings(final Plot plot, final Runnable whenDone) { - addPlotTask(plot, new UniqueStatement("createPlotAndSettings_" + plot.hashCode()) { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - stmt.setInt(1, plot.getId().x); - stmt.setInt(2, plot.getId().y); - stmt.setString(3, plot.owner.toString()); - stmt.setString(4, plot.getArea().toString()); - stmt.setTimestamp(5, new Timestamp(plot.getTimestamp())); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement(CREATE_PLOT, Statement.RETURN_GENERATED_KEYS); - } - - @Override - public void execute(final PreparedStatement stmt) { - - } - - @Override - public void addBatch(final PreparedStatement stmt) throws SQLException { - stmt.executeUpdate(); - final ResultSet keys = stmt.getGeneratedKeys(); - if (keys.next()) { - plot.temp = keys.getInt(1); - } - } - }); - addPlotTask(plot, new UniqueStatement("createPlotAndSettings_settings_" + plot.hashCode()) { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - stmt.setInt(1, getId(plot)); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("INSERT INTO `" + prefix + "plot_settings`(`plot_plot_id`) VALUES(" + "?)"); - } - }); - addNotifyTask(whenDone); - } - - /** - * Create tables - * - * @throws SQLException - */ - @Override - public void createTables() throws SQLException { - final String[] tables; - if (Settings.ENABLE_CLUSTERS) { - tables = new String[] { "plot", "plot_denied", "plot_helpers", "plot_comments", "plot_trusted", "plot_rating", "plot_settings", "cluster", "player_meta" }; - } else { - tables = new String[] { "plot", "plot_denied", "plot_helpers", "plot_comments", "plot_trusted", "plot_rating", "plot_settings", "player_meta" }; - } - final DatabaseMetaData meta = connection.getMetaData(); - int create = 0; - for (final String s : tables) { - final ResultSet set = meta.getTables(null, null, prefix + s, new String[] { "TABLE" }); - // ResultSet set = meta.getTables(null, null, prefix + s, null); - if (!set.next()) { - create++; - } - set.close(); - } - if (create == 0) { - return; - } - boolean add_constraint = create == tables.length; - PS.debug("Creating tables"); - final Statement stmt = connection.createStatement(); - if (MYSQL) { - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" - + prefix - + "plot` (" - + "`id` INT(11) NOT NULL AUTO_INCREMENT," - + "`plot_id_x` INT(11) NOT NULL," - + "`plot_id_z` INT(11) NOT NULL," - + "`owner` VARCHAR(40) NOT NULL," - + "`world` VARCHAR(45) NOT NULL," - + "`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP," - + "PRIMARY KEY (`id`)" - + ") ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=0"); - stmt - .addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "plot_denied` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" - + prefix - + "plot_helpers` (" - + "`plot_plot_id` INT(11) NOT NULL," - + "`user_uuid` VARCHAR(40) NOT NULL" - + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" - + prefix - + "plot_comments` (" - + "`world` VARCHAR(40) NOT NULL, `hashcode` INT(11) NOT NULL," - + "`comment` VARCHAR(40) NOT NULL," - + "`inbox` VARCHAR(40) NOT NULL," - + "`timestamp` INT(11) NOT NULL," - + "`sender` VARCHAR(40) NOT NULL" - + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" - + prefix - + "plot_trusted` (" - + "`plot_plot_id` INT(11) NOT NULL," - + "`user_uuid` VARCHAR(40) NOT NULL" - + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" - + prefix - + "plot_settings` (" - + " `plot_plot_id` INT(11) NOT NULL," - + " `biome` VARCHAR(45) DEFAULT 'FOREST'," - + " `rain` INT(1) DEFAULT 0," - + " `custom_time` TINYINT(1) DEFAULT '0'," - + " `time` INT(11) DEFAULT '8000'," - + " `deny_entry` TINYINT(1) DEFAULT '0'," - + " `alias` VARCHAR(50) DEFAULT NULL," - + " `flags` VARCHAR(512) DEFAULT NULL," - + " `merged` INT(11) DEFAULT NULL," - + " `position` VARCHAR(50) NOT NULL DEFAULT 'DEFAULT'," - + " PRIMARY KEY (`plot_plot_id`)," - + " UNIQUE KEY `unique_alias` (`alias`)" - + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" - + prefix - + "plot_rating` ( `plot_plot_id` INT(11) NOT NULL, `rating` INT(2) NOT NULL, `player` VARCHAR(40) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8"); - if (add_constraint) { - stmt.addBatch("ALTER TABLE `" - + prefix - + "plot_settings` ADD CONSTRAINT `" - + prefix - + "plot_settings_ibfk_1` FOREIGN KEY (`plot_plot_id`) REFERENCES `" - + prefix - + "plot` (`id`) ON DELETE CASCADE"); - } - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" - + prefix - + "cluster` (" - + "`id` INT(11) NOT NULL AUTO_INCREMENT," - + "`pos1_x` INT(11) NOT NULL," - + "`pos1_z` INT(11) NOT NULL," - + "`pos2_x` INT(11) NOT NULL," - + "`pos2_z` INT(11) NOT NULL," - + "`owner` VARCHAR(40) NOT NULL," - + "`world` VARCHAR(45) NOT NULL," - + "`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP," - + "PRIMARY KEY (`id`)" - + ") ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=0"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" - + prefix - + "cluster_helpers` (" - + "`cluster_id` INT(11) NOT NULL," - + "`user_uuid` VARCHAR(40) NOT NULL" - + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" - + prefix - + "cluster_invited` (" - + "`cluster_id` INT(11) NOT NULL," - + "`user_uuid` VARCHAR(40) NOT NULL" - + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" - + prefix - + "cluster_settings` (" - + " `cluster_id` INT(11) NOT NULL," - + " `biome` VARCHAR(45) DEFAULT 'FOREST'," - + " `rain` INT(1) DEFAULT 0," - + " `custom_time` TINYINT(1) DEFAULT '0'," - + " `time` INT(11) DEFAULT '8000'," - + " `deny_entry` TINYINT(1) DEFAULT '0'," - + " `alias` VARCHAR(50) DEFAULT NULL," - + " `flags` VARCHAR(512) DEFAULT NULL," - + " `merged` INT(11) DEFAULT NULL," - + " `position` VARCHAR(50) NOT NULL DEFAULT 'DEFAULT'," - + " PRIMARY KEY (`cluster_id`)" - + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" - + prefix - + "player_meta` (" - + " `meta_id` INT(11) NOT NULL AUTO_INCREMENT," - + " `uuid` VARCHAR(40) NOT NULL," - + " `key` VARCHAR(32) NOT NULL," - + " `value` blob NOT NULL," - + " PRIMARY KEY (`meta_id`)" - + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); - } else { - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" - + prefix - + "plot` (" - + "`id` INTEGER PRIMARY KEY AUTOINCREMENT," - + "`plot_id_x` INT(11) NOT NULL," - + "`plot_id_z` INT(11) NOT NULL," - + "`owner` VARCHAR(45) NOT NULL," - + "`world` VARCHAR(45) NOT NULL," - + "`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP)"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "plot_denied` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ")"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "plot_helpers` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ")"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "plot_trusted` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ")"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" - + prefix - + "plot_comments` (" - + "`world` VARCHAR(40) NOT NULL, `hashcode` INT(11) NOT NULL," - + "`comment` VARCHAR(40) NOT NULL," - + "`inbox` VARCHAR(40) NOT NULL, `timestamp` INT(11) NOT NULL," - + "`sender` VARCHAR(40) NOT NULL" - + ")"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" - + prefix - + "plot_settings` (" - + " `plot_plot_id` INT(11) NOT NULL," - + " `biome` VARCHAR(45) DEFAULT 'FOREST'," - + " `rain` INT(1) DEFAULT 0," - + " `custom_time` TINYINT(1) DEFAULT '0'," - + " `time` INT(11) DEFAULT '8000'," - + " `deny_entry` TINYINT(1) DEFAULT '0'," - + " `alias` VARCHAR(50) DEFAULT NULL," - + " `flags` VARCHAR(512) DEFAULT NULL," - + " `merged` INT(11) DEFAULT NULL," - + " `position` VARCHAR(50) NOT NULL DEFAULT 'DEFAULT'," - + " PRIMARY KEY (`plot_plot_id`)" - + ")"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "plot_rating` (`plot_plot_id` INT(11) NOT NULL, `rating` INT(2) NOT NULL, `player` VARCHAR(40) NOT NULL)"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" - + prefix - + "cluster` (" - + "`id` INTEGER PRIMARY KEY AUTOINCREMENT," - + "`pos1_x` INT(11) NOT NULL," - + "`pos1_z` INT(11) NOT NULL," - + "`pos2_x` INT(11) NOT NULL," - + "`pos2_z` INT(11) NOT NULL," - + "`owner` VARCHAR(40) NOT NULL," - + "`world` VARCHAR(45) NOT NULL," - + "`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP" - + ")"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "cluster_helpers` (" + "`cluster_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ")"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "cluster_invited` (" + "`cluster_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ")"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" - + prefix - + "cluster_settings` (" - + " `cluster_id` INT(11) NOT NULL," - + " `biome` VARCHAR(45) DEFAULT 'FOREST'," - + " `rain` INT(1) DEFAULT 0," - + " `custom_time` TINYINT(1) DEFAULT '0'," - + " `time` INT(11) DEFAULT '8000'," - + " `deny_entry` TINYINT(1) DEFAULT '0'," - + " `alias` VARCHAR(50) DEFAULT NULL," - + " `flags` VARCHAR(512) DEFAULT NULL," - + " `merged` INT(11) DEFAULT NULL," - + " `position` VARCHAR(50) NOT NULL DEFAULT 'DEFAULT'," - + " PRIMARY KEY (`cluster_id`)" - + ")"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `" - + prefix - + "player_meta` (" - + " `meta_id` INTEGER PRIMARY KEY AUTOINCREMENT," - + " `uuid` VARCHAR(40) NOT NULL," - + " `key` VARCHAR(32) NOT NULL," - + " `value` blob NOT NULL" - + ")"); - } - stmt.executeBatch(); - stmt.clearBatch(); - stmt.close(); - } - - @Override - public void deleteSettings(final Plot plot) { - if (plot.settings == null) { - return; - } - addPlotTask(plot, new UniqueStatement("delete_plot_settings") { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - stmt.setInt(1, getId(plot)); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("DELETE FROM `" + prefix + "plot_settings` WHERE `plot_plot_id` = ?"); - } - }); - } - - @Override - public void deleteHelpers(final Plot plot) { - if (plot.getTrusted().isEmpty()) { - return; - } - addPlotTask(plot, new UniqueStatement("delete_plot_helpers") { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - stmt.setInt(1, getId(plot)); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("DELETE FROM `" + prefix + "plot_helpers` WHERE `plot_plot_id` = ?"); - } - }); - } - - @Override - public void deleteTrusted(final Plot plot) { - if (plot.getMembers().isEmpty()) { - return; - } - addPlotTask(plot, new UniqueStatement("delete_plot_trusted") { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - stmt.setInt(1, getId(plot)); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("DELETE FROM `" + prefix + "plot_trusted` WHERE `plot_plot_id` = ?"); - } - }); - } - - @Override - public void deleteDenied(final Plot plot) { - if (plot.getDenied().isEmpty()) { - return; - } - addPlotTask(plot, new UniqueStatement("delete_plot_denied") { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - stmt.setInt(1, getId(plot)); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("DELETE FROM `" + prefix + "plot_denied` WHERE `plot_plot_id` = ?"); - } - }); - } - - @Override - public void deleteComments(final Plot plot) { - addPlotTask(plot, new UniqueStatement("delete_plot_comments") { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - stmt.setString(1, plot.getArea().toString()); - stmt.setInt(2, plot.hashCode()); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("DELETE FROM `" + prefix + "plot_comments` WHERE `world` = ? AND `hashcode` = ?"); - } - }); - } - - @Override - public void deleteRatings(final Plot plot) { - if (Settings.CACHE_RATINGS && plot.getSettings().getRatings().isEmpty()) { - return; - } - addPlotTask(plot, new UniqueStatement("delete_plot_ratings") { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - stmt.setInt(1, getId(plot)); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("DELETE FROM `" + prefix + "plot_rating` WHERE `plot_plot_id` = ?"); - } - }); - } - - /** - * Delete a plot - * - * @param plot - */ - @Override - public void delete(final Plot plot) { - deleteSettings(plot); - deleteDenied(plot); - deleteHelpers(plot); - deleteTrusted(plot); - deleteComments(plot); - deleteRatings(plot); - addPlotTask(plot, new UniqueStatement("delete_plot") { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - stmt.setInt(1, getId(plot)); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("DELETE FROM `" + prefix + "plot` WHERE `id` = ?"); - } - }); - } - - /** - * Create plot settings - * - * @param id - * @param plot - */ - @Override - public void createPlotSettings(final int id, final Plot plot) { - addPlotTask(plot, new UniqueStatement("createPlotSettings") { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - stmt.setInt(1, id); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("INSERT INTO `" + prefix + "plot_settings`(`plot_plot_id`) VALUES(" + "?)"); - } - }); - } - - @Override - public int getClusterId(final PlotCluster cluster) { - if (cluster.temp > 0) { - return cluster.temp; - } - try { - commit(); - if (cluster.temp > 0) { - return cluster.temp; - } - PreparedStatement stmt = connection.prepareStatement("SELECT `id` FROM `" - + prefix - + "cluster` WHERE `pos1_x` = ? AND `pos1_z` = ? AND `pos2_x` = ? AND `pos2_z` = ? AND `world` = ? ORDER BY `timestamp` ASC"); - stmt.setInt(1, cluster.getP1().x); - stmt.setInt(2, cluster.getP1().y); - stmt.setInt(3, cluster.getP2().x); - stmt.setInt(4, cluster.getP2().y); - stmt.setString(5, cluster.area.toString()); - final ResultSet r = stmt.executeQuery(); - int c_id = Integer.MAX_VALUE; - while (r.next()) { - c_id = r.getInt("id"); - } - stmt.close(); - r.close(); - if ((c_id == Integer.MAX_VALUE) || (c_id == 0)) { - if (cluster.temp > 0) { - return cluster.temp; - } - throw new SQLException("Cluster does not exist in database"); - } - cluster.temp = c_id; - return c_id; - } catch (final SQLException e) { - e.printStackTrace(); - } - return Integer.MAX_VALUE; - } - - @Override - public int getId(final Plot plot) { - if (plot.temp > 0) { - return plot.temp; - } - try { - commit(); - if (plot.temp > 0) { - return plot.temp; - } - PreparedStatement stmt = connection.prepareStatement( - "SELECT `id` FROM `" + prefix + "plot` WHERE `plot_id_x` = ? AND `plot_id_z` = ? AND world = ? ORDER BY `timestamp` ASC"); - stmt.setInt(1, plot.getId().x); - stmt.setInt(2, plot.getId().y); - stmt.setString(3, plot.getArea().toString()); - final ResultSet r = stmt.executeQuery(); - int id = Integer.MAX_VALUE; - while (r.next()) { - id = r.getInt("id"); - } - r.close(); - stmt.close(); - if ((id == Integer.MAX_VALUE) || (id == 0)) { - if (plot.temp > 0) { - return plot.temp; - } - throw new SQLException("Plot does not exist in database"); - } - plot.temp = id; - return id; - } catch (final SQLException e) { - e.printStackTrace(); - } - return Integer.MAX_VALUE; - } - - public void updateTables() { - if (PS.get().getVersion().equals(PS.get().getLastVersion()) || (PS.get().getLastVersion() == null)) { - return; - } - try { - final DatabaseMetaData data = connection.getMetaData(); - ResultSet rs = data.getColumns(null, null, prefix + "plot_comments", "plot_plot_id"); - if (rs.next()) { - rs.close(); - rs = data.getColumns(null, null, prefix + "plot_comments", "hashcode"); - if (!rs.next()) { - rs.close(); - try { - final Statement statement = connection.createStatement(); - statement.addBatch("DROP TABLE `" + prefix + "plot_comments`"); - if (Settings.DB.USE_MYSQL) { - statement.addBatch("CREATE TABLE IF NOT EXISTS `" - + prefix - + "plot_comments` (" - + "`world` VARCHAR(40) NOT NULL, `hashcode` INT(11) NOT NULL," - + "`comment` VARCHAR(40) NOT NULL," - + "`inbox` VARCHAR(40) NOT NULL," - + "`timestamp` INT(11) NOT NULL," - + "`sender` VARCHAR(40) NOT NULL" - + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); - } else { - statement.addBatch("CREATE TABLE IF NOT EXISTS `" - + prefix - + "plot_comments` (" - + "`world` VARCHAR(40) NOT NULL, `hashcode` INT(11) NOT NULL," - + "`comment` VARCHAR(40) NOT NULL," - + "`inbox` VARCHAR(40) NOT NULL, `timestamp` INT(11) NOT NULL," - + "`sender` VARCHAR(40) NOT NULL" - + ")"); - } - statement.executeBatch(); - statement.close(); - } catch (final SQLException e) { - final Statement statement = connection.createStatement(); - statement.addBatch("ALTER IGNORE TABLE `" + prefix + "plot_comments` ADD `inbox` VARCHAR(11) DEFAULT `public`"); - statement.addBatch("ALTER IGNORE TABLE `" + prefix + "plot_comments` ADD `timestamp` INT(11) DEFAULT 0"); - statement.addBatch("ALTER TABLE `" + prefix + "plot` DROP `tier`"); - statement.executeBatch(); - statement.close(); - } - } - } - rs.close(); - rs = data.getColumns(null, null, prefix + "plot_denied", "plot_plot_id"); - if (rs.next()) { - try (Statement statement = connection.createStatement()) { - statement.executeUpdate( - "DELETE FROM `" + prefix + "plot_denied` WHERE `plot_plot_id` NOT IN (SELECT `id` FROM `" + prefix + "plot`)"); - statement.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - - rs.close(); - try (Statement statement = connection.createStatement()) { - for (final String table : new String[]{"plot_denied", "plot_helpers", "plot_trusted"}) { - final ResultSet result = statement.executeQuery("SELECT plot_plot_id, user_uuid, COUNT(*) FROM " + prefix + table - + " GROUP BY plot_plot_id, user_uuid HAVING COUNT(*) > 1"); - if (result.next()) { - PS.debug("BACKING UP: " + prefix + table); - result.close(); - statement.executeUpdate("CREATE TABLE " + prefix + table + "_tmp AS SELECT * FROM " + prefix + table - + " GROUP BY plot_plot_id, user_uuid"); - statement.executeUpdate("DROP TABLE " + prefix + table); - statement.executeUpdate("CREATE TABLE " + prefix + table + " AS SELECT * FROM " + prefix + table + "_tmp"); - statement.executeUpdate("DROP TABLE " + prefix + table + "_tmp"); - PS.debug("RESTORING: " + prefix + table); - } - } - statement.close(); - } catch (SQLException e2) { - e2.printStackTrace(); - } - } - } catch (SQLException e) { - e.printStackTrace(); - } - - } - - public void deleteRows(final ArrayList rowIds, final String table, final String column) { - setBulk(rowIds, new StmtMod() { - - @Override - public String getCreateMySQL(int size) { - return getCreateMySQL(1, "DELETE FROM `" + table + "` WHERE `" + prefix + column + "` IN ", size); - } - - @Override - public String getCreateSQLite(int size) { - return getCreateMySQL(1, "DELETE FROM `" + table + "` WHERE `" + prefix + column + "` IN ", size); - } - - @Override - public String getCreateSQL() { - return "DELETE FROM `" + table + "` WHERE `" + prefix + column + "` = ?"; - } - - @Override - public void setMySQL(PreparedStatement stmt, int i, Integer obj) throws SQLException { - stmt.setInt((i) + 1, obj); - } - - @Override - public void setSQLite(PreparedStatement stmt, int i, Integer obj) throws SQLException { - stmt.setInt((i) + 1, obj); - } - - @Override - public void setSQL(PreparedStatement stmt, Integer obj) throws SQLException { - stmt.setInt(1, obj); - } - }, null); - } - - /** - * Load all plots, helpers, denied, trusted, and every setting from DB into a hashmap - */ - @Override - public HashMap> getPlots() { - final HashMap> newplots = new HashMap<>(); - final HashMap plots = new HashMap<>(); - try { - HashSet areas = new HashSet<>(); - if (PS.get().config.contains("worlds")) { - ConfigurationSection worldSection = PS.get().config.getConfigurationSection("worlds"); - if (worldSection != null) { - for (String worldKey : worldSection.getKeys(false)) { - areas.add(worldKey); - ConfigurationSection areaSection = worldSection.getConfigurationSection(worldKey + ".areas"); - if (areaSection != null) { - for (String areaKey : areaSection.getKeys(false)) { - String[] split = areaKey.split("-"); - if (split.length == 3) { - areas.add(worldKey + ";" + split[0]); - } - } - } - } - } - } - final HashMap uuids = new HashMap<>(); - final HashMap noExist = new HashMap<>(); - - /* - * Getting plots - */ - Statement stmt = connection.createStatement(); - int id; - String o; - UUID user; - try (ResultSet r = stmt.executeQuery("SELECT `id`, `plot_id_x`, `plot_id_z`, `owner`, `world`, `timestamp` FROM `" + prefix + "plot`")) { - ArrayList toDelete = new ArrayList<>(); - while (r.next()) { - PlotId plot_id = new PlotId(r.getInt("plot_id_x"), r.getInt("plot_id_z")); - id = r.getInt("id"); - final String areaid = r.getString("world"); - if (!areas.contains(areaid)) { - if (Settings.AUTO_PURGE) { - toDelete.add(id); - continue; - } else { - AtomicInteger value = noExist.get(areaid); - if (value != null) { - value.incrementAndGet(); - } else { - noExist.put(areaid, new AtomicInteger(1)); - } - } - } - o = r.getString("owner"); - user = uuids.get(o); - if (user == null) { - user = UUID.fromString(o); - uuids.put(o, user); - } - Timestamp timestamp = null; - try { - timestamp = r.getTimestamp("timestamp"); - } catch (SQLException ignored) { - } - long time; - if (timestamp == null) { - time = plot_id.hashCode(); - } else { - time = timestamp.getTime(); - } - Plot p = new Plot(plot_id, user, new HashSet(), new HashSet(), new HashSet(), "", null, null, null, - new boolean[]{false, false, false, false}, time, id); - HashMap map = newplots.get(areaid); - if (map != null) { - Plot last = map.put(p.getId(), p); - if (last != null) { - map.put(last.getId(), last); - if (Settings.AUTO_PURGE) { - toDelete.add(id); - } else { - PS.debug("&cPLOT " + id + " in `plot` is a duplicate. Delete this plot or set `auto-purge: true` in the settings.yml."); - } - continue; - } - } else { - map = new HashMap<>(); - newplots.put(areaid, map); - map.put(p.getId(), p); - } - plots.put(id, p); - } - deleteRows(toDelete, "plot", "id"); - } - if (Settings.CACHE_RATINGS) { - try (ResultSet r = stmt.executeQuery("SELECT `plot_plot_id`, `player`, `rating` FROM `" + prefix + "plot_rating`")) { - ArrayList toDelete = new ArrayList<>(); - while (r.next()) { - id = r.getInt("plot_plot_id"); - o = r.getString("player"); - user = uuids.get(o); - if (user == null) { - user = UUID.fromString(o); - uuids.put(o, user); - } - final Plot plot = plots.get(id); - if (plot != null) { - if (plot.getSettings().ratings == null) { - plot.getSettings().ratings = new HashMap<>(); - } - plot.getSettings().ratings.put(user, r.getInt("rating")); - } else if (Settings.AUTO_PURGE) { - toDelete.add(id); - } else { - PS.debug("&cENTRY " + id + " in `plot_rating` does not exist. Create this plot or set `auto-purge: true` in the settings.yml."); - } - } - deleteRows(toDelete, "plot_rating", "plot_plot_id"); - } - } - - /* - * Getting helpers - */ - try (ResultSet r = stmt.executeQuery("SELECT `user_uuid`, `plot_plot_id` FROM `" + prefix + "plot_helpers`")) { - ArrayList toDelete = new ArrayList<>(); - while (r.next()) { - id = r.getInt("plot_plot_id"); - o = r.getString("user_uuid"); - user = uuids.get(o); - if (user == null) { - user = UUID.fromString(o); - uuids.put(o, user); - } - final Plot plot = plots.get(id); - if (plot != null) { - plot.getTrusted().add(user); - } else if (Settings.AUTO_PURGE) { - toDelete.add(id); - } else { - PS.debug("&cENTRY " + id + " in `plot_helpers` does not exist. Create this plot or set `auto-purge: true` in the settings.yml."); - } - } - deleteRows(toDelete, "plot_helpers", "plot_plot_id"); - } - - /* - * Getting trusted - */ - try (ResultSet r = stmt.executeQuery("SELECT `user_uuid`, `plot_plot_id` FROM `" + prefix + "plot_trusted`")) { - ArrayList toDelete = new ArrayList<>(); - while (r.next()) { - id = r.getInt("plot_plot_id"); - o = r.getString("user_uuid"); - user = uuids.get(o); - if (user == null) { - user = UUID.fromString(o); - uuids.put(o, user); - } - final Plot plot = plots.get(id); - if (plot != null) { - plot.getMembers().add(user); - } else if (Settings.AUTO_PURGE) { - toDelete.add(id); - } else { - PS.debug("&cENTRY " + id + " in `plot_trusted` does not exist. Create this plot or set `auto-purge: true` in the settings.yml."); - } - } - deleteRows(toDelete, "plot_trusted", "plot_plot_id"); - } - - /* - * Getting denied - */ - try (ResultSet r = stmt.executeQuery("SELECT `user_uuid`, `plot_plot_id` FROM `" + prefix + "plot_denied`")) { - ArrayList toDelete = new ArrayList<>(); - while (r.next()) { - id = r.getInt("plot_plot_id"); - o = r.getString("user_uuid"); - user = uuids.get(o); - if (user == null) { - user = UUID.fromString(o); - uuids.put(o, user); - } - final Plot plot = plots.get(id); - if (plot != null) { - plot.getDenied().add(user); - } else if (Settings.AUTO_PURGE) { - toDelete.add(id); - } else { - PS.debug("&cENTRY " + id + " in `plot_denied` does not exist. Create this plot or set `auto-purge: true` in the settings.yml."); - } - } - deleteRows(toDelete, "plot_denied", "plot_plot_id"); - } - - try (ResultSet r = stmt.executeQuery("SELECT * FROM `" + prefix + "plot_settings`")) { - ArrayList toDelete = new ArrayList<>(); - while (r.next()) { - id = r.getInt("plot_plot_id"); - final Plot plot = plots.get(id); - if (plot != null) { - plots.remove(id); - final String alias = r.getString("alias"); - if (alias != null) { - plot.getSettings().setAlias(alias); - } - final String pos = r.getString("position"); - switch (pos.toLowerCase()) { - case "": - case "default": - case "0,0,0": - case "center": - break; - default: - try { - plot.getSettings().setPosition(BlockLoc.fromString(pos)); - } catch (final Exception ignored) {} - } - final Integer m = r.getInt("merged"); - final boolean[] merged = new boolean[4]; - for (int i = 0; i < 4; i++) { - merged[3 - i] = (m & (1 << i)) != 0; - } - plot.getSettings().setMerged(merged); - String[] flags_string; - final String myflags = r.getString("flags"); - if (myflags == null) { - flags_string = new String[] {}; - } else { - if (!myflags.isEmpty()) { - flags_string = myflags.split(","); - } else { - flags_string = new String[] {}; - } - } - final HashMap flags = new HashMap<>(); - boolean exception = false; - for (String element : flags_string) { - if (element.contains(":")) { - final String[] split = element.split(":"); - try { - final String flag_str = split[1].replaceAll("\u00AF", ":").replaceAll("\u00B4", ","); - final Flag flag = new Flag(FlagManager.getFlag(split[0], true), flag_str); - flags.put(flag.getKey(), flag); - } catch (final Exception e) { - e.printStackTrace(); - exception = true; - } - } else { - element = element.replaceAll("\u00AF", ":").replaceAll("\u00B4", ","); - if (StringMan.isAlpha(element.replaceAll("_", "").replaceAll("-", ""))) { - final Flag flag = new Flag(FlagManager.getFlag(element, true), ""); - flags.put(flag.getKey(), flag); - } else { - PS.debug("INVALID FLAG: " + element); - } - } - } - if (exception) { - PS.debug("&cPlot " + id + " | " + plot + " had an invalid flag. A fix has been attempted."); - PS.debug("&c" + myflags); - this.setFlags(plot, flags.values()); - } - plot.getSettings().flags = flags; - } else if (Settings.AUTO_PURGE) { - toDelete.add(id); - } else { - PS.debug("&cENTRY " + id + " in `plot_settings` does not exist. Create this plot or set `auto-purge: true` in the settings.yml."); - } - } - stmt.close(); - deleteRows(toDelete, "plot_settings", "plot_plot_id"); - } - if (!plots.entrySet().isEmpty()) { - createEmptySettings(new ArrayList<>(plots.keySet()), null); - for (Entry entry : plots.entrySet()) { - entry.getValue().getSettings(); - } - } - boolean invalidPlot = false; - for (final Entry entry : noExist.entrySet()) { - final String worldname = entry.getKey(); - invalidPlot = true; - PS.debug("&c[WARNING] Found " + entry.getValue().intValue() + " plots in DB for non existant world; '" + worldname + "'."); - } - if (invalidPlot) { - PS.debug("&c[WARNING] - Please create the world/s or remove the plots using the purge command"); - } - } catch (final SQLException e) { - PS.debug("&7[WARN] " + "Failed to load plots."); - e.printStackTrace(); - } - return newplots; - } - - @Override - public void setMerged(final Plot plot, final boolean[] merged) { - plot.getSettings().setMerged(merged); - addPlotTask(plot, new UniqueStatement("setMerged") { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - int hash = MainUtil.hash(merged); - stmt.setInt(1, hash); - stmt.setInt(2, getId(plot)); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("UPDATE `" + prefix + "plot_settings` SET `merged` = ? WHERE `plot_plot_id` = ?"); - } - }); - } - - @Override - public void swapPlots(final Plot p1, final Plot p2) { - final int id1 = getId(p1); - final int id2 = getId(p2); - final PlotId pos1 = p1.getId(); - final PlotId pos2 = p2.getId(); - addPlotTask(p1, new UniqueStatement("swapPlots") { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - stmt.setInt(1, pos2.x); - stmt.setInt(2, pos2.y); - stmt.setInt(3, id1); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("UPDATE `" + prefix + "plot` SET `plot_id_x` = ?, `plot_id_z` = ? WHERE `id` = ?"); - } - }); - addPlotTask(p2, new UniqueStatement("swapPlots") { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - stmt.setInt(1, pos1.x); - stmt.setInt(2, pos1.y); - stmt.setInt(3, id2); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("UPDATE `" + prefix + "plot` SET `plot_id_x` = ?, `plot_id_z` = ? WHERE `id` = ?"); - } - }); - } - - @Override - public void movePlot(final Plot original, final Plot newPlot) { - addPlotTask(original, new UniqueStatement("movePlot") { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - stmt.setInt(1, newPlot.getId().x); - stmt.setInt(2, newPlot.getId().y); - stmt.setString(3, newPlot.getArea().toString()); - stmt.setInt(4, getId(original)); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("UPDATE `" + prefix + "plot` SET `plot_id_x` = ?, `plot_id_z` = ?, `world` = ? WHERE `id` = ?"); - } - }); - addPlotTask(newPlot, null); - } - - @Override - public void setFlags(final Plot plot, final Collection flags) { - final StringBuilder flag_string = new StringBuilder(); - int i = 0; - for (final Flag flag : flags) { - if (i != 0) { - flag_string.append(","); - } - flag_string.append(flag.getKey() + ":" + flag.getValueString().replaceAll(":", "\u00AF").replaceAll(",", "\u00B4")); - i++; - } - addPlotTask(plot, new UniqueStatement("setFlags") { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - stmt.setString(1, flag_string.toString()); - stmt.setInt(2, getId(plot)); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("UPDATE `" + prefix + "plot_settings` SET `flags` = ? WHERE `plot_plot_id` = ?"); - } - }); - } - - @Override - public void setAlias(final Plot plot, final String alias) { - addPlotTask(plot, new UniqueStatement("setAlias") { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - stmt.setString(1, alias); - stmt.setInt(2, getId(plot)); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("UPDATE `" + prefix + "plot_settings` SET `alias` = ? WHERE `plot_plot_id` = ?"); - } - }); - } - - /** - * Purge all plots with the following database IDs - */ - @Override - public void purgeIds(final Set uniqueIds) { - addGlobalTask(new Runnable() { - @Override - public void run() { - if (!uniqueIds.isEmpty()) { - try { - String stmt_prefix = ""; - final StringBuilder idstr2 = new StringBuilder(""); - for (final Integer id : uniqueIds) { - idstr2.append(stmt_prefix).append(id); - stmt_prefix = " OR `id` = "; - } - stmt_prefix = ""; - final StringBuilder idstr = new StringBuilder(""); - for (final Integer id : uniqueIds) { - idstr.append(stmt_prefix).append(id); - stmt_prefix = " OR `plot_plot_id` = "; - } - PreparedStatement stmt = connection.prepareStatement("DELETE FROM `" + prefix + "plot_helpers` WHERE `plot_plot_id` = " + idstr + ""); - stmt.executeUpdate(); - stmt.close(); - stmt = connection.prepareStatement("DELETE FROM `" + prefix + "plot_denied` WHERE `plot_plot_id` = " + idstr + ""); - stmt.executeUpdate(); - stmt.close(); - stmt = connection.prepareStatement("DELETE FROM `" + prefix + "plot_settings` WHERE `plot_plot_id` = " + idstr + ""); - stmt.executeUpdate(); - stmt.close(); - stmt = connection.prepareStatement("DELETE FROM `" + prefix + "plot_trusted` WHERE `plot_plot_id` = " + idstr + ""); - stmt.executeUpdate(); - stmt.close(); - stmt = connection.prepareStatement("DELETE FROM `" + prefix + "plot` WHERE `id` = " + idstr2 + ""); - stmt.executeUpdate(); - stmt.close(); - } catch (final SQLException e) { - e.printStackTrace(); - PS.debug("&c[ERROR] " + "FAILED TO PURGE PLOTS!"); - return; - } - } - PS.debug("&6[INFO] " + "SUCCESSFULLY PURGED " + uniqueIds.size() + " PLOTS!"); - } - }); - } - - @Override - public void purge(final PlotArea area, final Set plots) { - addGlobalTask(new Runnable() { - @Override - public void run() { - try (PreparedStatement stmt = connection - .prepareStatement("SELECT `id`, `plot_id_x`, `plot_id_z` FROM `" + prefix + "plot` WHERE `world` = ?")) { - stmt.setString(1, area.toString()); - Set ids; - try (ResultSet r = stmt.executeQuery()) { - ids = new HashSet<>(); - while (r.next()) { - PlotId plot_id = new PlotId(r.getInt("plot_id_x"), r.getInt("plot_id_z")); - if (plots.contains(plot_id)) { - ids.add(r.getInt("id")); - } - } - } - purgeIds(ids); - } catch (final SQLException e) { - e.printStackTrace(); - PS.debug("&c[ERROR] " + "FAILED TO PURGE AREA '" + area + "'!"); - } - for (final Iterator iter = plots.iterator(); iter.hasNext();) { - final PlotId plotId = iter.next(); - iter.remove(); - final PlotId id = new PlotId(plotId.x, plotId.y); - area.removePlot(id); - } - } - }); - } - - @Override - public void setPosition(final Plot plot, final String position) { - addPlotTask(plot, new UniqueStatement("setPosition") { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - stmt.setString(1, position); - stmt.setInt(2, getId(plot)); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("UPDATE `" + prefix + "plot_settings` SET `position` = ? WHERE `plot_plot_id` = ?"); - } - }); - } - - @Override - public void removeComment(final Plot plot, final PlotComment comment) { - addPlotTask(plot, new UniqueStatement("removeComment") { - @Override - public void set(final PreparedStatement statement) throws SQLException { - if (plot != null) { - statement.setString(1, plot.getArea().toString()); - statement.setInt(2, plot.getId().hashCode()); - statement.setString(3, comment.comment); - statement.setString(4, comment.inbox); - statement.setString(5, comment.senderName); - } else { - statement.setString(1, comment.comment); - statement.setString(2, comment.inbox); - statement.setString(3, comment.senderName); - } - } - - @Override - public PreparedStatement get() throws SQLException { - if (plot != null) { - return connection.prepareStatement("DELETE FROM `" + prefix + "plot_comments` WHERE `world` = ? AND `hashcode` = ? AND `comment` = ? AND `inbox` = ? AND `sender` = ?"); - } - return connection.prepareStatement("DELETE FROM `" + prefix + "plot_comments` WHERE `comment` = ? AND `inbox` = ? AND `sender` = ?"); - } - }); - } - - @Override - public void clearInbox(final Plot plot, final String inbox) { - addPlotTask(plot, new UniqueStatement("clearInbox") { - @Override - public void set(final PreparedStatement statement) throws SQLException { - if (plot != null) { - statement.setString(1, plot.getArea().toString()); - statement.setInt(2, plot.getId().hashCode()); - statement.setString(3, inbox); - } else { - statement.setString(1, inbox); - } - } - - @Override - public PreparedStatement get() throws SQLException { - if (plot != null) { - return connection.prepareStatement("DELETE FROM `" + prefix + "plot_comments` WHERE `world` = ? AND `hashcode` = ? AND `inbox` = ?"); - } - return connection.prepareStatement("DELETE FROM `" + prefix + "plot_comments` `inbox` = ?"); - } - }); - } - - @Override - public void getComments(final Plot plot, final String inbox, final RunnableVal> whenDone) { - addPlotTask(plot, new UniqueStatement("getComments_" + plot) { - @Override - public void set(final PreparedStatement statement) throws SQLException { - if (plot != null) { - statement.setString(1, plot.getArea().toString()); - statement.setInt(2, plot.getId().hashCode()); - statement.setString(3, inbox); - } else { - statement.setString(1, inbox); - } - } - - @Override - public PreparedStatement get() throws SQLException { - if (plot != null) { - return connection.prepareStatement("SELECT * FROM `" + prefix + "plot_comments` WHERE `world` = ? AND `hashcode` = ? AND `inbox` = ?"); - } - return connection.prepareStatement("SELECT * FROM `" + prefix + "plot_comments` WHERE `inbox` = ?"); - } - - @Override - public void execute(final PreparedStatement stmt) {} - - @Override - public void addBatch(final PreparedStatement statement) throws SQLException { - final ArrayList comments = new ArrayList<>(); - try (ResultSet set = statement.executeQuery()) { - while (set.next()) { - final String sender = set.getString("sender"); - final String world = set.getString("world"); - final int hash = set.getInt("hashcode"); - PlotId id; - if (hash != 0) { - id = PlotId.unpair(hash); - } else { - id = null; - } - final String msg = set.getString("comment"); - final long timestamp = set.getInt("timestamp") * 1000; - PlotComment comment = new PlotComment(world, id, msg, sender, inbox, timestamp); - comments.add(comment); - whenDone.value = comments; - } - } - TaskManager.runTask(whenDone); - } - }); - } - - @Override - public void setComment(final Plot plot, final PlotComment comment) { - addPlotTask(plot, new UniqueStatement("setComment") { - @Override - public void set(final PreparedStatement statement) throws SQLException { - statement.setString(1, plot.getArea().toString()); - statement.setInt(2, plot.getId().hashCode()); - statement.setString(3, comment.comment); - statement.setString(4, comment.inbox); - statement.setInt(5, (int) (comment.timestamp / 1000)); - statement.setString(6, comment.senderName); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("INSERT INTO `" + prefix + "plot_comments` (`world`, `hashcode`, `comment`, `inbox`, `timestamp`, `sender`) VALUES(?,?,?,?,?,?)"); - } - }); - } - - @Override - public void removeTrusted(final Plot plot, final UUID uuid) { - addPlotTask(plot, new UniqueStatement("removeTrusted") { - @Override - public void set(final PreparedStatement statement) throws SQLException { - statement.setInt(1, getId(plot)); - statement.setString(2, uuid.toString()); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("DELETE FROM `" + prefix + "plot_helpers` WHERE `plot_plot_id` = ? AND `user_uuid` = ?"); - } - }); - } - - @Override - public void removeMember(final Plot plot, final UUID uuid) { - addPlotTask(plot, new UniqueStatement("removeMember") { - @Override - public void set(final PreparedStatement statement) throws SQLException { - statement.setInt(1, getId(plot)); - statement.setString(2, uuid.toString()); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("DELETE FROM `" + prefix + "plot_trusted` WHERE `plot_plot_id` = ? AND `user_uuid` = ?"); - } - }); - } - - @Override - public void setTrusted(final Plot plot, final UUID uuid) { - addPlotTask(plot, new UniqueStatement("setTrusted") { - @Override - public void set(final PreparedStatement statement) throws SQLException { - statement.setInt(1, getId(plot)); - statement.setString(2, uuid.toString()); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("INSERT INTO `" + prefix + "plot_helpers` (`plot_plot_id`, `user_uuid`) VALUES(?,?)"); - } - }); - } - - @Override - public void setMember(final Plot plot, final UUID uuid) { - addPlotTask(plot, new UniqueStatement("setMember") { - @Override - public void set(final PreparedStatement statement) throws SQLException { - statement.setInt(1, getId(plot)); - statement.setString(2, uuid.toString()); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("INSERT INTO `" + prefix + "plot_trusted` (`plot_plot_id`, `user_uuid`) VALUES(?,?)"); - } - }); - } - - @Override - public void removeDenied(final Plot plot, final UUID uuid) { - addPlotTask(plot, new UniqueStatement("removeDenied") { - @Override - public void set(final PreparedStatement statement) throws SQLException { - statement.setInt(1, getId(plot)); - statement.setString(2, uuid.toString()); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("DELETE FROM `" + prefix + "plot_denied` WHERE `plot_plot_id` = ? AND `user_uuid` = ?"); - } - }); - } - - @Override - public void setDenied(final Plot plot, final UUID uuid) { - addPlotTask(plot, new UniqueStatement("setDenied") { - @Override - public void set(final PreparedStatement statement) throws SQLException { - statement.setInt(1, getId(plot)); - statement.setString(2, uuid.toString()); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("INSERT INTO `" + prefix + "plot_denied` (`plot_plot_id`, `user_uuid`) VALUES(?,?)"); - } - }); - } - - @Override - public HashMap getRatings(final Plot plot) { - final HashMap map = new HashMap<>(); - try (PreparedStatement statement = connection - .prepareStatement("SELECT `rating`, `player` FROM `" + prefix + "plot_rating` WHERE `plot_plot_id` = ? ")) { - statement.setInt(1, getId(plot)); - try (ResultSet set = statement.executeQuery()) { - while (set.next()) { - final UUID uuid = UUID.fromString(set.getString("player")); - final int rating = set.getInt("rating"); - map.put(uuid, rating); - } - } - } catch (final SQLException e) { - PS.debug("&7[WARN] " + "Failed to fetch rating for plot " + plot.getId().toString()); - e.printStackTrace(); - } - return map; - } - - @Override - public void setRating(final Plot plot, final UUID rater, final int value) { - addPlotTask(plot, new UniqueStatement("setRating") { - @Override - public void set(final PreparedStatement statement) throws SQLException { - statement.setInt(1, getId(plot)); - statement.setInt(2, value); - statement.setString(3, rater.toString()); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("INSERT INTO `" + prefix + "plot_rating` (`plot_plot_id`, `rating`, `player`) VALUES(?,?,?)"); - } - }); - } - - @Override - public void delete(final PlotCluster cluster) { - final int id = getClusterId(cluster); - addClusterTask(cluster, new UniqueStatement("delete_cluster_settings") { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - stmt.setInt(1, id); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("DELETE FROM `" + prefix + "cluster_settings` WHERE `cluster_id` = ?"); - } - }); - addClusterTask(cluster, new UniqueStatement("delete_cluster_helpers") { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - stmt.setInt(1, id); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("DELETE FROM `" + prefix + "cluster_helpers` WHERE `cluster_id` = ?"); - } - }); - addClusterTask(cluster, new UniqueStatement("delete_cluster_invited") { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - stmt.setInt(1, id); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("DELETE FROM `" + prefix + "cluster_invited` WHERE `cluster_id` = ?"); - } - }); - addClusterTask(cluster, new UniqueStatement("delete_cluster") { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - stmt.setInt(1, id); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("DELETE FROM `" + prefix + "cluster` WHERE `id` = ?"); - } - }); - } - - @Override - public void addPersistentMeta(final UUID uuid, final String key, final byte[] meta, final boolean replace) { - addPlayerTask(uuid, new UniqueStatement("addPersistentMeta") { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - Blob blob = connection.createBlob(); - blob.setBytes(1, meta); - if (replace) { - stmt.setBlob(1, blob); - stmt.setString(2, uuid.toString()); - stmt.setString(3, key); - } else { - stmt.setString(1, uuid.toString()); - stmt.setString(2, key); - stmt.setBlob(3, blob); - } - } - - @Override - public PreparedStatement get() throws SQLException { - if (replace) { - return connection.prepareStatement("UPDATE `" + prefix + "player_meta` SET `value` = ? WHERE `uuid` = ? AND `key` = ?"); - } else { - return connection.prepareStatement("INSERT INTO `" + prefix + "player_meta`(`uuid`, `key`, `value`) VALUES(?, ? ,?)"); - } - } - }); - } - - @Override - public void removePersistentMeta(final UUID uuid, final String key) { - addPlayerTask(uuid, new UniqueStatement("removePersistentMeta") { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - stmt.setString(1, uuid.toString()); - stmt.setString(2, key); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("DELETE FROM `" + prefix + "player_meta` WHERE `uuid` = ? AND `key` = ?"); - } - }); - } - - @Override - public void getPersistentMeta(final UUID uuid, final RunnableVal> result) { - addPlayerTask(uuid, new UniqueStatement("getPersistentMeta") { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - stmt.setString(1, uuid.toString()); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("SELECT * FROM `" + prefix + "player_meta` WHERE `uuid` = ?"); - } - - @Override - public void execute(PreparedStatement stmt) {} - - @Override - public void addBatch(PreparedStatement stmt) throws SQLException { - ResultSet resultSet = stmt.executeQuery(); - - final Map metaMap = new HashMap<>(); - - while (resultSet.next()) { - String key = resultSet.getString("key"); - Blob rawValue = resultSet.getBlob("value"); - byte[] bytes = rawValue.getBytes(1, (int) rawValue.length()); - metaMap.put(key, bytes); - } - - resultSet.close(); - result.run(metaMap); - } - - }); - } - - @Override - public HashMap> getClusters() { - final LinkedHashMap> newClusters = new LinkedHashMap<>(); - final HashMap clusters = new HashMap<>(); - try { - HashSet areas = new HashSet<>(); - if (PS.get().config.contains("worlds")) { - ConfigurationSection worldSection = PS.get().config.getConfigurationSection("worlds"); - if (worldSection != null) { - for (String worldKey : worldSection.getKeys(false)) { - areas.add(worldKey); - ConfigurationSection areaSection = worldSection.getConfigurationSection(worldKey + ".areas"); - if (areaSection != null) { - for (String areaKey : areaSection.getKeys(false)) { - String[] split = areaKey.split("-"); - if (split.length == 3) { - areas.add(worldKey + ";" + split[0]); - } - } - } - } - } - } - final HashMap uuids = new HashMap<>(); - final HashMap noExist = new HashMap<>(); - /* - * Getting clusters - */ - Statement stmt = connection.createStatement(); - ResultSet r = stmt.executeQuery("SELECT * FROM `" + prefix + "cluster`"); - PlotCluster cluster; - String owner; - UUID user; - int id; - while (r.next()) { - PlotId pos1 = new PlotId(r.getInt("pos1_x"), r.getInt("pos1_z")); - PlotId pos2 = new PlotId(r.getInt("pos2_x"), r.getInt("pos2_z")); - id = r.getInt("id"); - String areaid = r.getString("world"); - if (!areas.contains(areaid)) { - if (noExist.containsKey(areaid)) { - noExist.put(areaid, noExist.get(areaid) + 1); - } else { - noExist.put(areaid, 1); - } - } - owner = r.getString("owner"); - user = uuids.get(owner); - if (user == null) { - user = UUID.fromString(owner); - uuids.put(owner, user); - } - cluster = new PlotCluster(null, pos1, pos2, user, id); - clusters.put(id, cluster); - Set set = newClusters.get(areaid); - if (set == null) { - set = new HashSet<>(); - newClusters.put(areaid, set); - } - set.add(cluster); - } - /* - * Getting helpers - */ - r = stmt.executeQuery("SELECT `user_uuid`, `cluster_id` FROM `" + prefix + "cluster_helpers`"); - while (r.next()) { - id = r.getInt("cluster_id"); - owner = r.getString("user_uuid"); - user = uuids.get(owner); - if (user == null) { - user = UUID.fromString(owner); - uuids.put(owner, user); - } - cluster = clusters.get(id); - if (cluster != null) { - cluster.helpers.add(user); - } else { - PS.debug("&cCluster " + id + " in cluster_helpers does not exist. Please create the cluster or remove this entry."); - } - } - /* - * Getting invited - */ - r = stmt.executeQuery("SELECT `user_uuid`, `cluster_id` FROM `" + prefix + "cluster_invited`"); - while (r.next()) { - id = r.getInt("cluster_id"); - owner = r.getString("user_uuid"); - user = uuids.get(owner); - if (user == null) { - user = UUID.fromString(owner); - uuids.put(owner, user); - } - cluster = clusters.get(id); - if (cluster != null) { - cluster.invited.add(user); - } else { - PS.debug("&cCluster " + id + " in cluster_invited does not exist. Please create the cluster or remove this entry."); - } - } - r = stmt.executeQuery("SELECT * FROM `" + prefix + "cluster_settings`"); - while (r.next()) { - id = r.getInt("cluster_id"); - cluster = clusters.get(id); - if (cluster != null) { - final String alias = r.getString("alias"); - if (alias != null) { - cluster.settings.setAlias(alias); - } - final String pos = r.getString("position"); - switch (pos.toLowerCase()) { - case "": - case "default": - case "0,0,0": - case "center": - break; - default: - try { - BlockLoc loc = BlockLoc.fromString(pos); - cluster.settings.setPosition(loc); - } catch (final Exception e) {} - } - final Integer m = r.getInt("merged"); - final boolean[] merged = new boolean[4]; - for (int i = 0; i < 4; i++) { - merged[3 - i] = ((m) & (1 << i)) != 0; - } - cluster.settings.setMerged(merged); - String[] flags_string; - final String myflags = r.getString("flags"); - if (myflags == null) { - flags_string = new String[] {}; - } else { - if (!myflags.isEmpty()) { - flags_string = myflags.split(","); - } else { - flags_string = new String[] {}; - } - } - final HashMap flags = new HashMap<>(); - boolean exception = false; - for (final String element : flags_string) { - if (element.contains(":")) { - final String[] split = element.split(":"); - try { - final String flag_str = split[1].replaceAll("\u00AF", ":").replaceAll("�", ","); - final Flag flag = new Flag(FlagManager.getFlag(split[0], true), flag_str); - flags.put(flag.getKey(), flag); - } catch (final Exception e) { - e.printStackTrace(); - exception = true; - } - } else { - final Flag flag = new Flag(FlagManager.getFlag(element, true), ""); - flags.put(flag.getKey(), flag); - } - } - if (exception) { - PS.debug("&cCluster " + id + " had an invalid flag. A fix has been attempted."); - PS.debug("&c" + myflags); - } - cluster.settings.flags = flags; - } else { - PS.debug("&cCluster " + id + " in cluster_settings does not exist. Please create the cluster or remove this entry."); - } - } - stmt.close(); - r.close(); - boolean invalidPlot = false; - for (final Entry entry : noExist.entrySet()) { - final String a = entry.getKey(); - invalidPlot = true; - PS.debug("&c[WARNING] Found " + noExist.get(a) + " clusters in DB for non existant area; '" + a + "'."); - } - if (invalidPlot) { - PS.debug("&c[WARNING] - Please create the world/s or remove the clusters using the purge command"); - } - } catch (final SQLException e) { - PS.debug("&7[WARN] " + "Failed to load clusters."); - e.printStackTrace(); - } - return newClusters; - } - - @Override - public void setFlags(final PlotCluster cluster, final Collection flags) { - final StringBuilder flag_string = new StringBuilder(); - int i = 0; - for (final Flag flag : flags) { - if (i != 0) { - flag_string.append(","); - } - flag_string.append(flag.getKey() + ":" + flag.getValueString().replaceAll(":", "\u00AF").replaceAll(",", "\u00B4")); - i++; - } - addClusterTask(cluster, new UniqueStatement("setFlags") { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - stmt.setString(1, flag_string.toString()); - stmt.setInt(2, getClusterId(cluster)); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("UPDATE `" + prefix + "cluster_settings` SET `flags` = ? WHERE `cluster_id` = ?"); - } - }); - } - - @Override - public void setClusterName(final PlotCluster cluster, final String name) { - addClusterTask(cluster, new UniqueStatement("setClusterName") { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - stmt.setString(1, name); - stmt.setInt(2, getClusterId(cluster)); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("UPDATE `" + prefix + "cluster_settings` SET `alias` = ? WHERE `cluster_id` = ?"); - } - }); - cluster.settings.setAlias(name); - } - - @Override - public void removeHelper(final PlotCluster cluster, final UUID uuid) { - addClusterTask(cluster, new UniqueStatement("removeHelper") { - @Override - public void set(final PreparedStatement statement) throws SQLException { - statement.setInt(1, getClusterId(cluster)); - statement.setString(2, uuid.toString()); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("DELETE FROM `" + prefix + "cluster_helpers` WHERE `cluster_id` = ? AND `user_uuid` = ?"); - } - }); - } - - @Override - public void setHelper(final PlotCluster cluster, final UUID uuid) { - addClusterTask(cluster, new UniqueStatement("setHelper") { - @Override - public void set(final PreparedStatement statement) throws SQLException { - statement.setInt(1, getClusterId(cluster)); - statement.setString(2, uuid.toString()); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("INSERT INTO `" + prefix + "cluster_helpers` (`cluster_id`, `user_uuid`) VALUES(?,?)"); - } - }); - } - - @Override - public void createCluster(final PlotCluster cluster) { - addClusterTask(cluster, new UniqueStatement("createCluster_" + cluster.hashCode()) { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - stmt.setInt(1, cluster.getP1().x); - stmt.setInt(2, cluster.getP1().y); - stmt.setInt(3, cluster.getP2().x); - stmt.setInt(4, cluster.getP2().y); - stmt.setString(5, cluster.owner.toString()); - stmt.setString(6, cluster.area.toString()); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement(CREATE_CLUSTER, Statement.RETURN_GENERATED_KEYS); - } - - @Override - public void execute(final PreparedStatement stmt) { - - } - - @Override - public void addBatch(final PreparedStatement stmt) throws SQLException { - stmt.executeUpdate(); - final ResultSet keys = stmt.getGeneratedKeys(); - if (keys.next()) { - cluster.temp = keys.getInt(1); - } - } - }); - addClusterTask(cluster, new UniqueStatement("createCluster_settings_" + cluster.hashCode()) { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - stmt.setInt(1, getClusterId(cluster)); - stmt.setString(2, cluster.settings.getAlias()); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("INSERT INTO `" + prefix + "cluster_settings`(`cluster_id`, `alias`) VALUES(?, ?" + ")"); - } - }); - } - - @Override - public void resizeCluster(final PlotCluster current, PlotId min, PlotId max) { - final PlotId pos1 = new PlotId(current.getP1().x, current.getP1().y); - final PlotId pos2 = new PlotId(current.getP2().x, current.getP2().y); - current.setP1(min); - current.setP2(max); - - addClusterTask(current, new UniqueStatement("resizeCluster") { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - stmt.setInt(1, pos1.x); - stmt.setInt(2, pos1.y); - stmt.setInt(3, pos2.x); - stmt.setInt(4, pos2.y); - stmt.setInt(5, getClusterId(current)); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("UPDATE `" + prefix + "cluster` SET `pos1_x` = ?, `pos1_z` = ?, `pos2_x` = ?, `pos2_z` = ? WHERE `id` = ?"); - } - }); - } - - @Override - public void setPosition(final PlotCluster cluster, final String position) { - addClusterTask(cluster, new UniqueStatement("setPosition") { - @Override - public void set(final PreparedStatement stmt) throws SQLException { - stmt.setString(1, position); - stmt.setInt(2, getClusterId(cluster)); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("UPDATE `" + prefix + "cluster_settings` SET `position` = ? WHERE `cluster_id` = ?"); - } - }); - } - - @Override - public void removeInvited(final PlotCluster cluster, final UUID uuid) { - addClusterTask(cluster, new UniqueStatement("removeInvited") { - @Override - public void set(final PreparedStatement statement) throws SQLException { - statement.setInt(1, getClusterId(cluster)); - statement.setString(2, uuid.toString()); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("DELETE FROM `" + prefix + "cluster_invited` WHERE `cluster_id` = ? AND `user_uuid` = ?"); - } - }); - } - - @Override - public void setInvited(final PlotCluster cluster, final UUID uuid) { - addClusterTask(cluster, new UniqueStatement("setInvited") { - @Override - public void set(final PreparedStatement statement) throws SQLException { - statement.setInt(1, getClusterId(cluster)); - statement.setString(2, uuid.toString()); - } - - @Override - public PreparedStatement get() throws SQLException { - return connection.prepareStatement("INSERT INTO `" + prefix + "cluster_invited` (`cluster_id`, `user_uuid`) VALUES(?,?)"); - } - }); - } - - @Override - public boolean deleteTables() { - try { - close(); - CLOSED = false; - SQLManager.this.connection = database.forceConnection(); - final Statement stmt = connection.createStatement(); - stmt.addBatch("DROP TABLE `" + prefix + "cluster_invited`"); - stmt.addBatch("DROP TABLE `" + prefix + "cluster_helpers`"); - stmt.addBatch("DROP TABLE `" + prefix + "cluster`"); - stmt.addBatch("DROP TABLE `" + prefix + "plot_rating`"); - stmt.addBatch("DROP TABLE `" + prefix + "plot_settings`"); - stmt.addBatch("DROP TABLE `" + prefix + "plot_comments`"); - stmt.addBatch("DROP TABLE `" + prefix + "plot_trusted`"); - stmt.addBatch("DROP TABLE `" + prefix + "plot_helpers`"); - stmt.addBatch("DROP TABLE `" + prefix + "plot_denied`"); - stmt.executeBatch(); - stmt.clearBatch(); - stmt.close(); - - final PreparedStatement statement = connection.prepareStatement("DROP TABLE `" + prefix + "plot`"); - statement.executeUpdate(); - statement.close(); - } catch (ClassNotFoundException | SQLException e) { - e.printStackTrace(); - } - return true; - } - - @Override - public void validateAllPlots(final Set toValidate) { - try { - if (connection.isClosed() || CLOSED) { - CLOSED = false; - connection = database.forceConnection(); - } - } catch (ClassNotFoundException | SQLException e) { - e.printStackTrace(); - } - PS.debug("$1All DB transactions during this session are being validated (This may take a while if corrections need to be made)"); - commit(); - while (true) { - if (!sendBatch()) { - break; - } - } - try { - if (connection.getAutoCommit()) { - connection.setAutoCommit(false); - } - } catch (final SQLException e) { - e.printStackTrace(); - } - final HashMap> database = getPlots(); - final ArrayList toCreate = new ArrayList<>(); - for (final Plot plot : toValidate) { - if (plot.temp == -1) { - continue; - } - final HashMap worldplots = database.get(plot.getArea().toString()); - if (worldplots == null) { - PS.debug("&8 - &7Creating plot (1): " + plot); - toCreate.add(plot); - continue; - } - final Plot dataplot = worldplots.remove(plot.getId()); - if (dataplot == null) { - PS.debug("&8 - &7Creating plot (2): " + plot); - toCreate.add(plot); - continue; - } - // owner - if (!plot.owner.equals(dataplot.owner)) { - PS.debug("&8 - &7Setting owner: " + plot + " -> " + MainUtil.getName(plot.owner)); - setOwner(plot, plot.owner); - } - // trusted - if (!plot.getTrusted().equals(dataplot.getTrusted())) { - final HashSet toAdd = (HashSet) plot.getTrusted().clone(); - final HashSet toRemove = (HashSet) dataplot.getTrusted().clone(); - toRemove.removeAll(plot.getTrusted()); - toAdd.removeAll(dataplot.getTrusted()); - PS.debug("&8 - &7Correcting " + (toAdd.size() + toRemove.size()) + " trusted for: " + plot); - if (!toRemove.isEmpty()) { - for (final UUID uuid : toRemove) { - removeTrusted(plot, uuid); - } - } - if (!toAdd.isEmpty()) { - for (final UUID uuid : toAdd) { - setTrusted(plot, uuid); - } - } - } - if (!plot.getMembers().equals(dataplot.getMembers())) { - final HashSet toAdd = (HashSet) plot.getMembers().clone(); - final HashSet toRemove = (HashSet) dataplot.getMembers().clone(); - toRemove.removeAll(plot.getMembers()); - toAdd.removeAll(dataplot.getMembers()); - PS.debug("&8 - &7Correcting " + (toAdd.size() + toRemove.size()) + " members for: " + plot); - if (!toRemove.isEmpty()) { - for (final UUID uuid : toRemove) { - removeMember(plot, uuid); - } - } - if (!toAdd.isEmpty()) { - for (final UUID uuid : toAdd) { - setMember(plot, uuid); - } - } - } - if (!plot.getDenied().equals(dataplot.getDenied())) { - final HashSet toAdd = (HashSet) plot.getDenied().clone(); - final HashSet toRemove = (HashSet) dataplot.getDenied().clone(); - toRemove.removeAll(plot.getDenied()); - toAdd.removeAll(dataplot.getDenied()); - PS.debug("&8 - &7Correcting " + (toAdd.size() + toRemove.size()) + " denied for: " + plot); - if (!toRemove.isEmpty()) { - for (final UUID uuid : toRemove) { - removeDenied(plot, uuid); - } - } - if (!toAdd.isEmpty()) { - for (final UUID uuid : toAdd) { - setDenied(plot, uuid); - } - } - } - final boolean[] pm = plot.getMerged(); - final boolean[] dm = dataplot.getMerged(); - if (pm[0] != dm[0] || pm[1] != dm[1]) { - PS.debug("&8 - &7Correcting merge for: " + plot); - setMerged(dataplot, plot.getMerged()); - } - final HashMap pf = plot.getFlags(); - final HashMap df = dataplot.getFlags(); - if (!pf.isEmpty() && !df.isEmpty()) { - if (pf.size() != df.size() || !StringMan.isEqual(StringMan.joinOrdered(pf.values(), ","), StringMan.joinOrdered(df.values(), ","))) { - PS.debug("&8 - &7Correcting flags for: " + plot); - setFlags(plot, pf.values()); - } - } - } - - for (final Entry> entry : database.entrySet()) { - final HashMap map = entry.getValue(); - if (!map.isEmpty()) { - for (final Entry entry2 : map.entrySet()) { - PS.debug("$1Plot was deleted: " + entry2.getValue() + "// TODO implement this when sure safe"); - } - } - } - commit(); - } - - @Override - public void replaceWorld(final String oldWorld, final String newWorld, final PlotId min, final PlotId max) { - addGlobalTask(new Runnable() { - @Override - public void run() { - if (min == null) { - try (PreparedStatement stmt = connection.prepareStatement("UPDATE `" + prefix + "plot` SET `world` = ? WHERE `world` = ?")) { - stmt.setString(1, newWorld); - stmt.setString(2, oldWorld); - stmt.executeUpdate(); - stmt.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - try (PreparedStatement stmt = connection.prepareStatement("UPDATE `" + prefix + "cluster` SET `world` = ? WHERE `world` = ?")) { - stmt.setString(1, newWorld); - stmt.setString(2, oldWorld); - stmt.executeUpdate(); - stmt.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } else { - try (PreparedStatement stmt = connection.prepareStatement("UPDATE `" - + prefix - + "plot` SET `world` = ? WHERE `world` = ? AND `plot_id_x` BETWEEN ? AND ? AND `plot_id_z` BETWEEN ? AND ?")) { - stmt.setString(1, newWorld); - stmt.setString(2, oldWorld); - stmt.setInt(3, min.x); - stmt.setInt(4, max.x); - stmt.setInt(5, min.y); - stmt.setInt(6, max.y); - stmt.executeUpdate(); - stmt.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - try (PreparedStatement stmt = connection.prepareStatement("UPDATE `" - + prefix - + "cluster` SET `world` = ? WHERE `world` = ? AND `pos1_x` <= ? AND `pos1_z` <= ? AND `pos2_x` >= ? AND `pos2_z` >= ?")) { - stmt.setString(1, newWorld); - stmt.setString(2, oldWorld); - stmt.setInt(3, max.x); - stmt.setInt(4, max.y); - stmt.setInt(5, min.x); - stmt.setInt(6, min.y); - stmt.executeUpdate(); - stmt.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - } - }); - } - - @Override - public void replaceUUID(final UUID old, final UUID now) { - addGlobalTask(new Runnable() { - @Override - public void run() { - try (Statement stmt = connection.createStatement()) { - stmt.executeUpdate( - "UPDATE `" + prefix + "cluster` SET `owner` = '" + now.toString() + "' WHERE `owner` = '" + old.toString() + "'"); - stmt.executeUpdate( - "UPDATE `" + prefix + "cluster_helpers` SET `user_uuid` = '" + now.toString() + "' WHERE `user_uuid` = '" + old.toString() - + "'"); - stmt.executeUpdate( - "UPDATE `" + prefix + "cluster_invited` SET `user_uuid` = '" + now.toString() + "' WHERE `user_uuid` = '" + old.toString() - + "'"); - stmt.executeUpdate("UPDATE `" + prefix + "plot` SET `owner` = '" + now.toString() + "' WHERE `owner` = '" + old.toString() + "'"); - stmt.executeUpdate( - "UPDATE `" + prefix + "plot_denied` SET `user_uuid` = '" + now.toString() + "' WHERE `user_uuid` = '" + old.toString() - + "'"); - stmt.executeUpdate( - "UPDATE `" + prefix + "plot_helpers` SET `user_uuid` = '" + now.toString() + "' WHERE `user_uuid` = '" + old.toString() - + "'"); - stmt.executeUpdate( - "UPDATE `" + prefix + "plot_trusted` SET `user_uuid` = '" + now.toString() + "' WHERE `user_uuid` = '" + old.toString() - + "'"); - stmt.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - }); - } - - @Override - public void close() { - try { - CLOSED = true; - connection.close(); - } catch (final SQLException e) { - e.printStackTrace(); - } - } - - public abstract class UniqueStatement { - - public String _method; - - public UniqueStatement(final String method) { - _method = method; - } - - public void addBatch(final PreparedStatement stmt) throws SQLException { - stmt.addBatch(); - } - - public void execute(final PreparedStatement stmt) throws SQLException { - stmt.executeBatch(); - } - - public abstract PreparedStatement get() throws SQLException; - - public abstract void set(final PreparedStatement stmt) throws SQLException; - } - - private class UUIDPair { - - public final int id; - public final UUID uuid; - - public UUIDPair(final int id, final UUID uuid) { - this.id = id; - this.uuid = uuid; - } - } - - private class SettingsPair { - - public final int id; - public final PlotSettings settings; - - public SettingsPair(final int id, final PlotSettings settings) { - this.id = id; - this.settings = settings; - } - } -} +//////////////////////////////////////////////////////////////////////////////////////////////////// +// PlotSquared - A plot manager and world generator for the Bukkit API / +// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / +// / +// This program is free software; you can redistribute it and/or modify / +// it under the terms of the GNU General Public License as published by / +// the Free Software Foundation; either version 3 of the License, or / +// (at your option) any later version. / +// / +// This program is distributed in the hope that it will be useful, / +// but WITHOUT ANY WARRANTY; without even the implied warranty of / +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / +// GNU General Public License for more details. / +// / +// You should have received a copy of the GNU General Public License / +// along with this program; if not, write to the Free Software Foundation, / +// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / +// / +// You can contact us via: support@intellectualsites.com / +//////////////////////////////////////////////////////////////////////////////////////////////////// +package com.intellectualcrafters.plot.database; + +import com.intellectualcrafters.configuration.ConfigurationSection; +import com.intellectualcrafters.plot.PS; +import com.intellectualcrafters.plot.config.Settings; +import com.intellectualcrafters.plot.flag.Flag; +import com.intellectualcrafters.plot.flag.FlagManager; +import com.intellectualcrafters.plot.object.BlockLoc; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotArea; +import com.intellectualcrafters.plot.object.PlotCluster; +import com.intellectualcrafters.plot.object.PlotId; +import com.intellectualcrafters.plot.object.PlotSettings; +import com.intellectualcrafters.plot.object.RunnableVal; +import com.intellectualcrafters.plot.object.comment.PlotComment; +import com.intellectualcrafters.plot.util.MainUtil; +import com.intellectualcrafters.plot.util.StringMan; +import com.intellectualcrafters.plot.util.TaskManager; + +import java.sql.Blob; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Queue; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicInteger; + +/** + + */ +public class SQLManager implements AbstractDB { + // Public final + public final String SET_OWNER; + public final String GET_ALL_PLOTS; + public final String CREATE_PLOTS; + public final String CREATE_SETTINGS; + public final String CREATE_TIERS; + public final String CREATE_PLOT; + public final String CREATE_CLUSTER; + private final String prefix; + // Private Final + private final Database database; + private final boolean MYSQL; + /** + * important tasks + */ + public volatile Queue globalTasks; + /** + * Notify tasks + */ + public volatile Queue notifyTasks; + /** + * plot + * plot_denied + * plot_helpers + * plot_trusted + * plot_comments + * plot_settings + * plot_rating + */ + public volatile ConcurrentHashMap> plotTasks; + /** + * player_meta + */ + public volatile ConcurrentHashMap> playerTasks; + /** + * cluster + * cluster_helpers + * cluster_invited + * cluster_settings + */ + public volatile ConcurrentHashMap> clusterTasks; + // Private + private Connection connection; + private boolean CLOSED = false; + + /** + * Constructor + * + * @param database + * @param p prefix + * @throws SQLException + * @throws ClassNotFoundException + */ + public SQLManager(final Database database, final String p, final boolean debug) throws SQLException, ClassNotFoundException { + // Private final + this.database = database; + connection = database.openConnection(); + MYSQL = database instanceof MySQL; + globalTasks = new ConcurrentLinkedQueue<>(); + notifyTasks = new ConcurrentLinkedQueue<>(); + plotTasks = new ConcurrentHashMap<>(); + playerTasks = new ConcurrentHashMap<>(); + clusterTasks = new ConcurrentHashMap<>(); + TaskManager.runTaskAsync(new Runnable() { + @Override + public void run() { + long last = System.currentTimeMillis(); + while (true) { + if (CLOSED) { + break; + } + // schedule reconnect + if (MYSQL && ((System.currentTimeMillis() - last) > 550000)) { + last = System.currentTimeMillis(); + try { + close(); + CLOSED = false; + connection = database.forceConnection(); + } catch (SQLException | ClassNotFoundException e) { + e.printStackTrace(); + } + } + if (!sendBatch()) { + try { + if (!getNotifyTasks().isEmpty()) { + for (final Runnable task : getNotifyTasks()) { + TaskManager.runTask(task); + } + getNotifyTasks().clear(); + } + Thread.sleep(50); + } catch (final InterruptedException e) { + e.printStackTrace(); + } + } + } + } + }); + prefix = p; + // Set timout + // setTimout(); + // Public final + SET_OWNER = "UPDATE `" + prefix + "plot` SET `owner` = ? WHERE `plot_id_x` = ? AND `plot_id_z` = ? AND `world` = ?"; + GET_ALL_PLOTS = "SELECT `id`, `plot_id_x`, `plot_id_z`, `world` FROM `" + prefix + "plot`"; + CREATE_PLOTS = "INSERT INTO `" + prefix + "plot`(`plot_id_x`, `plot_id_z`, `owner`, `world`, `timestamp`) values "; + CREATE_SETTINGS = "INSERT INTO `" + prefix + "plot_settings` (`plot_plot_id`) values "; + CREATE_TIERS = "INSERT INTO `" + prefix + "plot_%tier%` (`plot_plot_id`, `user_uuid`) values "; + CREATE_PLOT = "INSERT INTO `" + prefix + "plot`(`plot_id_x`, `plot_id_z`, `owner`, `world`, `timestamp`) VALUES(?, ?, ?, ?, ?)"; + CREATE_CLUSTER = "INSERT INTO `" + prefix + "cluster`(`pos1_x`, `pos1_z`, `pos2_x`, `pos2_z`, `owner`, `world`) VALUES(?, ?, ?, ?, ?, ?)"; + updateTables(); + createTables(); + } + + public synchronized Queue getGlobalTasks() { + return globalTasks; + } + + public synchronized Queue getNotifyTasks() { + return notifyTasks; + } + + public synchronized void addPlotTask(Plot plot, UniqueStatement task) { + if (plot == null) { + plot = new Plot(null, new PlotId(Integer.MAX_VALUE, Integer.MAX_VALUE)); + } + Queue tasks = plotTasks.get(plot); + if (tasks == null) { + tasks = new ConcurrentLinkedQueue<>(); + plotTasks.put(plot, tasks); + } + if (task == null) { + task = new UniqueStatement(plot.hashCode() + "") { + + @Override + public PreparedStatement get() { + return null; + } + + @Override + public void set(final PreparedStatement stmt) {} + + @Override + public void addBatch(final PreparedStatement stmt) {} + + @Override + public void execute(final PreparedStatement stmt) {} + + }; + } + tasks.add(task); + } + + public synchronized void addPlayerTask(UUID uuid, UniqueStatement task) { + if (uuid == null) { + return; + } + Queue tasks = playerTasks.get(uuid); + if (tasks == null) { + tasks = new ConcurrentLinkedQueue<>(); + playerTasks.put(uuid, tasks); + } + if (task == null) { + task = new UniqueStatement(uuid.hashCode() + "") { + + @Override + public PreparedStatement get() { + return null; + } + + @Override + public void set(final PreparedStatement stmt) {} + + @Override + public void addBatch(final PreparedStatement stmt) {} + + @Override + public void execute(final PreparedStatement stmt) {} + + }; + } + tasks.add(task); + } + + public synchronized void addClusterTask(final PlotCluster cluster, UniqueStatement task) { + Queue tasks = clusterTasks.get(cluster); + if (tasks == null) { + tasks = new ConcurrentLinkedQueue<>(); + clusterTasks.put(cluster, tasks); + } + if (task == null) { + task = new UniqueStatement(cluster.hashCode() + "") { + + @Override + public PreparedStatement get() { + return null; + } + + @Override + public void set(final PreparedStatement stmt) {} + + @Override + public void addBatch(final PreparedStatement stmt) {} + + @Override + public void execute(final PreparedStatement stmt) {} + + }; + } + tasks.add(task); + } + + public synchronized void addGlobalTask(final Runnable task) { + getGlobalTasks().add(task); + } + + public synchronized void addNotifyTask(final Runnable task) { + if (task != null) { + getNotifyTasks().add(task); + } + } + + public boolean sendBatch() { + try { + if (!getGlobalTasks().isEmpty()) { + if (connection.getAutoCommit()) { + connection.setAutoCommit(false); + } + final Runnable task = getGlobalTasks().remove(); + if (task != null) { + task.run(); + } + commit(); + return true; + } + int count = -1; + if (!plotTasks.isEmpty()) { + count = 0; + if (connection.getAutoCommit()) { + connection.setAutoCommit(false); + } + String method = null; + PreparedStatement stmt = null; + UniqueStatement task = null; + UniqueStatement lastTask = null; + for (final Entry> entry : plotTasks.entrySet()) { + final Plot plot = entry.getKey(); + if (plotTasks.get(plot).isEmpty()) { + plotTasks.remove(plot); + continue; + } + task = plotTasks.get(plot).remove(); + count++; + if (task != null) { + if (task._method == null || !task._method.equals(method)) { + if (stmt != null) { + lastTask.execute(stmt); + stmt.close(); + } + method = task._method; + stmt = task.get(); + } + task.set(stmt); + task.addBatch(stmt); + } + lastTask = task; + } + if (stmt != null && task != null) { + task.execute(stmt); + stmt.close(); + } + } + if (!playerTasks.isEmpty()) { + count = 0; + if (connection.getAutoCommit()) { + connection.setAutoCommit(false); + } + String method = null; + PreparedStatement stmt = null; + UniqueStatement task = null; + UniqueStatement lastTask = null; + for (final Entry> entry : playerTasks.entrySet()) { + final UUID uuid = entry.getKey(); + if (playerTasks.get(uuid).isEmpty()) { + playerTasks.remove(uuid); + continue; + } + task = playerTasks.get(uuid).remove(); + count++; + if (task != null) { + if (task._method == null || !task._method.equals(method)) { + if (stmt != null) { + lastTask.execute(stmt); + stmt.close(); + } + method = task._method; + stmt = task.get(); + } + task.set(stmt); + task.addBatch(stmt); + } + lastTask = task; + } + if (stmt != null && task != null) { + task.execute(stmt); + stmt.close(); + } + } + if (!clusterTasks.isEmpty()) { + count = 0; + if (connection.getAutoCommit()) { + connection.setAutoCommit(false); + } + String method = null; + PreparedStatement stmt = null; + UniqueStatement task = null; + UniqueStatement lastTask = null; + for (final Entry> entry : clusterTasks.entrySet()) { + final PlotCluster cluster = entry.getKey(); + if (clusterTasks.get(cluster).isEmpty()) { + clusterTasks.remove(cluster); + continue; + } + task = clusterTasks.get(cluster).remove(); + count++; + if (task != null) { + if (task._method == null || !task._method.equals(method)) { + if (stmt != null) { + lastTask.execute(stmt); + stmt.close(); + } + method = task._method; + stmt = task.get(); + } + task.set(stmt); + task.addBatch(stmt); + } + lastTask = task; + } + if (stmt != null && task != null) { + task.execute(stmt); + stmt.close(); + } + } + if (count > 0) { + commit(); + return true; + } else if (count != -1) { + if (!connection.getAutoCommit()) { + connection.setAutoCommit(true); + } + } + if (!clusterTasks.isEmpty()) { + clusterTasks.clear(); + } + if (!plotTasks.isEmpty()) { + plotTasks.clear(); + } + } catch (SQLException e) { + e.printStackTrace(); + } + return false; + } + + public Connection getConnection() { + return connection; + } + + /** + * Set Plot owner + * + * @param plot Plot Object + * @param uuid Owner UUID + */ + @Override + public void setOwner(final Plot plot, final UUID uuid) { + addPlotTask(plot, new UniqueStatement("setOwner") { + @Override + public void set(final PreparedStatement statement) throws SQLException { + statement.setString(1, uuid.toString()); + statement.setInt(2, plot.getId().x); + statement.setInt(3, plot.getId().y); + statement.setString(4, plot.getArea().toString()); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement(SET_OWNER); + } + }); + } + + @Override + public void createPlotsAndData(final ArrayList myList, final Runnable whenDone) { + addGlobalTask(new Runnable() { + @Override + public void run() { + try { + // Create the plots + createPlots(myList, new Runnable() { + @Override + public void run() { + try { + // Creating datastructures + final HashMap plotMap = new HashMap<>(); + for (final Plot plot : myList) { + plotMap.put(plot.getId(), plot); + } + final ArrayList settings = new ArrayList<>(); + final ArrayList helpers = new ArrayList<>(); + final ArrayList trusted = new ArrayList<>(); + final ArrayList denied = new ArrayList<>(); + + // Populating structures + try (PreparedStatement stmt = connection.prepareStatement(GET_ALL_PLOTS); ResultSet result = stmt.executeQuery()) { + while (result.next()) { + final int id = result.getInt("id"); + final int x = result.getInt("plot_id_x"); + final int y = result.getInt("plot_id_z"); + final PlotId plotId = new PlotId(x, y); + final Plot plot = plotMap.get(plotId); + if (plot != null) { + settings.add(new SettingsPair(id, plot.getSettings())); + if (plot.getDenied() != null) { + for (final UUID uuid : plot.getDenied()) { + denied.add(new UUIDPair(id, uuid)); + } + } + if (plot.getMembers() != null) { + for (final UUID uuid : plot.getMembers()) { + trusted.add(new UUIDPair(id, uuid)); + } + } + if (plot.getTrusted() != null) { + for (final UUID uuid : plot.getTrusted()) { + helpers.add(new UUIDPair(id, uuid)); + } + } + } + } + } + createSettings(settings, new Runnable() { + @Override + public void run() { + createTiers(helpers, "helpers", new Runnable() { + @Override + public void run() { + createTiers(trusted, "trusted", new Runnable() { + @Override + public void run() { + createTiers(denied, "denied", new Runnable() { + @Override + public void run() { + try { + connection.commit(); + } catch (final SQLException e) { + e.printStackTrace(); + } + if (whenDone != null) { + whenDone.run(); + } + } + }); + } + }); + } + }); + } + }); + } catch (final SQLException e) { + e.printStackTrace(); + PS.debug("&7[WARN] " + "Failed to set all helpers for plots"); + try { + connection.commit(); + } catch (final SQLException e1) { + e1.printStackTrace(); + } + } + } + }); + } catch (final Exception e) { + e.printStackTrace(); + PS.debug("&7[WARN] " + "Failed to set all helpers for plots"); + try { + connection.commit(); + } catch (final SQLException e1) { + e1.printStackTrace(); + } + } + } + }); + } + + /** + * Create a plot + * + * @param myList list of plots to be created + */ + public void createTiers(final ArrayList myList, final String tier, final Runnable whenDone) { + final StmtMod mod = new StmtMod() { + @Override + public String getCreateMySQL(final int size) { + return getCreateMySQL(size, CREATE_TIERS.replaceAll("%tier%", tier), 2); + } + + @Override + public String getCreateSQLite(final int size) { + return getCreateSQLite(size, "INSERT INTO `" + prefix + "plot_" + tier + "` SELECT ? AS `plot_plot_id`, ? AS `user_uuid`", 2); + } + + @Override + public String getCreateSQL() { + return "INSERT INTO `" + prefix + "plot_" + tier + "` (`plot_plot_id`, `user_uuid`) VALUES(?,?)"; + } + + @Override + public void setMySQL(final PreparedStatement stmt, final int i, final UUIDPair pair) throws SQLException { + stmt.setInt((i * 2) + 1, pair.id); + stmt.setString((i * 2) + 2, pair.uuid.toString()); + } + + @Override + public void setSQLite(final PreparedStatement stmt, final int i, final UUIDPair pair) throws SQLException { + stmt.setInt((i * 2) + 1, pair.id); + stmt.setString((i * 2) + 2, pair.uuid.toString()); + } + + @Override + public void setSQL(final PreparedStatement stmt, final UUIDPair pair) throws SQLException { + stmt.setInt(1, pair.id); + stmt.setString(2, pair.uuid.toString()); + } + }; + setBulk(myList, mod, whenDone); + } + + /** + * Create a plot + * + * @param myList list of plots to be created + */ + public void createPlots(final ArrayList myList, final Runnable whenDone) { + final StmtMod mod = new StmtMod() { + @Override + public String getCreateMySQL(final int size) { + return getCreateMySQL(size, CREATE_PLOTS, 5); + } + + @Override + public String getCreateSQLite(final int size) { + return getCreateSQLite(size, "INSERT INTO `" + prefix + + "plot` SELECT ? AS `id`, ? AS `plot_id_x`, ? AS `plot_id_z`, ? AS `owner`, ? AS `world`, ? AS `timestamp` ", 6); + } + + @Override + public String getCreateSQL() { + return CREATE_PLOT; + } + + @Override + public void setMySQL(final PreparedStatement stmt, final int i, final Plot plot) throws SQLException { + stmt.setInt((i * 5) + 1, plot.getId().x); + stmt.setInt((i * 5) + 2, plot.getId().y); + try { + stmt.setString((i * 5) + 3, plot.owner.toString()); + } catch (SQLException e) { + stmt.setString((i * 5) + 3, everyone.toString()); + } + stmt.setString((i * 5) + 4, plot.getArea().toString()); + stmt.setTimestamp((i * 5) + 5, new Timestamp(plot.getTimestamp())); + } + + @Override + public void setSQLite(final PreparedStatement stmt, final int i, final Plot plot) throws SQLException { + stmt.setNull((i * 6) + 1, 4); + stmt.setInt((i * 6) + 2, plot.getId().x); + stmt.setInt((i * 6) + 3, plot.getId().y); + try { + stmt.setString((i * 6) + 4, plot.owner.toString()); + } catch (SQLException e1) { + stmt.setString((i * 6) + 4, everyone.toString()); + } + stmt.setString((i * 6) + 5, plot.getArea().toString()); + stmt.setTimestamp((i * 6) + 6, new Timestamp(plot.getTimestamp())); + } + + @Override + public void setSQL(final PreparedStatement stmt, final Plot plot) throws SQLException { + stmt.setInt(1, plot.getId().x); + stmt.setInt(2, plot.getId().y); + stmt.setString(3, plot.owner.toString()); + stmt.setString(4, plot.getArea().toString()); + stmt.setTimestamp(5, new Timestamp(plot.getTimestamp())); + + } + }; + setBulk(myList, mod, whenDone); + } + + public void setBulk(final ArrayList objList, final StmtMod mod, final Runnable whenDone) { + final int size = objList.size(); + if (size == 0) { + if (whenDone != null) { + whenDone.run(); + } + return; + } + int packet; + if (MYSQL) { + packet = Math.min(size, 5000); + } else { + packet = Math.min(size, 50); + } + final int amount = size / packet; + try { + int count = 0; + PreparedStatement preparedStmt = null; + int last = -1; + for (int j = 0; j <= amount; j++) { + final List subList = objList.subList(j * packet, Math.min(size, (j + 1) * packet)); + if (subList.isEmpty()) { + break; + } + String statement; + if (last == -1) { + last = subList.size(); + statement = mod.getCreateMySQL(subList.size()); + preparedStmt = connection.prepareStatement(statement); + } + if ((subList.size() != last) || (((count % 5000) == 0) && (count > 0))) { + preparedStmt.executeBatch(); + preparedStmt.close(); + statement = mod.getCreateMySQL(subList.size()); + preparedStmt = connection.prepareStatement(statement); + } + for (int i = 0; i < subList.size(); i++) { + count++; + final T obj = subList.get(i); + mod.setMySQL(preparedStmt, i, obj); + } + last = subList.size(); + preparedStmt.addBatch(); + } + PS.debug("&aBatch 1: " + count + " | " + objList.get(0).getClass().getCanonicalName()); + preparedStmt.executeBatch(); + preparedStmt.clearParameters(); + preparedStmt.close(); + if (whenDone != null) { + whenDone.run(); + } + return; + } catch (SQLException e) { + if (MYSQL) { + e.printStackTrace(); + PS.debug("&cERROR 1: " + " | " + objList.get(0).getClass().getCanonicalName()); + } + } + try { + int count = 0; + PreparedStatement preparedStmt = null; + int last = -1; + for (int j = 0; j <= amount; j++) { + final List subList = objList.subList(j * packet, Math.min(size, (j + 1) * packet)); + if (subList.isEmpty()) { + break; + } + String statement; + if (last == -1) { + last = subList.size(); + statement = mod.getCreateSQLite(subList.size()); + preparedStmt = connection.prepareStatement(statement); + } + if ((subList.size() != last) || (((count % 5000) == 0) && (count > 0))) { + preparedStmt.executeBatch(); + preparedStmt.clearParameters(); + statement = mod.getCreateSQLite(subList.size()); + preparedStmt = connection.prepareStatement(statement); + } + for (int i = 0; i < subList.size(); i++) { + count++; + final T obj = subList.get(i); + mod.setSQLite(preparedStmt, i, obj); + } + last = subList.size(); + preparedStmt.addBatch(); + } + PS.debug("&aBatch 2: " + count + " | " + objList.get(0).getClass().getCanonicalName()); + preparedStmt.executeBatch(); + preparedStmt.clearParameters(); + preparedStmt.close(); + } catch (SQLException e) { + e.printStackTrace(); + PS.debug("&cERROR 2: " + " | " + objList.get(0).getClass().getCanonicalName()); + PS.debug("&6[WARN] " + "Could not bulk save!"); + try { + final String nonBulk = mod.getCreateSQL(); + PreparedStatement preparedStmt = connection.prepareStatement(nonBulk); + for (final T obj : objList) { + try { + mod.setSQL(preparedStmt, obj); + preparedStmt.addBatch(); + } catch (SQLException e3) { + PS.debug("&c[ERROR] " + "Failed to save " + obj + "!"); + } + } + PS.debug("&aBatch 3"); + preparedStmt.executeBatch(); + preparedStmt.close(); + } catch (SQLException e3) { + e3.printStackTrace(); + PS.debug("&c[ERROR] " + "Failed to save all!"); + } + } + if (whenDone != null) { + whenDone.run(); + } + } + + public void createSettings(final ArrayList myList, final Runnable whenDone) { + final StmtMod mod = new StmtMod() { + @Override + public String getCreateMySQL(final int size) { + return getCreateMySQL(size, "INSERT INTO `" + prefix + "plot_settings`(`plot_plot_id`,`biome`,`rain`,`custom_time`,`time`,`deny_entry`,`alias`,`flags`,`merged`,`position`) VALUES ", + 10); + } + + @Override + public String getCreateSQLite(final int size) { + return getCreateSQLite( + size, + "INSERT INTO `" + + prefix + + "plot_settings` SELECT ? AS `plot_plot_id`, ? AS `biome`, ? AS `rain`, ? AS `custom_time`, ? AS `time`, ? AS `deny_entry`, ? AS `alias`, ? AS `flags`, ? AS `merged`, ? AS `position`", + 10); + } + + @Override + public String getCreateSQL() { + return "INSERT INTO `" + prefix + "plot_settings`(`plot_plot_id`) VALUES(?)"; + } + + @Override + public void setMySQL(final PreparedStatement stmt, final int i, final SettingsPair pair) throws SQLException { + stmt.setInt((i * 10) + 1, pair.id); // id + stmt.setNull((i * 10) + 2, 4); // biome + stmt.setNull((i * 10) + 3, 4); // rain + stmt.setNull((i * 10) + 4, 4); // custom_time + stmt.setNull((i * 10) + 5, 4); // time + stmt.setNull((i * 10) + 6, 4); // deny_entry + if (pair.settings.getAlias().equals("")) { + stmt.setNull((i * 10) + 7, 4); + } else { + stmt.setString((i * 10) + 7, pair.settings.getAlias()); + } + if (pair.settings.flags == null) { + stmt.setNull((i * 10) + 8, 4); + } else { + final StringBuilder flag_string = new StringBuilder(); + int k = 0; + for (final Flag flag : pair.settings.flags.values()) { + if (k != 0) { + flag_string.append(","); + } + flag_string.append(flag.getKey() + ":" + flag.getValueString().replaceAll(":", "\u00AF").replaceAll(",", "\u00B4")); + k++; + } + stmt.setString((i * 10) + 8, flag_string.toString()); + } + final boolean[] merged = pair.settings.getMerged(); + int hash = MainUtil.hash(merged); + stmt.setInt((i * 10) + 9, hash); + final BlockLoc loc = pair.settings.getPosition(); + String position; + if (loc.y == 0) { + position = "DEFAULT"; + } else { + position = loc.x + "," + loc.y + "," + loc.z; + } + stmt.setString((i * 10) + 10, position); + } + + @Override + public void setSQLite(final PreparedStatement stmt, final int i, final SettingsPair pair) throws SQLException { + stmt.setInt((i * 10) + 1, pair.id); // id + stmt.setNull((i * 10) + 2, 4); // biome + stmt.setNull((i * 10) + 3, 4); // rain + stmt.setNull((i * 10) + 4, 4); // custom_time + stmt.setNull((i * 10) + 5, 4); // time + stmt.setNull((i * 10) + 6, 4); // deny_entry + if (pair.settings.getAlias().equals("")) { + stmt.setNull((i * 10) + 7, 4); + } else { + stmt.setString((i * 10) + 7, pair.settings.getAlias()); + } + if (pair.settings.flags == null) { + stmt.setNull((i * 10) + 8, 4); + } else { + final StringBuilder flag_string = new StringBuilder(); + int k = 0; + for (final Flag flag : pair.settings.flags.values()) { + if (k != 0) { + flag_string.append(","); + } + flag_string.append(flag.getKey() + ":" + flag.getValueString().replaceAll(":", "\u00AF").replaceAll(",", "\u00B4")); + k++; + } + stmt.setString((i * 10) + 8, flag_string.toString()); + } + final boolean[] merged = pair.settings.getMerged(); + int n = 0; + for (int j = 0; j < 4; ++j) { + n = (n << 1) + (merged[j] ? 1 : 0); + } + stmt.setInt((i * 10) + 9, n); + final BlockLoc loc = pair.settings.getPosition(); + String position; + if (loc.y == 0) { + position = "DEFAULT"; + } else { + position = loc.x + "," + loc.y + "," + loc.z; + } + stmt.setString((i * 10) + 10, position); + } + + @Override + public void setSQL(final PreparedStatement stmt, final SettingsPair pair) throws SQLException { + stmt.setInt(1, pair.id); + } + }; + addGlobalTask(new Runnable() { + @Override + public void run() { + setBulk(myList, mod, whenDone); + } + }); + } + + public void createEmptySettings(final ArrayList myList, final Runnable whenDone) { + final StmtMod mod = new StmtMod() { + @Override + public String getCreateMySQL(final int size) { + return getCreateMySQL(size, CREATE_SETTINGS, 1); + } + + @Override + public String getCreateSQLite(final int size) { + return getCreateSQLite( + size, + "INSERT INTO `" + + prefix + + "plot_settings` SELECT ? AS `plot_plot_id`, ? AS `biome`, ? AS `rain`, ? AS `custom_time`, ? AS `time`, ? AS `deny_entry`, ? AS `alias`, ? AS `flags`, ? AS `merged`, ? AS `position` ", + 10); + } + + @Override + public String getCreateSQL() { + return "INSERT INTO `" + prefix + "plot_settings`(`plot_plot_id`) VALUES(?)"; + } + + @Override + public void setMySQL(final PreparedStatement stmt, final int i, final Integer id) throws SQLException { + stmt.setInt((i) + 1, id); + } + + @Override + public void setSQLite(final PreparedStatement stmt, final int i, final Integer id) throws SQLException { + stmt.setInt((i * 10) + 1, id); + stmt.setNull((i * 10) + 2, 4); + stmt.setNull((i * 10) + 3, 4); + stmt.setNull((i * 10) + 4, 4); + stmt.setNull((i * 10) + 5, 4); + stmt.setNull((i * 10) + 6, 4); + stmt.setNull((i * 10) + 7, 4); + stmt.setNull((i * 10) + 8, 4); + stmt.setNull((i * 10) + 9, 4); + stmt.setString((i * 10) + 10, "DEFAULT"); + } + + @Override + public void setSQL(final PreparedStatement stmt, final Integer id) throws SQLException { + stmt.setInt(1, id); + } + }; + addGlobalTask(new Runnable() { + @Override + public void run() { + setBulk(myList, mod, whenDone); + } + }); + } + + /** + * Create a plot + * + * @param plot + */ + @Override + public void createPlot(final Plot plot) { + addPlotTask(plot, new UniqueStatement("createPlot") { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + stmt.setInt(1, plot.getId().x); + stmt.setInt(2, plot.getId().y); + stmt.setString(3, plot.owner.toString()); + stmt.setString(4, plot.getArea().toString()); + stmt.setTimestamp(5, new Timestamp(plot.getTimestamp())); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement(CREATE_PLOT); + } + }); + } + + public void commit() { + try { + if (CLOSED) { + return; + } + if (!connection.getAutoCommit()) { + connection.commit(); + connection.setAutoCommit(true); + } + } catch (final SQLException e) { + e.printStackTrace(); + } + } + + @Override + public void createPlotAndSettings(final Plot plot, final Runnable whenDone) { + addPlotTask(plot, new UniqueStatement("createPlotAndSettings_" + plot.hashCode()) { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + stmt.setInt(1, plot.getId().x); + stmt.setInt(2, plot.getId().y); + stmt.setString(3, plot.owner.toString()); + stmt.setString(4, plot.getArea().toString()); + stmt.setTimestamp(5, new Timestamp(plot.getTimestamp())); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement(CREATE_PLOT, Statement.RETURN_GENERATED_KEYS); + } + + @Override + public void execute(final PreparedStatement stmt) { + + } + + @Override + public void addBatch(final PreparedStatement stmt) throws SQLException { + stmt.executeUpdate(); + final ResultSet keys = stmt.getGeneratedKeys(); + if (keys.next()) { + plot.temp = keys.getInt(1); + } + } + }); + addPlotTask(plot, new UniqueStatement("createPlotAndSettings_settings_" + plot.hashCode()) { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + stmt.setInt(1, getId(plot)); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("INSERT INTO `" + prefix + "plot_settings`(`plot_plot_id`) VALUES(" + "?)"); + } + }); + addNotifyTask(whenDone); + } + + /** + * Create tables + * + * @throws SQLException + */ + @Override + public void createTables() throws SQLException { + final String[] tables; + if (Settings.ENABLE_CLUSTERS) { + tables = new String[] { "plot", "plot_denied", "plot_helpers", "plot_comments", "plot_trusted", "plot_rating", "plot_settings", "cluster", "player_meta" }; + } else { + tables = new String[] { "plot", "plot_denied", "plot_helpers", "plot_comments", "plot_trusted", "plot_rating", "plot_settings", "player_meta" }; + } + final DatabaseMetaData meta = connection.getMetaData(); + int create = 0; + for (final String s : tables) { + final ResultSet set = meta.getTables(null, null, prefix + s, new String[] { "TABLE" }); + // ResultSet set = meta.getTables(null, null, prefix + s, null); + if (!set.next()) { + create++; + } + set.close(); + } + if (create == 0) { + return; + } + boolean add_constraint = create == tables.length; + PS.debug("Creating tables"); + final Statement stmt = connection.createStatement(); + if (MYSQL) { + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + + prefix + + "plot` (" + + "`id` INT(11) NOT NULL AUTO_INCREMENT," + + "`plot_id_x` INT(11) NOT NULL," + + "`plot_id_z` INT(11) NOT NULL," + + "`owner` VARCHAR(40) NOT NULL," + + "`world` VARCHAR(45) NOT NULL," + + "`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP," + + "PRIMARY KEY (`id`)" + + ") ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=0"); + stmt + .addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "plot_denied` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + + prefix + + "plot_helpers` (" + + "`plot_plot_id` INT(11) NOT NULL," + + "`user_uuid` VARCHAR(40) NOT NULL" + + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + + prefix + + "plot_comments` (" + + "`world` VARCHAR(40) NOT NULL, `hashcode` INT(11) NOT NULL," + + "`comment` VARCHAR(40) NOT NULL," + + "`inbox` VARCHAR(40) NOT NULL," + + "`timestamp` INT(11) NOT NULL," + + "`sender` VARCHAR(40) NOT NULL" + + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + + prefix + + "plot_trusted` (" + + "`plot_plot_id` INT(11) NOT NULL," + + "`user_uuid` VARCHAR(40) NOT NULL" + + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + + prefix + + "plot_settings` (" + + " `plot_plot_id` INT(11) NOT NULL," + + " `biome` VARCHAR(45) DEFAULT 'FOREST'," + + " `rain` INT(1) DEFAULT 0," + + " `custom_time` TINYINT(1) DEFAULT '0'," + + " `time` INT(11) DEFAULT '8000'," + + " `deny_entry` TINYINT(1) DEFAULT '0'," + + " `alias` VARCHAR(50) DEFAULT NULL," + + " `flags` VARCHAR(512) DEFAULT NULL," + + " `merged` INT(11) DEFAULT NULL," + + " `position` VARCHAR(50) NOT NULL DEFAULT 'DEFAULT'," + + " PRIMARY KEY (`plot_plot_id`)," + + " UNIQUE KEY `unique_alias` (`alias`)" + + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + + prefix + + "plot_rating` ( `plot_plot_id` INT(11) NOT NULL, `rating` INT(2) NOT NULL, `player` VARCHAR(40) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8"); + if (add_constraint) { + stmt.addBatch("ALTER TABLE `" + + prefix + + "plot_settings` ADD CONSTRAINT `" + + prefix + + "plot_settings_ibfk_1` FOREIGN KEY (`plot_plot_id`) REFERENCES `" + + prefix + + "plot` (`id`) ON DELETE CASCADE"); + } + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + + prefix + + "cluster` (" + + "`id` INT(11) NOT NULL AUTO_INCREMENT," + + "`pos1_x` INT(11) NOT NULL," + + "`pos1_z` INT(11) NOT NULL," + + "`pos2_x` INT(11) NOT NULL," + + "`pos2_z` INT(11) NOT NULL," + + "`owner` VARCHAR(40) NOT NULL," + + "`world` VARCHAR(45) NOT NULL," + + "`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP," + + "PRIMARY KEY (`id`)" + + ") ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=0"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + + prefix + + "cluster_helpers` (" + + "`cluster_id` INT(11) NOT NULL," + + "`user_uuid` VARCHAR(40) NOT NULL" + + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + + prefix + + "cluster_invited` (" + + "`cluster_id` INT(11) NOT NULL," + + "`user_uuid` VARCHAR(40) NOT NULL" + + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + + prefix + + "cluster_settings` (" + + " `cluster_id` INT(11) NOT NULL," + + " `biome` VARCHAR(45) DEFAULT 'FOREST'," + + " `rain` INT(1) DEFAULT 0," + + " `custom_time` TINYINT(1) DEFAULT '0'," + + " `time` INT(11) DEFAULT '8000'," + + " `deny_entry` TINYINT(1) DEFAULT '0'," + + " `alias` VARCHAR(50) DEFAULT NULL," + + " `flags` VARCHAR(512) DEFAULT NULL," + + " `merged` INT(11) DEFAULT NULL," + + " `position` VARCHAR(50) NOT NULL DEFAULT 'DEFAULT'," + + " PRIMARY KEY (`cluster_id`)" + + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + + prefix + + "player_meta` (" + + " `meta_id` INT(11) NOT NULL AUTO_INCREMENT," + + " `uuid` VARCHAR(40) NOT NULL," + + " `key` VARCHAR(32) NOT NULL," + + " `value` blob NOT NULL," + + " PRIMARY KEY (`meta_id`)" + + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); + } else { + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + + prefix + + "plot` (" + + "`id` INTEGER PRIMARY KEY AUTOINCREMENT," + + "`plot_id_x` INT(11) NOT NULL," + + "`plot_id_z` INT(11) NOT NULL," + + "`owner` VARCHAR(45) NOT NULL," + + "`world` VARCHAR(45) NOT NULL," + + "`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP)"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "plot_denied` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ")"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "plot_helpers` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ")"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "plot_trusted` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ")"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + + prefix + + "plot_comments` (" + + "`world` VARCHAR(40) NOT NULL, `hashcode` INT(11) NOT NULL," + + "`comment` VARCHAR(40) NOT NULL," + + "`inbox` VARCHAR(40) NOT NULL, `timestamp` INT(11) NOT NULL," + + "`sender` VARCHAR(40) NOT NULL" + + ")"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + + prefix + + "plot_settings` (" + + " `plot_plot_id` INT(11) NOT NULL," + + " `biome` VARCHAR(45) DEFAULT 'FOREST'," + + " `rain` INT(1) DEFAULT 0," + + " `custom_time` TINYINT(1) DEFAULT '0'," + + " `time` INT(11) DEFAULT '8000'," + + " `deny_entry` TINYINT(1) DEFAULT '0'," + + " `alias` VARCHAR(50) DEFAULT NULL," + + " `flags` VARCHAR(512) DEFAULT NULL," + + " `merged` INT(11) DEFAULT NULL," + + " `position` VARCHAR(50) NOT NULL DEFAULT 'DEFAULT'," + + " PRIMARY KEY (`plot_plot_id`)" + + ")"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "plot_rating` (`plot_plot_id` INT(11) NOT NULL, `rating` INT(2) NOT NULL, `player` VARCHAR(40) NOT NULL)"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + + prefix + + "cluster` (" + + "`id` INTEGER PRIMARY KEY AUTOINCREMENT," + + "`pos1_x` INT(11) NOT NULL," + + "`pos1_z` INT(11) NOT NULL," + + "`pos2_x` INT(11) NOT NULL," + + "`pos2_z` INT(11) NOT NULL," + + "`owner` VARCHAR(40) NOT NULL," + + "`world` VARCHAR(45) NOT NULL," + + "`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP" + + ")"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "cluster_helpers` (" + "`cluster_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ")"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "cluster_invited` (" + "`cluster_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ")"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + + prefix + + "cluster_settings` (" + + " `cluster_id` INT(11) NOT NULL," + + " `biome` VARCHAR(45) DEFAULT 'FOREST'," + + " `rain` INT(1) DEFAULT 0," + + " `custom_time` TINYINT(1) DEFAULT '0'," + + " `time` INT(11) DEFAULT '8000'," + + " `deny_entry` TINYINT(1) DEFAULT '0'," + + " `alias` VARCHAR(50) DEFAULT NULL," + + " `flags` VARCHAR(512) DEFAULT NULL," + + " `merged` INT(11) DEFAULT NULL," + + " `position` VARCHAR(50) NOT NULL DEFAULT 'DEFAULT'," + + " PRIMARY KEY (`cluster_id`)" + + ")"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + + prefix + + "player_meta` (" + + " `meta_id` INTEGER PRIMARY KEY AUTOINCREMENT," + + " `uuid` VARCHAR(40) NOT NULL," + + " `key` VARCHAR(32) NOT NULL," + + " `value` blob NOT NULL" + + ")"); + } + stmt.executeBatch(); + stmt.clearBatch(); + stmt.close(); + } + + @Override + public void deleteSettings(final Plot plot) { + if (plot.settings == null) { + return; + } + addPlotTask(plot, new UniqueStatement("delete_plot_settings") { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + stmt.setInt(1, getId(plot)); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("DELETE FROM `" + prefix + "plot_settings` WHERE `plot_plot_id` = ?"); + } + }); + } + + @Override + public void deleteHelpers(final Plot plot) { + if (plot.getTrusted().isEmpty()) { + return; + } + addPlotTask(plot, new UniqueStatement("delete_plot_helpers") { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + stmt.setInt(1, getId(plot)); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("DELETE FROM `" + prefix + "plot_helpers` WHERE `plot_plot_id` = ?"); + } + }); + } + + @Override + public void deleteTrusted(final Plot plot) { + if (plot.getMembers().isEmpty()) { + return; + } + addPlotTask(plot, new UniqueStatement("delete_plot_trusted") { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + stmt.setInt(1, getId(plot)); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("DELETE FROM `" + prefix + "plot_trusted` WHERE `plot_plot_id` = ?"); + } + }); + } + + @Override + public void deleteDenied(final Plot plot) { + if (plot.getDenied().isEmpty()) { + return; + } + addPlotTask(plot, new UniqueStatement("delete_plot_denied") { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + stmt.setInt(1, getId(plot)); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("DELETE FROM `" + prefix + "plot_denied` WHERE `plot_plot_id` = ?"); + } + }); + } + + @Override + public void deleteComments(final Plot plot) { + addPlotTask(plot, new UniqueStatement("delete_plot_comments") { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + stmt.setString(1, plot.getArea().toString()); + stmt.setInt(2, plot.hashCode()); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("DELETE FROM `" + prefix + "plot_comments` WHERE `world` = ? AND `hashcode` = ?"); + } + }); + } + + @Override + public void deleteRatings(final Plot plot) { + if (Settings.CACHE_RATINGS && plot.getSettings().getRatings().isEmpty()) { + return; + } + addPlotTask(plot, new UniqueStatement("delete_plot_ratings") { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + stmt.setInt(1, getId(plot)); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("DELETE FROM `" + prefix + "plot_rating` WHERE `plot_plot_id` = ?"); + } + }); + } + + /** + * Delete a plot + * + * @param plot + */ + @Override + public void delete(final Plot plot) { + deleteSettings(plot); + deleteDenied(plot); + deleteHelpers(plot); + deleteTrusted(plot); + deleteComments(plot); + deleteRatings(plot); + addPlotTask(plot, new UniqueStatement("delete_plot") { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + stmt.setInt(1, getId(plot)); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("DELETE FROM `" + prefix + "plot` WHERE `id` = ?"); + } + }); + } + + /** + * Create plot settings + * + * @param id + * @param plot + */ + @Override + public void createPlotSettings(final int id, final Plot plot) { + addPlotTask(plot, new UniqueStatement("createPlotSettings") { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + stmt.setInt(1, id); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("INSERT INTO `" + prefix + "plot_settings`(`plot_plot_id`) VALUES(" + "?)"); + } + }); + } + + @Override + public int getClusterId(final PlotCluster cluster) { + if (cluster.temp > 0) { + return cluster.temp; + } + try { + commit(); + if (cluster.temp > 0) { + return cluster.temp; + } + PreparedStatement stmt = connection.prepareStatement("SELECT `id` FROM `" + + prefix + + "cluster` WHERE `pos1_x` = ? AND `pos1_z` = ? AND `pos2_x` = ? AND `pos2_z` = ? AND `world` = ? ORDER BY `timestamp` ASC"); + stmt.setInt(1, cluster.getP1().x); + stmt.setInt(2, cluster.getP1().y); + stmt.setInt(3, cluster.getP2().x); + stmt.setInt(4, cluster.getP2().y); + stmt.setString(5, cluster.area.toString()); + final ResultSet r = stmt.executeQuery(); + int c_id = Integer.MAX_VALUE; + while (r.next()) { + c_id = r.getInt("id"); + } + stmt.close(); + r.close(); + if ((c_id == Integer.MAX_VALUE) || (c_id == 0)) { + if (cluster.temp > 0) { + return cluster.temp; + } + throw new SQLException("Cluster does not exist in database"); + } + cluster.temp = c_id; + return c_id; + } catch (final SQLException e) { + e.printStackTrace(); + } + return Integer.MAX_VALUE; + } + + @Override + public int getId(final Plot plot) { + if (plot.temp > 0) { + return plot.temp; + } + try { + commit(); + if (plot.temp > 0) { + return plot.temp; + } + PreparedStatement stmt = connection.prepareStatement( + "SELECT `id` FROM `" + prefix + "plot` WHERE `plot_id_x` = ? AND `plot_id_z` = ? AND world = ? ORDER BY `timestamp` ASC"); + stmt.setInt(1, plot.getId().x); + stmt.setInt(2, plot.getId().y); + stmt.setString(3, plot.getArea().toString()); + final ResultSet r = stmt.executeQuery(); + int id = Integer.MAX_VALUE; + while (r.next()) { + id = r.getInt("id"); + } + r.close(); + stmt.close(); + if ((id == Integer.MAX_VALUE) || (id == 0)) { + if (plot.temp > 0) { + return plot.temp; + } + throw new SQLException("Plot does not exist in database"); + } + plot.temp = id; + return id; + } catch (final SQLException e) { + e.printStackTrace(); + } + return Integer.MAX_VALUE; + } + + public void updateTables() { + if (PS.get().getVersion().equals(PS.get().getLastVersion()) || (PS.get().getLastVersion() == null)) { + return; + } + try { + final DatabaseMetaData data = connection.getMetaData(); + ResultSet rs = data.getColumns(null, null, prefix + "plot_comments", "plot_plot_id"); + if (rs.next()) { + rs.close(); + rs = data.getColumns(null, null, prefix + "plot_comments", "hashcode"); + if (!rs.next()) { + rs.close(); + try { + final Statement statement = connection.createStatement(); + statement.addBatch("DROP TABLE `" + prefix + "plot_comments`"); + if (Settings.DB.USE_MYSQL) { + statement.addBatch("CREATE TABLE IF NOT EXISTS `" + + prefix + + "plot_comments` (" + + "`world` VARCHAR(40) NOT NULL, `hashcode` INT(11) NOT NULL," + + "`comment` VARCHAR(40) NOT NULL," + + "`inbox` VARCHAR(40) NOT NULL," + + "`timestamp` INT(11) NOT NULL," + + "`sender` VARCHAR(40) NOT NULL" + + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); + } else { + statement.addBatch("CREATE TABLE IF NOT EXISTS `" + + prefix + + "plot_comments` (" + + "`world` VARCHAR(40) NOT NULL, `hashcode` INT(11) NOT NULL," + + "`comment` VARCHAR(40) NOT NULL," + + "`inbox` VARCHAR(40) NOT NULL, `timestamp` INT(11) NOT NULL," + + "`sender` VARCHAR(40) NOT NULL" + + ")"); + } + statement.executeBatch(); + statement.close(); + } catch (final SQLException e) { + final Statement statement = connection.createStatement(); + statement.addBatch("ALTER IGNORE TABLE `" + prefix + "plot_comments` ADD `inbox` VARCHAR(11) DEFAULT `public`"); + statement.addBatch("ALTER IGNORE TABLE `" + prefix + "plot_comments` ADD `timestamp` INT(11) DEFAULT 0"); + statement.addBatch("ALTER TABLE `" + prefix + "plot` DROP `tier`"); + statement.executeBatch(); + statement.close(); + } + } + } + rs.close(); + rs = data.getColumns(null, null, prefix + "plot_denied", "plot_plot_id"); + if (rs.next()) { + try (Statement statement = connection.createStatement()) { + statement.executeUpdate( + "DELETE FROM `" + prefix + "plot_denied` WHERE `plot_plot_id` NOT IN (SELECT `id` FROM `" + prefix + "plot`)"); + statement.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + + rs.close(); + try (Statement statement = connection.createStatement()) { + for (final String table : new String[]{"plot_denied", "plot_helpers", "plot_trusted"}) { + final ResultSet result = statement.executeQuery("SELECT plot_plot_id, user_uuid, COUNT(*) FROM " + prefix + table + + " GROUP BY plot_plot_id, user_uuid HAVING COUNT(*) > 1"); + if (result.next()) { + PS.debug("BACKING UP: " + prefix + table); + result.close(); + statement.executeUpdate("CREATE TABLE " + prefix + table + "_tmp AS SELECT * FROM " + prefix + table + + " GROUP BY plot_plot_id, user_uuid"); + statement.executeUpdate("DROP TABLE " + prefix + table); + statement.executeUpdate("CREATE TABLE " + prefix + table + " AS SELECT * FROM " + prefix + table + "_tmp"); + statement.executeUpdate("DROP TABLE " + prefix + table + "_tmp"); + PS.debug("RESTORING: " + prefix + table); + } + } + statement.close(); + } catch (SQLException e2) { + e2.printStackTrace(); + } + } + } catch (SQLException e) { + e.printStackTrace(); + } + + } + + public void deleteRows(final ArrayList rowIds, final String table, final String column) { + setBulk(rowIds, new StmtMod() { + + @Override + public String getCreateMySQL(int size) { + return getCreateMySQL(1, "DELETE FROM `" + table + "` WHERE `" + prefix + column + "` IN ", size); + } + + @Override + public String getCreateSQLite(int size) { + return getCreateMySQL(1, "DELETE FROM `" + table + "` WHERE `" + prefix + column + "` IN ", size); + } + + @Override + public String getCreateSQL() { + return "DELETE FROM `" + table + "` WHERE `" + prefix + column + "` = ?"; + } + + @Override + public void setMySQL(PreparedStatement stmt, int i, Integer obj) throws SQLException { + stmt.setInt((i) + 1, obj); + } + + @Override + public void setSQLite(PreparedStatement stmt, int i, Integer obj) throws SQLException { + stmt.setInt((i) + 1, obj); + } + + @Override + public void setSQL(PreparedStatement stmt, Integer obj) throws SQLException { + stmt.setInt(1, obj); + } + }, null); + } + + /** + * Load all plots, helpers, denied, trusted, and every setting from DB into a hashmap + */ + @Override + public HashMap> getPlots() { + final HashMap> newplots = new HashMap<>(); + final HashMap plots = new HashMap<>(); + try { + HashSet areas = new HashSet<>(); + if (PS.get().config.contains("worlds")) { + ConfigurationSection worldSection = PS.get().config.getConfigurationSection("worlds"); + if (worldSection != null) { + for (String worldKey : worldSection.getKeys(false)) { + areas.add(worldKey); + ConfigurationSection areaSection = worldSection.getConfigurationSection(worldKey + ".areas"); + if (areaSection != null) { + for (String areaKey : areaSection.getKeys(false)) { + String[] split = areaKey.split("-"); + if (split.length == 3) { + areas.add(worldKey + ";" + split[0]); + } + } + } + } + } + } + final HashMap uuids = new HashMap<>(); + final HashMap noExist = new HashMap<>(); + + /* + * Getting plots + */ + Statement stmt = connection.createStatement(); + int id; + String o; + UUID user; + try (ResultSet r = stmt.executeQuery("SELECT `id`, `plot_id_x`, `plot_id_z`, `owner`, `world`, `timestamp` FROM `" + prefix + "plot`")) { + ArrayList toDelete = new ArrayList<>(); + while (r.next()) { + PlotId plot_id = new PlotId(r.getInt("plot_id_x"), r.getInt("plot_id_z")); + id = r.getInt("id"); + final String areaid = r.getString("world"); + if (!areas.contains(areaid)) { + if (Settings.AUTO_PURGE) { + toDelete.add(id); + continue; + } else { + AtomicInteger value = noExist.get(areaid); + if (value != null) { + value.incrementAndGet(); + } else { + noExist.put(areaid, new AtomicInteger(1)); + } + } + } + o = r.getString("owner"); + user = uuids.get(o); + if (user == null) { + user = UUID.fromString(o); + uuids.put(o, user); + } + Timestamp timestamp = null; + try { + timestamp = r.getTimestamp("timestamp"); + } catch (SQLException ignored) { + } + long time; + if (timestamp == null) { + time = plot_id.hashCode(); + } else { + time = timestamp.getTime(); + } + Plot p = new Plot(plot_id, user, new HashSet(), new HashSet(), new HashSet(), "", null, null, null, + new boolean[]{false, false, false, false}, time, id); + HashMap map = newplots.get(areaid); + if (map != null) { + Plot last = map.put(p.getId(), p); + if (last != null) { + map.put(last.getId(), last); + if (Settings.AUTO_PURGE) { + toDelete.add(id); + } else { + PS.debug("&cPLOT " + id + " in `plot` is a duplicate. Delete this plot or set `auto-purge: true` in the settings.yml."); + } + continue; + } + } else { + map = new HashMap<>(); + newplots.put(areaid, map); + map.put(p.getId(), p); + } + plots.put(id, p); + } + deleteRows(toDelete, "plot", "id"); + } + if (Settings.CACHE_RATINGS) { + try (ResultSet r = stmt.executeQuery("SELECT `plot_plot_id`, `player`, `rating` FROM `" + prefix + "plot_rating`")) { + ArrayList toDelete = new ArrayList<>(); + while (r.next()) { + id = r.getInt("plot_plot_id"); + o = r.getString("player"); + user = uuids.get(o); + if (user == null) { + user = UUID.fromString(o); + uuids.put(o, user); + } + final Plot plot = plots.get(id); + if (plot != null) { + if (plot.getSettings().ratings == null) { + plot.getSettings().ratings = new HashMap<>(); + } + plot.getSettings().ratings.put(user, r.getInt("rating")); + } else if (Settings.AUTO_PURGE) { + toDelete.add(id); + } else { + PS.debug("&cENTRY " + id + " in `plot_rating` does not exist. Create this plot or set `auto-purge: true` in the settings.yml."); + } + } + deleteRows(toDelete, "plot_rating", "plot_plot_id"); + } + } + + /* + * Getting helpers + */ + try (ResultSet r = stmt.executeQuery("SELECT `user_uuid`, `plot_plot_id` FROM `" + prefix + "plot_helpers`")) { + ArrayList toDelete = new ArrayList<>(); + while (r.next()) { + id = r.getInt("plot_plot_id"); + o = r.getString("user_uuid"); + user = uuids.get(o); + if (user == null) { + user = UUID.fromString(o); + uuids.put(o, user); + } + final Plot plot = plots.get(id); + if (plot != null) { + plot.getTrusted().add(user); + } else if (Settings.AUTO_PURGE) { + toDelete.add(id); + } else { + PS.debug("&cENTRY " + id + " in `plot_helpers` does not exist. Create this plot or set `auto-purge: true` in the settings.yml."); + } + } + deleteRows(toDelete, "plot_helpers", "plot_plot_id"); + } + + /* + * Getting trusted + */ + try (ResultSet r = stmt.executeQuery("SELECT `user_uuid`, `plot_plot_id` FROM `" + prefix + "plot_trusted`")) { + ArrayList toDelete = new ArrayList<>(); + while (r.next()) { + id = r.getInt("plot_plot_id"); + o = r.getString("user_uuid"); + user = uuids.get(o); + if (user == null) { + user = UUID.fromString(o); + uuids.put(o, user); + } + final Plot plot = plots.get(id); + if (plot != null) { + plot.getMembers().add(user); + } else if (Settings.AUTO_PURGE) { + toDelete.add(id); + } else { + PS.debug("&cENTRY " + id + " in `plot_trusted` does not exist. Create this plot or set `auto-purge: true` in the settings.yml."); + } + } + deleteRows(toDelete, "plot_trusted", "plot_plot_id"); + } + + /* + * Getting denied + */ + try (ResultSet r = stmt.executeQuery("SELECT `user_uuid`, `plot_plot_id` FROM `" + prefix + "plot_denied`")) { + ArrayList toDelete = new ArrayList<>(); + while (r.next()) { + id = r.getInt("plot_plot_id"); + o = r.getString("user_uuid"); + user = uuids.get(o); + if (user == null) { + user = UUID.fromString(o); + uuids.put(o, user); + } + final Plot plot = plots.get(id); + if (plot != null) { + plot.getDenied().add(user); + } else if (Settings.AUTO_PURGE) { + toDelete.add(id); + } else { + PS.debug("&cENTRY " + id + " in `plot_denied` does not exist. Create this plot or set `auto-purge: true` in the settings.yml."); + } + } + deleteRows(toDelete, "plot_denied", "plot_plot_id"); + } + + try (ResultSet r = stmt.executeQuery("SELECT * FROM `" + prefix + "plot_settings`")) { + ArrayList toDelete = new ArrayList<>(); + while (r.next()) { + id = r.getInt("plot_plot_id"); + final Plot plot = plots.get(id); + if (plot != null) { + plots.remove(id); + final String alias = r.getString("alias"); + if (alias != null) { + plot.getSettings().setAlias(alias); + } + final String pos = r.getString("position"); + switch (pos.toLowerCase()) { + case "": + case "default": + case "0,0,0": + case "center": + break; + default: + try { + plot.getSettings().setPosition(BlockLoc.fromString(pos)); + } catch (final Exception ignored) {} + } + final Integer m = r.getInt("merged"); + final boolean[] merged = new boolean[4]; + for (int i = 0; i < 4; i++) { + merged[3 - i] = (m & (1 << i)) != 0; + } + plot.getSettings().setMerged(merged); + String[] flags_string; + final String myflags = r.getString("flags"); + if (myflags == null) { + flags_string = new String[] {}; + } else { + if (!myflags.isEmpty()) { + flags_string = myflags.split(","); + } else { + flags_string = new String[] {}; + } + } + final HashMap flags = new HashMap<>(); + boolean exception = false; + for (String element : flags_string) { + if (element.contains(":")) { + final String[] split = element.split(":"); + try { + final String flag_str = split[1].replaceAll("\u00AF", ":").replaceAll("\u00B4", ","); + final Flag flag = new Flag(FlagManager.getFlag(split[0], true), flag_str); + flags.put(flag.getKey(), flag); + } catch (final Exception e) { + e.printStackTrace(); + exception = true; + } + } else { + element = element.replaceAll("\u00AF", ":").replaceAll("\u00B4", ","); + if (StringMan.isAlpha(element.replaceAll("_", "").replaceAll("-", ""))) { + final Flag flag = new Flag(FlagManager.getFlag(element, true), ""); + flags.put(flag.getKey(), flag); + } else { + PS.debug("INVALID FLAG: " + element); + } + } + } + if (exception) { + PS.debug("&cPlot " + id + " | " + plot + " had an invalid flag. A fix has been attempted."); + PS.debug("&c" + myflags); + this.setFlags(plot, flags.values()); + } + plot.getSettings().flags = flags; + } else if (Settings.AUTO_PURGE) { + toDelete.add(id); + } else { + PS.debug("&cENTRY " + id + " in `plot_settings` does not exist. Create this plot or set `auto-purge: true` in the settings.yml."); + } + } + stmt.close(); + deleteRows(toDelete, "plot_settings", "plot_plot_id"); + } + if (!plots.entrySet().isEmpty()) { + createEmptySettings(new ArrayList<>(plots.keySet()), null); + for (Entry entry : plots.entrySet()) { + entry.getValue().getSettings(); + } + } + boolean invalidPlot = false; + for (final Entry entry : noExist.entrySet()) { + final String worldname = entry.getKey(); + invalidPlot = true; + PS.debug("&c[WARNING] Found " + entry.getValue().intValue() + " plots in DB for non existant world; '" + worldname + "'."); + } + if (invalidPlot) { + PS.debug("&c[WARNING] - Please create the world/s or remove the plots using the purge command"); + } + } catch (final SQLException e) { + PS.debug("&7[WARN] " + "Failed to load plots."); + e.printStackTrace(); + } + return newplots; + } + + @Override + public void setMerged(final Plot plot, final boolean[] merged) { + plot.getSettings().setMerged(merged); + addPlotTask(plot, new UniqueStatement("setMerged") { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + int hash = MainUtil.hash(merged); + stmt.setInt(1, hash); + stmt.setInt(2, getId(plot)); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("UPDATE `" + prefix + "plot_settings` SET `merged` = ? WHERE `plot_plot_id` = ?"); + } + }); + } + + @Override + public void swapPlots(final Plot p1, final Plot p2) { + final int id1 = getId(p1); + final int id2 = getId(p2); + final PlotId pos1 = p1.getId(); + final PlotId pos2 = p2.getId(); + addPlotTask(p1, new UniqueStatement("swapPlots") { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + stmt.setInt(1, pos2.x); + stmt.setInt(2, pos2.y); + stmt.setInt(3, id1); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("UPDATE `" + prefix + "plot` SET `plot_id_x` = ?, `plot_id_z` = ? WHERE `id` = ?"); + } + }); + addPlotTask(p2, new UniqueStatement("swapPlots") { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + stmt.setInt(1, pos1.x); + stmt.setInt(2, pos1.y); + stmt.setInt(3, id2); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("UPDATE `" + prefix + "plot` SET `plot_id_x` = ?, `plot_id_z` = ? WHERE `id` = ?"); + } + }); + } + + @Override + public void movePlot(final Plot original, final Plot newPlot) { + addPlotTask(original, new UniqueStatement("movePlot") { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + stmt.setInt(1, newPlot.getId().x); + stmt.setInt(2, newPlot.getId().y); + stmt.setString(3, newPlot.getArea().toString()); + stmt.setInt(4, getId(original)); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("UPDATE `" + prefix + "plot` SET `plot_id_x` = ?, `plot_id_z` = ?, `world` = ? WHERE `id` = ?"); + } + }); + addPlotTask(newPlot, null); + } + + @Override + public void setFlags(final Plot plot, final Collection flags) { + final StringBuilder flag_string = new StringBuilder(); + int i = 0; + for (final Flag flag : flags) { + if (i != 0) { + flag_string.append(","); + } + flag_string.append(flag.getKey() + ":" + flag.getValueString().replaceAll(":", "\u00AF").replaceAll(",", "\u00B4")); + i++; + } + addPlotTask(plot, new UniqueStatement("setFlags") { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + stmt.setString(1, flag_string.toString()); + stmt.setInt(2, getId(plot)); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("UPDATE `" + prefix + "plot_settings` SET `flags` = ? WHERE `plot_plot_id` = ?"); + } + }); + } + + @Override + public void setAlias(final Plot plot, final String alias) { + addPlotTask(plot, new UniqueStatement("setAlias") { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + stmt.setString(1, alias); + stmt.setInt(2, getId(plot)); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("UPDATE `" + prefix + "plot_settings` SET `alias` = ? WHERE `plot_plot_id` = ?"); + } + }); + } + + /** + * Purge all plots with the following database IDs + */ + @Override + public void purgeIds(final Set uniqueIds) { + addGlobalTask(new Runnable() { + @Override + public void run() { + if (!uniqueIds.isEmpty()) { + try { + String stmt_prefix = ""; + final StringBuilder idstr2 = new StringBuilder(""); + for (final Integer id : uniqueIds) { + idstr2.append(stmt_prefix).append(id); + stmt_prefix = " OR `id` = "; + } + stmt_prefix = ""; + final StringBuilder idstr = new StringBuilder(""); + for (final Integer id : uniqueIds) { + idstr.append(stmt_prefix).append(id); + stmt_prefix = " OR `plot_plot_id` = "; + } + PreparedStatement stmt = connection.prepareStatement("DELETE FROM `" + prefix + "plot_helpers` WHERE `plot_plot_id` = " + idstr + ""); + stmt.executeUpdate(); + stmt.close(); + stmt = connection.prepareStatement("DELETE FROM `" + prefix + "plot_denied` WHERE `plot_plot_id` = " + idstr + ""); + stmt.executeUpdate(); + stmt.close(); + stmt = connection.prepareStatement("DELETE FROM `" + prefix + "plot_settings` WHERE `plot_plot_id` = " + idstr + ""); + stmt.executeUpdate(); + stmt.close(); + stmt = connection.prepareStatement("DELETE FROM `" + prefix + "plot_trusted` WHERE `plot_plot_id` = " + idstr + ""); + stmt.executeUpdate(); + stmt.close(); + stmt = connection.prepareStatement("DELETE FROM `" + prefix + "plot` WHERE `id` = " + idstr2 + ""); + stmt.executeUpdate(); + stmt.close(); + } catch (final SQLException e) { + e.printStackTrace(); + PS.debug("&c[ERROR] " + "FAILED TO PURGE PLOTS!"); + return; + } + } + PS.debug("&6[INFO] " + "SUCCESSFULLY PURGED " + uniqueIds.size() + " PLOTS!"); + } + }); + } + + @Override + public void purge(final PlotArea area, final Set plots) { + addGlobalTask(new Runnable() { + @Override + public void run() { + try (PreparedStatement stmt = connection + .prepareStatement("SELECT `id`, `plot_id_x`, `plot_id_z` FROM `" + prefix + "plot` WHERE `world` = ?")) { + stmt.setString(1, area.toString()); + Set ids; + try (ResultSet r = stmt.executeQuery()) { + ids = new HashSet<>(); + while (r.next()) { + PlotId plot_id = new PlotId(r.getInt("plot_id_x"), r.getInt("plot_id_z")); + if (plots.contains(plot_id)) { + ids.add(r.getInt("id")); + } + } + } + purgeIds(ids); + } catch (final SQLException e) { + e.printStackTrace(); + PS.debug("&c[ERROR] " + "FAILED TO PURGE AREA '" + area + "'!"); + } + for (final Iterator iter = plots.iterator(); iter.hasNext();) { + final PlotId plotId = iter.next(); + iter.remove(); + final PlotId id = new PlotId(plotId.x, plotId.y); + area.removePlot(id); + } + } + }); + } + + @Override + public void setPosition(final Plot plot, final String position) { + addPlotTask(plot, new UniqueStatement("setPosition") { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + stmt.setString(1, position); + stmt.setInt(2, getId(plot)); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("UPDATE `" + prefix + "plot_settings` SET `position` = ? WHERE `plot_plot_id` = ?"); + } + }); + } + + @Override + public void removeComment(final Plot plot, final PlotComment comment) { + addPlotTask(plot, new UniqueStatement("removeComment") { + @Override + public void set(final PreparedStatement statement) throws SQLException { + if (plot != null) { + statement.setString(1, plot.getArea().toString()); + statement.setInt(2, plot.getId().hashCode()); + statement.setString(3, comment.comment); + statement.setString(4, comment.inbox); + statement.setString(5, comment.senderName); + } else { + statement.setString(1, comment.comment); + statement.setString(2, comment.inbox); + statement.setString(3, comment.senderName); + } + } + + @Override + public PreparedStatement get() throws SQLException { + if (plot != null) { + return connection.prepareStatement("DELETE FROM `" + prefix + "plot_comments` WHERE `world` = ? AND `hashcode` = ? AND `comment` = ? AND `inbox` = ? AND `sender` = ?"); + } + return connection.prepareStatement("DELETE FROM `" + prefix + "plot_comments` WHERE `comment` = ? AND `inbox` = ? AND `sender` = ?"); + } + }); + } + + @Override + public void clearInbox(final Plot plot, final String inbox) { + addPlotTask(plot, new UniqueStatement("clearInbox") { + @Override + public void set(final PreparedStatement statement) throws SQLException { + if (plot != null) { + statement.setString(1, plot.getArea().toString()); + statement.setInt(2, plot.getId().hashCode()); + statement.setString(3, inbox); + } else { + statement.setString(1, inbox); + } + } + + @Override + public PreparedStatement get() throws SQLException { + if (plot != null) { + return connection.prepareStatement("DELETE FROM `" + prefix + "plot_comments` WHERE `world` = ? AND `hashcode` = ? AND `inbox` = ?"); + } + return connection.prepareStatement("DELETE FROM `" + prefix + "plot_comments` `inbox` = ?"); + } + }); + } + + @Override + public void getComments(final Plot plot, final String inbox, final RunnableVal> whenDone) { + addPlotTask(plot, new UniqueStatement("getComments_" + plot) { + @Override + public void set(final PreparedStatement statement) throws SQLException { + if (plot != null) { + statement.setString(1, plot.getArea().toString()); + statement.setInt(2, plot.getId().hashCode()); + statement.setString(3, inbox); + } else { + statement.setString(1, inbox); + } + } + + @Override + public PreparedStatement get() throws SQLException { + if (plot != null) { + return connection.prepareStatement("SELECT * FROM `" + prefix + "plot_comments` WHERE `world` = ? AND `hashcode` = ? AND `inbox` = ?"); + } + return connection.prepareStatement("SELECT * FROM `" + prefix + "plot_comments` WHERE `inbox` = ?"); + } + + @Override + public void execute(final PreparedStatement stmt) {} + + @Override + public void addBatch(final PreparedStatement statement) throws SQLException { + final ArrayList comments = new ArrayList<>(); + try (ResultSet set = statement.executeQuery()) { + while (set.next()) { + final String sender = set.getString("sender"); + final String world = set.getString("world"); + final int hash = set.getInt("hashcode"); + PlotId id; + if (hash != 0) { + id = PlotId.unpair(hash); + } else { + id = null; + } + final String msg = set.getString("comment"); + final long timestamp = set.getInt("timestamp") * 1000; + PlotComment comment = new PlotComment(world, id, msg, sender, inbox, timestamp); + comments.add(comment); + whenDone.value = comments; + } + } + TaskManager.runTask(whenDone); + } + }); + } + + @Override + public void setComment(final Plot plot, final PlotComment comment) { + addPlotTask(plot, new UniqueStatement("setComment") { + @Override + public void set(final PreparedStatement statement) throws SQLException { + statement.setString(1, plot.getArea().toString()); + statement.setInt(2, plot.getId().hashCode()); + statement.setString(3, comment.comment); + statement.setString(4, comment.inbox); + statement.setInt(5, (int) (comment.timestamp / 1000)); + statement.setString(6, comment.senderName); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("INSERT INTO `" + prefix + "plot_comments` (`world`, `hashcode`, `comment`, `inbox`, `timestamp`, `sender`) VALUES(?,?,?,?,?,?)"); + } + }); + } + + @Override + public void removeTrusted(final Plot plot, final UUID uuid) { + addPlotTask(plot, new UniqueStatement("removeTrusted") { + @Override + public void set(final PreparedStatement statement) throws SQLException { + statement.setInt(1, getId(plot)); + statement.setString(2, uuid.toString()); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("DELETE FROM `" + prefix + "plot_helpers` WHERE `plot_plot_id` = ? AND `user_uuid` = ?"); + } + }); + } + + @Override + public void removeMember(final Plot plot, final UUID uuid) { + addPlotTask(plot, new UniqueStatement("removeMember") { + @Override + public void set(final PreparedStatement statement) throws SQLException { + statement.setInt(1, getId(plot)); + statement.setString(2, uuid.toString()); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("DELETE FROM `" + prefix + "plot_trusted` WHERE `plot_plot_id` = ? AND `user_uuid` = ?"); + } + }); + } + + @Override + public void setTrusted(final Plot plot, final UUID uuid) { + addPlotTask(plot, new UniqueStatement("setTrusted") { + @Override + public void set(final PreparedStatement statement) throws SQLException { + statement.setInt(1, getId(plot)); + statement.setString(2, uuid.toString()); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("INSERT INTO `" + prefix + "plot_helpers` (`plot_plot_id`, `user_uuid`) VALUES(?,?)"); + } + }); + } + + @Override + public void setMember(final Plot plot, final UUID uuid) { + addPlotTask(plot, new UniqueStatement("setMember") { + @Override + public void set(final PreparedStatement statement) throws SQLException { + statement.setInt(1, getId(plot)); + statement.setString(2, uuid.toString()); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("INSERT INTO `" + prefix + "plot_trusted` (`plot_plot_id`, `user_uuid`) VALUES(?,?)"); + } + }); + } + + @Override + public void removeDenied(final Plot plot, final UUID uuid) { + addPlotTask(plot, new UniqueStatement("removeDenied") { + @Override + public void set(final PreparedStatement statement) throws SQLException { + statement.setInt(1, getId(plot)); + statement.setString(2, uuid.toString()); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("DELETE FROM `" + prefix + "plot_denied` WHERE `plot_plot_id` = ? AND `user_uuid` = ?"); + } + }); + } + + @Override + public void setDenied(final Plot plot, final UUID uuid) { + addPlotTask(plot, new UniqueStatement("setDenied") { + @Override + public void set(final PreparedStatement statement) throws SQLException { + statement.setInt(1, getId(plot)); + statement.setString(2, uuid.toString()); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("INSERT INTO `" + prefix + "plot_denied` (`plot_plot_id`, `user_uuid`) VALUES(?,?)"); + } + }); + } + + @Override + public HashMap getRatings(final Plot plot) { + final HashMap map = new HashMap<>(); + try (PreparedStatement statement = connection + .prepareStatement("SELECT `rating`, `player` FROM `" + prefix + "plot_rating` WHERE `plot_plot_id` = ? ")) { + statement.setInt(1, getId(plot)); + try (ResultSet set = statement.executeQuery()) { + while (set.next()) { + final UUID uuid = UUID.fromString(set.getString("player")); + final int rating = set.getInt("rating"); + map.put(uuid, rating); + } + } + } catch (final SQLException e) { + PS.debug("&7[WARN] " + "Failed to fetch rating for plot " + plot.getId().toString()); + e.printStackTrace(); + } + return map; + } + + @Override + public void setRating(final Plot plot, final UUID rater, final int value) { + addPlotTask(plot, new UniqueStatement("setRating") { + @Override + public void set(final PreparedStatement statement) throws SQLException { + statement.setInt(1, getId(plot)); + statement.setInt(2, value); + statement.setString(3, rater.toString()); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("INSERT INTO `" + prefix + "plot_rating` (`plot_plot_id`, `rating`, `player`) VALUES(?,?,?)"); + } + }); + } + + @Override + public void delete(final PlotCluster cluster) { + final int id = getClusterId(cluster); + addClusterTask(cluster, new UniqueStatement("delete_cluster_settings") { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + stmt.setInt(1, id); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("DELETE FROM `" + prefix + "cluster_settings` WHERE `cluster_id` = ?"); + } + }); + addClusterTask(cluster, new UniqueStatement("delete_cluster_helpers") { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + stmt.setInt(1, id); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("DELETE FROM `" + prefix + "cluster_helpers` WHERE `cluster_id` = ?"); + } + }); + addClusterTask(cluster, new UniqueStatement("delete_cluster_invited") { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + stmt.setInt(1, id); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("DELETE FROM `" + prefix + "cluster_invited` WHERE `cluster_id` = ?"); + } + }); + addClusterTask(cluster, new UniqueStatement("delete_cluster") { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + stmt.setInt(1, id); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("DELETE FROM `" + prefix + "cluster` WHERE `id` = ?"); + } + }); + } + + @Override + public void addPersistentMeta(final UUID uuid, final String key, final byte[] meta, final boolean replace) { + addPlayerTask(uuid, new UniqueStatement("addPersistentMeta") { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + Blob blob = connection.createBlob(); + blob.setBytes(1, meta); + if (replace) { + stmt.setBlob(1, blob); + stmt.setString(2, uuid.toString()); + stmt.setString(3, key); + } else { + stmt.setString(1, uuid.toString()); + stmt.setString(2, key); + stmt.setBlob(3, blob); + } + } + + @Override + public PreparedStatement get() throws SQLException { + if (replace) { + return connection.prepareStatement("UPDATE `" + prefix + "player_meta` SET `value` = ? WHERE `uuid` = ? AND `key` = ?"); + } else { + return connection.prepareStatement("INSERT INTO `" + prefix + "player_meta`(`uuid`, `key`, `value`) VALUES(?, ? ,?)"); + } + } + }); + } + + @Override + public void removePersistentMeta(final UUID uuid, final String key) { + addPlayerTask(uuid, new UniqueStatement("removePersistentMeta") { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + stmt.setString(1, uuid.toString()); + stmt.setString(2, key); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("DELETE FROM `" + prefix + "player_meta` WHERE `uuid` = ? AND `key` = ?"); + } + }); + } + + @Override + public void getPersistentMeta(final UUID uuid, final RunnableVal> result) { + addPlayerTask(uuid, new UniqueStatement("getPersistentMeta") { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + stmt.setString(1, uuid.toString()); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("SELECT * FROM `" + prefix + "player_meta` WHERE `uuid` = ?"); + } + + @Override + public void execute(PreparedStatement stmt) {} + + @Override + public void addBatch(PreparedStatement stmt) throws SQLException { + ResultSet resultSet = stmt.executeQuery(); + + final Map metaMap = new HashMap<>(); + + while (resultSet.next()) { + String key = resultSet.getString("key"); + Blob rawValue = resultSet.getBlob("value"); + byte[] bytes = rawValue.getBytes(1, (int) rawValue.length()); + metaMap.put(key, bytes); + } + + resultSet.close(); + result.run(metaMap); + } + + }); + } + + @Override + public HashMap> getClusters() { + final LinkedHashMap> newClusters = new LinkedHashMap<>(); + final HashMap clusters = new HashMap<>(); + try { + HashSet areas = new HashSet<>(); + if (PS.get().config.contains("worlds")) { + ConfigurationSection worldSection = PS.get().config.getConfigurationSection("worlds"); + if (worldSection != null) { + for (String worldKey : worldSection.getKeys(false)) { + areas.add(worldKey); + ConfigurationSection areaSection = worldSection.getConfigurationSection(worldKey + ".areas"); + if (areaSection != null) { + for (String areaKey : areaSection.getKeys(false)) { + String[] split = areaKey.split("-"); + if (split.length == 3) { + areas.add(worldKey + ";" + split[0]); + } + } + } + } + } + } + final HashMap uuids = new HashMap<>(); + final HashMap noExist = new HashMap<>(); + /* + * Getting clusters + */ + Statement stmt = connection.createStatement(); + ResultSet r = stmt.executeQuery("SELECT * FROM `" + prefix + "cluster`"); + PlotCluster cluster; + String owner; + UUID user; + int id; + while (r.next()) { + PlotId pos1 = new PlotId(r.getInt("pos1_x"), r.getInt("pos1_z")); + PlotId pos2 = new PlotId(r.getInt("pos2_x"), r.getInt("pos2_z")); + id = r.getInt("id"); + String areaid = r.getString("world"); + if (!areas.contains(areaid)) { + if (noExist.containsKey(areaid)) { + noExist.put(areaid, noExist.get(areaid) + 1); + } else { + noExist.put(areaid, 1); + } + } + owner = r.getString("owner"); + user = uuids.get(owner); + if (user == null) { + user = UUID.fromString(owner); + uuids.put(owner, user); + } + cluster = new PlotCluster(null, pos1, pos2, user, id); + clusters.put(id, cluster); + Set set = newClusters.get(areaid); + if (set == null) { + set = new HashSet<>(); + newClusters.put(areaid, set); + } + set.add(cluster); + } + /* + * Getting helpers + */ + r = stmt.executeQuery("SELECT `user_uuid`, `cluster_id` FROM `" + prefix + "cluster_helpers`"); + while (r.next()) { + id = r.getInt("cluster_id"); + owner = r.getString("user_uuid"); + user = uuids.get(owner); + if (user == null) { + user = UUID.fromString(owner); + uuids.put(owner, user); + } + cluster = clusters.get(id); + if (cluster != null) { + cluster.helpers.add(user); + } else { + PS.debug("&cCluster " + id + " in cluster_helpers does not exist. Please create the cluster or remove this entry."); + } + } + /* + * Getting invited + */ + r = stmt.executeQuery("SELECT `user_uuid`, `cluster_id` FROM `" + prefix + "cluster_invited`"); + while (r.next()) { + id = r.getInt("cluster_id"); + owner = r.getString("user_uuid"); + user = uuids.get(owner); + if (user == null) { + user = UUID.fromString(owner); + uuids.put(owner, user); + } + cluster = clusters.get(id); + if (cluster != null) { + cluster.invited.add(user); + } else { + PS.debug("&cCluster " + id + " in cluster_invited does not exist. Please create the cluster or remove this entry."); + } + } + r = stmt.executeQuery("SELECT * FROM `" + prefix + "cluster_settings`"); + while (r.next()) { + id = r.getInt("cluster_id"); + cluster = clusters.get(id); + if (cluster != null) { + final String alias = r.getString("alias"); + if (alias != null) { + cluster.settings.setAlias(alias); + } + final String pos = r.getString("position"); + switch (pos.toLowerCase()) { + case "": + case "default": + case "0,0,0": + case "center": + break; + default: + try { + BlockLoc loc = BlockLoc.fromString(pos); + cluster.settings.setPosition(loc); + } catch (final Exception e) {} + } + final Integer m = r.getInt("merged"); + final boolean[] merged = new boolean[4]; + for (int i = 0; i < 4; i++) { + merged[3 - i] = ((m) & (1 << i)) != 0; + } + cluster.settings.setMerged(merged); + String[] flags_string; + final String myflags = r.getString("flags"); + if (myflags == null) { + flags_string = new String[] {}; + } else { + if (!myflags.isEmpty()) { + flags_string = myflags.split(","); + } else { + flags_string = new String[] {}; + } + } + final HashMap flags = new HashMap<>(); + boolean exception = false; + for (final String element : flags_string) { + if (element.contains(":")) { + final String[] split = element.split(":"); + try { + final String flag_str = split[1].replaceAll("\u00AF", ":").replaceAll("�", ","); + final Flag flag = new Flag(FlagManager.getFlag(split[0], true), flag_str); + flags.put(flag.getKey(), flag); + } catch (final Exception e) { + e.printStackTrace(); + exception = true; + } + } else { + final Flag flag = new Flag(FlagManager.getFlag(element, true), ""); + flags.put(flag.getKey(), flag); + } + } + if (exception) { + PS.debug("&cCluster " + id + " had an invalid flag. A fix has been attempted."); + PS.debug("&c" + myflags); + } + cluster.settings.flags = flags; + } else { + PS.debug("&cCluster " + id + " in cluster_settings does not exist. Please create the cluster or remove this entry."); + } + } + stmt.close(); + r.close(); + boolean invalidPlot = false; + for (final Entry entry : noExist.entrySet()) { + final String a = entry.getKey(); + invalidPlot = true; + PS.debug("&c[WARNING] Found " + noExist.get(a) + " clusters in DB for non existant area; '" + a + "'."); + } + if (invalidPlot) { + PS.debug("&c[WARNING] - Please create the world/s or remove the clusters using the purge command"); + } + } catch (final SQLException e) { + PS.debug("&7[WARN] " + "Failed to load clusters."); + e.printStackTrace(); + } + return newClusters; + } + + @Override + public void setFlags(final PlotCluster cluster, final Collection flags) { + final StringBuilder flag_string = new StringBuilder(); + int i = 0; + for (final Flag flag : flags) { + if (i != 0) { + flag_string.append(","); + } + flag_string.append(flag.getKey() + ":" + flag.getValueString().replaceAll(":", "\u00AF").replaceAll(",", "\u00B4")); + i++; + } + addClusterTask(cluster, new UniqueStatement("setFlags") { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + stmt.setString(1, flag_string.toString()); + stmt.setInt(2, getClusterId(cluster)); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("UPDATE `" + prefix + "cluster_settings` SET `flags` = ? WHERE `cluster_id` = ?"); + } + }); + } + + @Override + public void setClusterName(final PlotCluster cluster, final String name) { + addClusterTask(cluster, new UniqueStatement("setClusterName") { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + stmt.setString(1, name); + stmt.setInt(2, getClusterId(cluster)); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("UPDATE `" + prefix + "cluster_settings` SET `alias` = ? WHERE `cluster_id` = ?"); + } + }); + cluster.settings.setAlias(name); + } + + @Override + public void removeHelper(final PlotCluster cluster, final UUID uuid) { + addClusterTask(cluster, new UniqueStatement("removeHelper") { + @Override + public void set(final PreparedStatement statement) throws SQLException { + statement.setInt(1, getClusterId(cluster)); + statement.setString(2, uuid.toString()); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("DELETE FROM `" + prefix + "cluster_helpers` WHERE `cluster_id` = ? AND `user_uuid` = ?"); + } + }); + } + + @Override + public void setHelper(final PlotCluster cluster, final UUID uuid) { + addClusterTask(cluster, new UniqueStatement("setHelper") { + @Override + public void set(final PreparedStatement statement) throws SQLException { + statement.setInt(1, getClusterId(cluster)); + statement.setString(2, uuid.toString()); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("INSERT INTO `" + prefix + "cluster_helpers` (`cluster_id`, `user_uuid`) VALUES(?,?)"); + } + }); + } + + @Override + public void createCluster(final PlotCluster cluster) { + addClusterTask(cluster, new UniqueStatement("createCluster_" + cluster.hashCode()) { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + stmt.setInt(1, cluster.getP1().x); + stmt.setInt(2, cluster.getP1().y); + stmt.setInt(3, cluster.getP2().x); + stmt.setInt(4, cluster.getP2().y); + stmt.setString(5, cluster.owner.toString()); + stmt.setString(6, cluster.area.toString()); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement(CREATE_CLUSTER, Statement.RETURN_GENERATED_KEYS); + } + + @Override + public void execute(final PreparedStatement stmt) { + + } + + @Override + public void addBatch(final PreparedStatement stmt) throws SQLException { + stmt.executeUpdate(); + final ResultSet keys = stmt.getGeneratedKeys(); + if (keys.next()) { + cluster.temp = keys.getInt(1); + } + } + }); + addClusterTask(cluster, new UniqueStatement("createCluster_settings_" + cluster.hashCode()) { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + stmt.setInt(1, getClusterId(cluster)); + stmt.setString(2, cluster.settings.getAlias()); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("INSERT INTO `" + prefix + "cluster_settings`(`cluster_id`, `alias`) VALUES(?, ?" + ")"); + } + }); + } + + @Override + public void resizeCluster(final PlotCluster current, PlotId min, PlotId max) { + final PlotId pos1 = new PlotId(current.getP1().x, current.getP1().y); + final PlotId pos2 = new PlotId(current.getP2().x, current.getP2().y); + current.setP1(min); + current.setP2(max); + + addClusterTask(current, new UniqueStatement("resizeCluster") { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + stmt.setInt(1, pos1.x); + stmt.setInt(2, pos1.y); + stmt.setInt(3, pos2.x); + stmt.setInt(4, pos2.y); + stmt.setInt(5, getClusterId(current)); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("UPDATE `" + prefix + "cluster` SET `pos1_x` = ?, `pos1_z` = ?, `pos2_x` = ?, `pos2_z` = ? WHERE `id` = ?"); + } + }); + } + + @Override + public void setPosition(final PlotCluster cluster, final String position) { + addClusterTask(cluster, new UniqueStatement("setPosition") { + @Override + public void set(final PreparedStatement stmt) throws SQLException { + stmt.setString(1, position); + stmt.setInt(2, getClusterId(cluster)); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("UPDATE `" + prefix + "cluster_settings` SET `position` = ? WHERE `cluster_id` = ?"); + } + }); + } + + @Override + public void removeInvited(final PlotCluster cluster, final UUID uuid) { + addClusterTask(cluster, new UniqueStatement("removeInvited") { + @Override + public void set(final PreparedStatement statement) throws SQLException { + statement.setInt(1, getClusterId(cluster)); + statement.setString(2, uuid.toString()); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("DELETE FROM `" + prefix + "cluster_invited` WHERE `cluster_id` = ? AND `user_uuid` = ?"); + } + }); + } + + @Override + public void setInvited(final PlotCluster cluster, final UUID uuid) { + addClusterTask(cluster, new UniqueStatement("setInvited") { + @Override + public void set(final PreparedStatement statement) throws SQLException { + statement.setInt(1, getClusterId(cluster)); + statement.setString(2, uuid.toString()); + } + + @Override + public PreparedStatement get() throws SQLException { + return connection.prepareStatement("INSERT INTO `" + prefix + "cluster_invited` (`cluster_id`, `user_uuid`) VALUES(?,?)"); + } + }); + } + + @Override + public boolean deleteTables() { + try { + close(); + CLOSED = false; + SQLManager.this.connection = database.forceConnection(); + final Statement stmt = connection.createStatement(); + stmt.addBatch("DROP TABLE `" + prefix + "cluster_invited`"); + stmt.addBatch("DROP TABLE `" + prefix + "cluster_helpers`"); + stmt.addBatch("DROP TABLE `" + prefix + "cluster`"); + stmt.addBatch("DROP TABLE `" + prefix + "plot_rating`"); + stmt.addBatch("DROP TABLE `" + prefix + "plot_settings`"); + stmt.addBatch("DROP TABLE `" + prefix + "plot_comments`"); + stmt.addBatch("DROP TABLE `" + prefix + "plot_trusted`"); + stmt.addBatch("DROP TABLE `" + prefix + "plot_helpers`"); + stmt.addBatch("DROP TABLE `" + prefix + "plot_denied`"); + stmt.executeBatch(); + stmt.clearBatch(); + stmt.close(); + + final PreparedStatement statement = connection.prepareStatement("DROP TABLE `" + prefix + "plot`"); + statement.executeUpdate(); + statement.close(); + } catch (ClassNotFoundException | SQLException e) { + e.printStackTrace(); + } + return true; + } + + @Override + public void validateAllPlots(final Set toValidate) { + try { + if (connection.isClosed() || CLOSED) { + CLOSED = false; + connection = database.forceConnection(); + } + } catch (ClassNotFoundException | SQLException e) { + e.printStackTrace(); + } + PS.debug("$1All DB transactions during this session are being validated (This may take a while if corrections need to be made)"); + commit(); + while (true) { + if (!sendBatch()) { + break; + } + } + try { + if (connection.getAutoCommit()) { + connection.setAutoCommit(false); + } + } catch (final SQLException e) { + e.printStackTrace(); + } + final HashMap> database = getPlots(); + final ArrayList toCreate = new ArrayList<>(); + for (final Plot plot : toValidate) { + if (plot.temp == -1) { + continue; + } + final HashMap worldplots = database.get(plot.getArea().toString()); + if (worldplots == null) { + PS.debug("&8 - &7Creating plot (1): " + plot); + toCreate.add(plot); + continue; + } + final Plot dataplot = worldplots.remove(plot.getId()); + if (dataplot == null) { + PS.debug("&8 - &7Creating plot (2): " + plot); + toCreate.add(plot); + continue; + } + // owner + if (!plot.owner.equals(dataplot.owner)) { + PS.debug("&8 - &7Setting owner: " + plot + " -> " + MainUtil.getName(plot.owner)); + setOwner(plot, plot.owner); + } + // trusted + if (!plot.getTrusted().equals(dataplot.getTrusted())) { + final HashSet toAdd = (HashSet) plot.getTrusted().clone(); + final HashSet toRemove = (HashSet) dataplot.getTrusted().clone(); + toRemove.removeAll(plot.getTrusted()); + toAdd.removeAll(dataplot.getTrusted()); + PS.debug("&8 - &7Correcting " + (toAdd.size() + toRemove.size()) + " trusted for: " + plot); + if (!toRemove.isEmpty()) { + for (final UUID uuid : toRemove) { + removeTrusted(plot, uuid); + } + } + if (!toAdd.isEmpty()) { + for (final UUID uuid : toAdd) { + setTrusted(plot, uuid); + } + } + } + if (!plot.getMembers().equals(dataplot.getMembers())) { + final HashSet toAdd = (HashSet) plot.getMembers().clone(); + final HashSet toRemove = (HashSet) dataplot.getMembers().clone(); + toRemove.removeAll(plot.getMembers()); + toAdd.removeAll(dataplot.getMembers()); + PS.debug("&8 - &7Correcting " + (toAdd.size() + toRemove.size()) + " members for: " + plot); + if (!toRemove.isEmpty()) { + for (final UUID uuid : toRemove) { + removeMember(plot, uuid); + } + } + if (!toAdd.isEmpty()) { + for (final UUID uuid : toAdd) { + setMember(plot, uuid); + } + } + } + if (!plot.getDenied().equals(dataplot.getDenied())) { + final HashSet toAdd = (HashSet) plot.getDenied().clone(); + final HashSet toRemove = (HashSet) dataplot.getDenied().clone(); + toRemove.removeAll(plot.getDenied()); + toAdd.removeAll(dataplot.getDenied()); + PS.debug("&8 - &7Correcting " + (toAdd.size() + toRemove.size()) + " denied for: " + plot); + if (!toRemove.isEmpty()) { + for (final UUID uuid : toRemove) { + removeDenied(plot, uuid); + } + } + if (!toAdd.isEmpty()) { + for (final UUID uuid : toAdd) { + setDenied(plot, uuid); + } + } + } + final boolean[] pm = plot.getMerged(); + final boolean[] dm = dataplot.getMerged(); + if (pm[0] != dm[0] || pm[1] != dm[1]) { + PS.debug("&8 - &7Correcting merge for: " + plot); + setMerged(dataplot, plot.getMerged()); + } + final HashMap pf = plot.getFlags(); + final HashMap df = dataplot.getFlags(); + if (!pf.isEmpty() && !df.isEmpty()) { + if (pf.size() != df.size() || !StringMan.isEqual(StringMan.joinOrdered(pf.values(), ","), StringMan.joinOrdered(df.values(), ","))) { + PS.debug("&8 - &7Correcting flags for: " + plot); + setFlags(plot, pf.values()); + } + } + } + + for (final Entry> entry : database.entrySet()) { + final HashMap map = entry.getValue(); + if (!map.isEmpty()) { + for (final Entry entry2 : map.entrySet()) { + PS.debug("$1Plot was deleted: " + entry2.getValue() + "// TODO implement this when sure safe"); + } + } + } + commit(); + } + + @Override + public void replaceWorld(final String oldWorld, final String newWorld, final PlotId min, final PlotId max) { + addGlobalTask(new Runnable() { + @Override + public void run() { + if (min == null) { + try (PreparedStatement stmt = connection.prepareStatement("UPDATE `" + prefix + "plot` SET `world` = ? WHERE `world` = ?")) { + stmt.setString(1, newWorld); + stmt.setString(2, oldWorld); + stmt.executeUpdate(); + stmt.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + try (PreparedStatement stmt = connection.prepareStatement("UPDATE `" + prefix + "cluster` SET `world` = ? WHERE `world` = ?")) { + stmt.setString(1, newWorld); + stmt.setString(2, oldWorld); + stmt.executeUpdate(); + stmt.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } else { + try (PreparedStatement stmt = connection.prepareStatement("UPDATE `" + + prefix + + "plot` SET `world` = ? WHERE `world` = ? AND `plot_id_x` BETWEEN ? AND ? AND `plot_id_z` BETWEEN ? AND ?")) { + stmt.setString(1, newWorld); + stmt.setString(2, oldWorld); + stmt.setInt(3, min.x); + stmt.setInt(4, max.x); + stmt.setInt(5, min.y); + stmt.setInt(6, max.y); + stmt.executeUpdate(); + stmt.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + try (PreparedStatement stmt = connection.prepareStatement("UPDATE `" + + prefix + + "cluster` SET `world` = ? WHERE `world` = ? AND `pos1_x` <= ? AND `pos1_z` <= ? AND `pos2_x` >= ? AND `pos2_z` >= ?")) { + stmt.setString(1, newWorld); + stmt.setString(2, oldWorld); + stmt.setInt(3, max.x); + stmt.setInt(4, max.y); + stmt.setInt(5, min.x); + stmt.setInt(6, min.y); + stmt.executeUpdate(); + stmt.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + } + }); + } + + @Override + public void replaceUUID(final UUID old, final UUID now) { + addGlobalTask(new Runnable() { + @Override + public void run() { + try (Statement stmt = connection.createStatement()) { + stmt.executeUpdate( + "UPDATE `" + prefix + "cluster` SET `owner` = '" + now.toString() + "' WHERE `owner` = '" + old.toString() + "'"); + stmt.executeUpdate( + "UPDATE `" + prefix + "cluster_helpers` SET `user_uuid` = '" + now.toString() + "' WHERE `user_uuid` = '" + old.toString() + + "'"); + stmt.executeUpdate( + "UPDATE `" + prefix + "cluster_invited` SET `user_uuid` = '" + now.toString() + "' WHERE `user_uuid` = '" + old.toString() + + "'"); + stmt.executeUpdate("UPDATE `" + prefix + "plot` SET `owner` = '" + now.toString() + "' WHERE `owner` = '" + old.toString() + "'"); + stmt.executeUpdate( + "UPDATE `" + prefix + "plot_denied` SET `user_uuid` = '" + now.toString() + "' WHERE `user_uuid` = '" + old.toString() + + "'"); + stmt.executeUpdate( + "UPDATE `" + prefix + "plot_helpers` SET `user_uuid` = '" + now.toString() + "' WHERE `user_uuid` = '" + old.toString() + + "'"); + stmt.executeUpdate( + "UPDATE `" + prefix + "plot_trusted` SET `user_uuid` = '" + now.toString() + "' WHERE `user_uuid` = '" + old.toString() + + "'"); + stmt.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + }); + } + + @Override + public void close() { + try { + CLOSED = true; + connection.close(); + } catch (final SQLException e) { + e.printStackTrace(); + } + } + + public abstract class UniqueStatement { + + public String _method; + + public UniqueStatement(final String method) { + _method = method; + } + + public void addBatch(final PreparedStatement stmt) throws SQLException { + stmt.addBatch(); + } + + public void execute(final PreparedStatement stmt) throws SQLException { + stmt.executeBatch(); + } + + public abstract PreparedStatement get() throws SQLException; + + public abstract void set(final PreparedStatement stmt) throws SQLException; + } + + private class UUIDPair { + + public final int id; + public final UUID uuid; + + public UUIDPair(final int id, final UUID uuid) { + this.id = id; + this.uuid = uuid; + } + } + + private class SettingsPair { + + public final int id; + public final PlotSettings settings; + + public SettingsPair(final int id, final PlotSettings settings) { + this.id = id; + this.settings = settings; + } + } +} diff --git a/src/main/java/com/intellectualcrafters/plot/database/SQLite.java b/Core/src/main/java/com/intellectualcrafters/plot/database/SQLite.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/database/SQLite.java rename to Core/src/main/java/com/intellectualcrafters/plot/database/SQLite.java diff --git a/src/main/java/com/intellectualcrafters/plot/database/StmtMod.java b/Core/src/main/java/com/intellectualcrafters/plot/database/StmtMod.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/database/StmtMod.java rename to Core/src/main/java/com/intellectualcrafters/plot/database/StmtMod.java diff --git a/src/main/java/com/intellectualcrafters/plot/flag/AbstractFlag.java b/Core/src/main/java/com/intellectualcrafters/plot/flag/AbstractFlag.java similarity index 97% rename from src/main/java/com/intellectualcrafters/plot/flag/AbstractFlag.java rename to Core/src/main/java/com/intellectualcrafters/plot/flag/AbstractFlag.java index eea9c2740..aa3b895df 100644 --- a/src/main/java/com/intellectualcrafters/plot/flag/AbstractFlag.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/flag/AbstractFlag.java @@ -1,112 +1,112 @@ -//////////////////////////////////////////////////////////////////////////////////////////////////// -// PlotSquared - A plot manager and world generator for the Bukkit API / -// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / -// / -// This program is free software; you can redistribute it and/or modify / -// it under the terms of the GNU General Public License as published by / -// the Free Software Foundation; either version 3 of the License, or / -// (at your option) any later version. / -// / -// This program is distributed in the hope that it will be useful, / -// but WITHOUT ANY WARRANTY; without even the implied warranty of / -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / -// GNU General Public License for more details. / -// / -// You should have received a copy of the GNU General Public License / -// along with this program; if not, write to the Free Software Foundation, / -// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / -// / -// You can contact us via: support@intellectualsites.com / -//////////////////////////////////////////////////////////////////////////////////////////////////// -package com.intellectualcrafters.plot.flag; - -import com.intellectualcrafters.plot.util.StringMan; - -/** - * Created 2014-09-23 for PlotSquared - * - - - */ -public class AbstractFlag { - public final String key; - public final FlagValue value; - - public AbstractFlag(final String key) { - this(key, new FlagValue.StringValue()); - } - - /** - * AbstractFlag is a parameter used in creating a new Flag
- * The key must be alphabetical characters and <= 16 characters in length - * @param key - */ - public AbstractFlag(final String key, final FlagValue value) { - if (!StringMan.isAlpha(key.replaceAll("_", "").replaceAll("-", ""))) { - throw new IllegalArgumentException("Flag must be alphabetic characters"); - } - if (key.length() > 16) { - throw new IllegalArgumentException("Key must be <= 16 characters"); - } - this.key = key.toLowerCase(); - if (value == null) { - this.value = new FlagValue.StringValue(); - } else { - this.value = value; - } - } - - public boolean isList() { - return value instanceof FlagValue.ListValue; - } - - public Object parseValueRaw(final String value) { - try { - return this.value.parse(value); - } catch (final Exception e) { - return null; - } - } - - public String toString(final Object t) { - return value.toString(t); - } - - public String getValueDesc() { - return value.getDescription(); - } - - /** - * AbstractFlag key - * - * @return String - */ - public String getKey() { - return key; - } - - @Override - public String toString() { - return key; - } - - @Override - public int hashCode() { - return key.hashCode(); - } - - @Override - public boolean equals(final Object other) { - if (other == null) { - return false; - } - if (other == this) { - return true; - } - if (!(other instanceof AbstractFlag)) { - return false; - } - final AbstractFlag otherObj = (AbstractFlag) other; - return otherObj.key.equals(key); - } -} +//////////////////////////////////////////////////////////////////////////////////////////////////// +// PlotSquared - A plot manager and world generator for the Bukkit API / +// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / +// / +// This program is free software; you can redistribute it and/or modify / +// it under the terms of the GNU General Public License as published by / +// the Free Software Foundation; either version 3 of the License, or / +// (at your option) any later version. / +// / +// This program is distributed in the hope that it will be useful, / +// but WITHOUT ANY WARRANTY; without even the implied warranty of / +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / +// GNU General Public License for more details. / +// / +// You should have received a copy of the GNU General Public License / +// along with this program; if not, write to the Free Software Foundation, / +// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / +// / +// You can contact us via: support@intellectualsites.com / +//////////////////////////////////////////////////////////////////////////////////////////////////// +package com.intellectualcrafters.plot.flag; + +import com.intellectualcrafters.plot.util.StringMan; + +/** + * Created 2014-09-23 for PlotSquared + * + + + */ +public class AbstractFlag { + public final String key; + public final FlagValue value; + + public AbstractFlag(final String key) { + this(key, new FlagValue.StringValue()); + } + + /** + * AbstractFlag is a parameter used in creating a new Flag
+ * The key must be alphabetical characters and <= 16 characters in length + * @param key + */ + public AbstractFlag(final String key, final FlagValue value) { + if (!StringMan.isAlpha(key.replaceAll("_", "").replaceAll("-", ""))) { + throw new IllegalArgumentException("Flag must be alphabetic characters"); + } + if (key.length() > 16) { + throw new IllegalArgumentException("Key must be <= 16 characters"); + } + this.key = key.toLowerCase(); + if (value == null) { + this.value = new FlagValue.StringValue(); + } else { + this.value = value; + } + } + + public boolean isList() { + return value instanceof FlagValue.ListValue; + } + + public Object parseValueRaw(final String value) { + try { + return this.value.parse(value); + } catch (final Exception e) { + return null; + } + } + + public String toString(final Object t) { + return value.toString(t); + } + + public String getValueDesc() { + return value.getDescription(); + } + + /** + * AbstractFlag key + * + * @return String + */ + public String getKey() { + return key; + } + + @Override + public String toString() { + return key; + } + + @Override + public int hashCode() { + return key.hashCode(); + } + + @Override + public boolean equals(final Object other) { + if (other == null) { + return false; + } + if (other == this) { + return true; + } + if (!(other instanceof AbstractFlag)) { + return false; + } + final AbstractFlag otherObj = (AbstractFlag) other; + return otherObj.key.equals(key); + } +} diff --git a/src/main/java/com/intellectualcrafters/plot/flag/Flag.java b/Core/src/main/java/com/intellectualcrafters/plot/flag/Flag.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/flag/Flag.java rename to Core/src/main/java/com/intellectualcrafters/plot/flag/Flag.java diff --git a/src/main/java/com/intellectualcrafters/plot/flag/FlagManager.java b/Core/src/main/java/com/intellectualcrafters/plot/flag/FlagManager.java similarity index 97% rename from src/main/java/com/intellectualcrafters/plot/flag/FlagManager.java rename to Core/src/main/java/com/intellectualcrafters/plot/flag/FlagManager.java index 966befdba..a60a74ef2 100644 --- a/src/main/java/com/intellectualcrafters/plot/flag/FlagManager.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/flag/FlagManager.java @@ -1,453 +1,453 @@ -//////////////////////////////////////////////////////////////////////////////////////////////////// -// PlotSquared - A plot manager and world generator for the Bukkit API / -// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / -// / -// This program is free software; you can redistribute it and/or modify / -// it under the terms of the GNU General Public License as published by / -// the Free Software Foundation; either version 3 of the License, or / -// (at your option) any later version. / -// / -// This program is distributed in the hope that it will be useful, / -// but WITHOUT ANY WARRANTY; without even the implied warranty of / -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / -// GNU General Public License for more details. / -// / -// You should have received a copy of the GNU General Public License / -// along with this program; if not, write to the Free Software Foundation, / -// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / -// / -// You can contact us via: support@intellectualsites.com / -//////////////////////////////////////////////////////////////////////////////////////////////////// -package com.intellectualcrafters.plot.flag; - -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotCluster; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.PlotSettings; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.util.EventUtil; -import com.intellectualcrafters.plot.util.Permissions; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Flag Manager Utility - * - - - */ -public class FlagManager { - - private final static HashSet reserved = new HashSet<>(); - - private final static HashSet flags = new HashSet<>(); - - /** - * Reserve a flag so that it cannot be set by players - * @param flag - */ - public static void reserveFlag(final String flag) { - reserved.add(flag); - } - - /** - * Get if a flag is reserved - * @param flag - * @return - */ - public static boolean isReserved(final String flag) { - return reserved.contains(flag); - } - - /** - * Get the reserved flags - * @return - */ - public static HashSet getReservedFlags() { - return (HashSet) reserved.clone(); - } - - /** - * Unreserve a flag - * @param flag - */ - public static void unreserveFlag(final String flag) { - reserved.remove(flag); - } - - /** - * Register an AbstractFlag with PlotSquared - * - * @param af Flag to register - * - * @return boolean success - */ - public static boolean addFlag(final AbstractFlag af) { - return addFlag(af, false); - } - - public static boolean addFlag(final AbstractFlag af, final boolean reserved) { - PS.debug(C.PREFIX.s() + "&8 - Adding flag: &7" + af); - PS.get().foreachPlotArea(new RunnableVal() { - @Override - public void run(PlotArea value) { - final Flag flag = value.DEFAULT_FLAGS.get(af.getKey()); - if (flag != null) { - flag.setKey(af); - } - } - }); - PS.get().foreachPlotRaw(new RunnableVal() { - @Override - public void run(Plot value) { - final Flag flag = value.getFlags().get(af.getKey()); - if (flag != null) { - flag.setKey(af); - } - } - }); - if (flags.remove(af)) { - PS.debug("(Replaced existing flag)"); - } - flags.add(af); - if (reserved) { - reserveFlag(af.getKey()); - } - return false; - } - - public static Flag getSettingFlag(final PlotArea area, final PlotSettings settings, final String id) { - Flag flag; - if (settings.flags.isEmpty() || (flag = settings.flags.get(id)) == null) { - if (area == null) { - return null; - } - if (area.DEFAULT_FLAGS.isEmpty()) { - return null; - } - return area.DEFAULT_FLAGS.get(id); - } - return flag; - } - - public static boolean isBooleanFlag(final Plot plot, final String key, final boolean defaultValue) { - final Flag flag = FlagManager.getPlotFlagRaw(plot, key); - if (flag == null) { - return defaultValue; - } - final Object value = flag.getValue(); - if (value instanceof Boolean) { - return (boolean) value; - } - return defaultValue; - } - - /** - * Get the value of a flag for a plot (respects flag defaults) - * @param plot - * @param flag - * @return Flag - */ - public static Flag getPlotFlag(final Plot plot, final String flag) { - Flag result = getPlotFlagRaw(plot, flag); - return result == null ? null : (Flag) result.clone(); - } - - /** - * Returns the raw flag
- * - Faster - * - You should not modify the flag - * @param plot - * @param flag - * @return - */ - public static Flag getPlotFlagRaw(final Plot plot, final String flag) { - if (plot.owner == null) { - return null; - } - return getSettingFlag(plot.getArea(), plot.getSettings(), flag); - } - - public static boolean isPlotFlagTrue(final Plot plot, final String strFlag) { - if (plot.owner == null) { - return false; - } - final Flag flag = getPlotFlagRaw(plot, strFlag); - return !(flag == null || !((Boolean) flag.getValue())); - } - - public static boolean isPlotFlagFalse(final Plot plot, final String strFlag) { - if (plot.owner == null) { - return false; - } - final Flag flag = getPlotFlagRaw(plot, strFlag); - if (flag == null || (Boolean) flag.getValue()) { - return false; - } - return false; - } - - /** - * Get the value of a flag for a plot (ignores flag defaults) - * @param plot - * @param flag - * @return Flag - */ - public static Flag getPlotFlagAbs(final Plot plot, final String flag) { - return getSettingFlagAbs(plot.getSettings(), flag); - } - - public static Flag getSettingFlagAbs(final PlotSettings settings, final String flag) { - if (settings.flags == null || settings.flags.isEmpty()) { - return null; - } - return settings.flags.get(flag); - } - - /** - * Add a flag to a plot - * @param origin - * @param flag - */ - public static boolean addPlotFlag(final Plot origin, final Flag flag) { - final boolean result = EventUtil.manager.callFlagAdd(flag, origin); - if (!result) { - return false; - } - for (Plot plot : origin.getConnectedPlots()) { - plot.getFlags().put(flag.getKey(), flag); - plot.reEnter(); - DBFunc.setFlags(plot, plot.getFlags().values()); - } - return true; - } - - public static boolean addPlotFlagAbs(final Plot plot, final Flag flag) { - final boolean result = EventUtil.manager.callFlagAdd(flag, plot); - if (!result) { - return false; - } - plot.getFlags().put(flag.getKey(), flag); - return true; - } - - public static boolean addClusterFlag(final PlotCluster cluster, final Flag flag) { - getSettingFlag(cluster.area, cluster.settings, flag.getKey()); - cluster.settings.flags.put(flag.getKey(), flag); - DBFunc.setFlags(cluster, cluster.settings.flags.values()); - return true; - } - - /** - * - * @param plot - * @return set of flags - */ - public static HashMap getPlotFlags(final Plot plot) { - if (!plot.hasOwner()) { - return null; - } - return getSettingFlags(plot.getArea(), plot.getSettings()); - } - - public static HashMap getPlotFlags(PlotArea area, final PlotSettings settings, final boolean ignorePluginflags) { - final HashMap flags = new HashMap<>(); - if (area != null && !area.DEFAULT_FLAGS.isEmpty()) { - flags.putAll(area.DEFAULT_FLAGS); - } - if (ignorePluginflags) { - for (final Map.Entry flag : settings.flags.entrySet()) { - if (isReserved(flag.getValue().getAbstractFlag().getKey())) { - continue; - } - flags.put(flag.getKey(), flag.getValue()); - } - } else { - flags.putAll(settings.flags); - } - - return flags; - } - - public static HashMap getSettingFlags(PlotArea area, final PlotSettings settings) { - return getPlotFlags(area, settings, false); - } - - public static boolean removePlotFlag(final Plot plot, final String id) { - final Flag flag = plot.getFlags().remove(id); - if (flag == null) { - return false; - } - final boolean result = EventUtil.manager.callFlagRemove(flag, plot); - if (!result) { - plot.getFlags().put(id, flag); - return false; - } - plot.reEnter(); - DBFunc.setFlags(plot, plot.getFlags().values()); - return true; - } - - public static boolean removeClusterFlag(final PlotCluster cluster, final String id) { - final Flag flag = cluster.settings.flags.remove(id); - if (flag == null) { - return false; - } - final boolean result = EventUtil.manager.callFlagRemove(flag, cluster); - if (!result) { - cluster.settings.flags.put(id, flag); - return false; - } - DBFunc.setFlags(cluster, cluster.settings.flags.values()); - return true; - } - - public static void setPlotFlags(final Plot origin, final Set flags) { - for (Plot plot : origin.getConnectedPlots()) { - if (flags != null && !flags.isEmpty()) { - plot.getFlags().clear(); - for (final Flag flag : flags) { - plot.getFlags().put(flag.getKey(), flag); - } - } else if (plot.getFlags().isEmpty()) { - return; - } else { - plot.getFlags().clear(); - } - plot.reEnter(); - DBFunc.setFlags(plot, plot.getFlags().values()); - } - } - - public static void setClusterFlags(final PlotCluster cluster, final Set flags) { - if (flags != null && !flags.isEmpty()) { - cluster.settings.flags.clear(); - for (final Flag flag : flags) { - cluster.settings.flags.put(flag.getKey(), flag); - } - } else if (cluster.settings.flags.isEmpty()) { - return; - } else { - cluster.settings.flags.clear(); - } - DBFunc.setFlags(cluster, cluster.settings.flags.values()); - } - - public static Flag[] removeFlag(final Flag[] flags, final String r) { - final Flag[] f = new Flag[flags.length - 1]; - int index = 0; - for (final Flag flag : flags) { - if (!flag.getKey().equals(r)) { - f[index++] = flag; - } - } - return f; - } - - public static Set removeFlag(final Set flags, final String r) { - final HashSet newflags = new HashSet<>(); - for (final Flag flag : flags) { - if (!flag.getKey().equalsIgnoreCase(r)) { - newflags.add(flag); - } - } - return newflags; - } - - /** - * Get a list of registered AbstractFlag objects - * - * @return List (AbstractFlag) - */ - public static HashSet getFlags() { - return flags; - } - - /** - * Get a list of registered AbstractFlag objects based on player permissions - * - * @param player with permissions - * - * @return List (AbstractFlag) - */ - public static List getFlags(final PlotPlayer player) { - final List returnFlags = new ArrayList<>(); - for (final AbstractFlag flag : flags) { - if (Permissions.hasPermission(player, "plots.set.flag." + flag.getKey().toLowerCase())) { - returnFlags.add(flag); - } - } - return returnFlags; - } - - /** - * Get an AbstractFlag by a string Returns null if flag does not exist - * - * @param string Flag Key - * - * @return AbstractFlag - */ - public static AbstractFlag getFlag(final String string) { - for (final AbstractFlag flag : flags) { - if (flag.getKey().equalsIgnoreCase(string)) { - return flag; - } - } - return null; - } - - /** - * Get an AbstractFlag by a string - * - * @param string Flag Key - * @param create If to create the flag if it does not exist - * - * @return AbstractFlag - */ - public static AbstractFlag getFlag(final String string, final boolean create) { - if (getFlag(string) == null && create) { - return new AbstractFlag(string); - } - return getFlag(string); - } - - /** - * Remove a registered AbstractFlag - * - * @param flag Flag Key - * - * @return boolean Result of operation - */ - public static boolean removeFlag(final AbstractFlag flag) { - return flags.remove(flag); - } - - public static HashMap parseFlags(final List flagstrings) { - final HashMap map = new HashMap<>(); - for (final String key : flagstrings) { - final String[] split; - if (key.contains(";")) { - split = key.split(";"); - } else { - split = key.split(":"); - } - Flag flag; - if (split.length == 1) { - flag = new Flag(getFlag(split[0], true), ""); - } else { - flag = new Flag(getFlag(split[0], true), split[1]); - } - map.put(flag.getKey(), flag); - } - return map; - } -} +//////////////////////////////////////////////////////////////////////////////////////////////////// +// PlotSquared - A plot manager and world generator for the Bukkit API / +// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / +// / +// This program is free software; you can redistribute it and/or modify / +// it under the terms of the GNU General Public License as published by / +// the Free Software Foundation; either version 3 of the License, or / +// (at your option) any later version. / +// / +// This program is distributed in the hope that it will be useful, / +// but WITHOUT ANY WARRANTY; without even the implied warranty of / +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / +// GNU General Public License for more details. / +// / +// You should have received a copy of the GNU General Public License / +// along with this program; if not, write to the Free Software Foundation, / +// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / +// / +// You can contact us via: support@intellectualsites.com / +//////////////////////////////////////////////////////////////////////////////////////////////////// +package com.intellectualcrafters.plot.flag; + +import com.intellectualcrafters.plot.PS; +import com.intellectualcrafters.plot.config.C; +import com.intellectualcrafters.plot.database.DBFunc; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotArea; +import com.intellectualcrafters.plot.object.PlotCluster; +import com.intellectualcrafters.plot.object.PlotPlayer; +import com.intellectualcrafters.plot.object.PlotSettings; +import com.intellectualcrafters.plot.object.RunnableVal; +import com.intellectualcrafters.plot.util.EventUtil; +import com.intellectualcrafters.plot.util.Permissions; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Flag Manager Utility + * + + + */ +public class FlagManager { + + private final static HashSet reserved = new HashSet<>(); + + private final static HashSet flags = new HashSet<>(); + + /** + * Reserve a flag so that it cannot be set by players + * @param flag + */ + public static void reserveFlag(final String flag) { + reserved.add(flag); + } + + /** + * Get if a flag is reserved + * @param flag + * @return + */ + public static boolean isReserved(final String flag) { + return reserved.contains(flag); + } + + /** + * Get the reserved flags + * @return + */ + public static HashSet getReservedFlags() { + return (HashSet) reserved.clone(); + } + + /** + * Unreserve a flag + * @param flag + */ + public static void unreserveFlag(final String flag) { + reserved.remove(flag); + } + + /** + * Register an AbstractFlag with PlotSquared + * + * @param af Flag to register + * + * @return boolean success + */ + public static boolean addFlag(final AbstractFlag af) { + return addFlag(af, false); + } + + public static boolean addFlag(final AbstractFlag af, final boolean reserved) { + PS.debug(C.PREFIX.s() + "&8 - Adding flag: &7" + af); + PS.get().foreachPlotArea(new RunnableVal() { + @Override + public void run(PlotArea value) { + final Flag flag = value.DEFAULT_FLAGS.get(af.getKey()); + if (flag != null) { + flag.setKey(af); + } + } + }); + PS.get().foreachPlotRaw(new RunnableVal() { + @Override + public void run(Plot value) { + final Flag flag = value.getFlags().get(af.getKey()); + if (flag != null) { + flag.setKey(af); + } + } + }); + if (flags.remove(af)) { + PS.debug("(Replaced existing flag)"); + } + flags.add(af); + if (reserved) { + reserveFlag(af.getKey()); + } + return false; + } + + public static Flag getSettingFlag(final PlotArea area, final PlotSettings settings, final String id) { + Flag flag; + if (settings.flags.isEmpty() || (flag = settings.flags.get(id)) == null) { + if (area == null) { + return null; + } + if (area.DEFAULT_FLAGS.isEmpty()) { + return null; + } + return area.DEFAULT_FLAGS.get(id); + } + return flag; + } + + public static boolean isBooleanFlag(final Plot plot, final String key, final boolean defaultValue) { + final Flag flag = FlagManager.getPlotFlagRaw(plot, key); + if (flag == null) { + return defaultValue; + } + final Object value = flag.getValue(); + if (value instanceof Boolean) { + return (boolean) value; + } + return defaultValue; + } + + /** + * Get the value of a flag for a plot (respects flag defaults) + * @param plot + * @param flag + * @return Flag + */ + public static Flag getPlotFlag(final Plot plot, final String flag) { + Flag result = getPlotFlagRaw(plot, flag); + return result == null ? null : (Flag) result.clone(); + } + + /** + * Returns the raw flag
+ * - Faster + * - You should not modify the flag + * @param plot + * @param flag + * @return + */ + public static Flag getPlotFlagRaw(final Plot plot, final String flag) { + if (plot.owner == null) { + return null; + } + return getSettingFlag(plot.getArea(), plot.getSettings(), flag); + } + + public static boolean isPlotFlagTrue(final Plot plot, final String strFlag) { + if (plot.owner == null) { + return false; + } + final Flag flag = getPlotFlagRaw(plot, strFlag); + return !(flag == null || !((Boolean) flag.getValue())); + } + + public static boolean isPlotFlagFalse(final Plot plot, final String strFlag) { + if (plot.owner == null) { + return false; + } + final Flag flag = getPlotFlagRaw(plot, strFlag); + if (flag == null || (Boolean) flag.getValue()) { + return false; + } + return false; + } + + /** + * Get the value of a flag for a plot (ignores flag defaults) + * @param plot + * @param flag + * @return Flag + */ + public static Flag getPlotFlagAbs(final Plot plot, final String flag) { + return getSettingFlagAbs(plot.getSettings(), flag); + } + + public static Flag getSettingFlagAbs(final PlotSettings settings, final String flag) { + if (settings.flags == null || settings.flags.isEmpty()) { + return null; + } + return settings.flags.get(flag); + } + + /** + * Add a flag to a plot + * @param origin + * @param flag + */ + public static boolean addPlotFlag(final Plot origin, final Flag flag) { + final boolean result = EventUtil.manager.callFlagAdd(flag, origin); + if (!result) { + return false; + } + for (Plot plot : origin.getConnectedPlots()) { + plot.getFlags().put(flag.getKey(), flag); + plot.reEnter(); + DBFunc.setFlags(plot, plot.getFlags().values()); + } + return true; + } + + public static boolean addPlotFlagAbs(final Plot plot, final Flag flag) { + final boolean result = EventUtil.manager.callFlagAdd(flag, plot); + if (!result) { + return false; + } + plot.getFlags().put(flag.getKey(), flag); + return true; + } + + public static boolean addClusterFlag(final PlotCluster cluster, final Flag flag) { + getSettingFlag(cluster.area, cluster.settings, flag.getKey()); + cluster.settings.flags.put(flag.getKey(), flag); + DBFunc.setFlags(cluster, cluster.settings.flags.values()); + return true; + } + + /** + * + * @param plot + * @return set of flags + */ + public static HashMap getPlotFlags(final Plot plot) { + if (!plot.hasOwner()) { + return null; + } + return getSettingFlags(plot.getArea(), plot.getSettings()); + } + + public static HashMap getPlotFlags(PlotArea area, final PlotSettings settings, final boolean ignorePluginflags) { + final HashMap flags = new HashMap<>(); + if (area != null && !area.DEFAULT_FLAGS.isEmpty()) { + flags.putAll(area.DEFAULT_FLAGS); + } + if (ignorePluginflags) { + for (final Map.Entry flag : settings.flags.entrySet()) { + if (isReserved(flag.getValue().getAbstractFlag().getKey())) { + continue; + } + flags.put(flag.getKey(), flag.getValue()); + } + } else { + flags.putAll(settings.flags); + } + + return flags; + } + + public static HashMap getSettingFlags(PlotArea area, final PlotSettings settings) { + return getPlotFlags(area, settings, false); + } + + public static boolean removePlotFlag(final Plot plot, final String id) { + final Flag flag = plot.getFlags().remove(id); + if (flag == null) { + return false; + } + final boolean result = EventUtil.manager.callFlagRemove(flag, plot); + if (!result) { + plot.getFlags().put(id, flag); + return false; + } + plot.reEnter(); + DBFunc.setFlags(plot, plot.getFlags().values()); + return true; + } + + public static boolean removeClusterFlag(final PlotCluster cluster, final String id) { + final Flag flag = cluster.settings.flags.remove(id); + if (flag == null) { + return false; + } + final boolean result = EventUtil.manager.callFlagRemove(flag, cluster); + if (!result) { + cluster.settings.flags.put(id, flag); + return false; + } + DBFunc.setFlags(cluster, cluster.settings.flags.values()); + return true; + } + + public static void setPlotFlags(final Plot origin, final Set flags) { + for (Plot plot : origin.getConnectedPlots()) { + if (flags != null && !flags.isEmpty()) { + plot.getFlags().clear(); + for (final Flag flag : flags) { + plot.getFlags().put(flag.getKey(), flag); + } + } else if (plot.getFlags().isEmpty()) { + return; + } else { + plot.getFlags().clear(); + } + plot.reEnter(); + DBFunc.setFlags(plot, plot.getFlags().values()); + } + } + + public static void setClusterFlags(final PlotCluster cluster, final Set flags) { + if (flags != null && !flags.isEmpty()) { + cluster.settings.flags.clear(); + for (final Flag flag : flags) { + cluster.settings.flags.put(flag.getKey(), flag); + } + } else if (cluster.settings.flags.isEmpty()) { + return; + } else { + cluster.settings.flags.clear(); + } + DBFunc.setFlags(cluster, cluster.settings.flags.values()); + } + + public static Flag[] removeFlag(final Flag[] flags, final String r) { + final Flag[] f = new Flag[flags.length - 1]; + int index = 0; + for (final Flag flag : flags) { + if (!flag.getKey().equals(r)) { + f[index++] = flag; + } + } + return f; + } + + public static Set removeFlag(final Set flags, final String r) { + final HashSet newflags = new HashSet<>(); + for (final Flag flag : flags) { + if (!flag.getKey().equalsIgnoreCase(r)) { + newflags.add(flag); + } + } + return newflags; + } + + /** + * Get a list of registered AbstractFlag objects + * + * @return List (AbstractFlag) + */ + public static HashSet getFlags() { + return flags; + } + + /** + * Get a list of registered AbstractFlag objects based on player permissions + * + * @param player with permissions + * + * @return List (AbstractFlag) + */ + public static List getFlags(final PlotPlayer player) { + final List returnFlags = new ArrayList<>(); + for (final AbstractFlag flag : flags) { + if (Permissions.hasPermission(player, "plots.set.flag." + flag.getKey().toLowerCase())) { + returnFlags.add(flag); + } + } + return returnFlags; + } + + /** + * Get an AbstractFlag by a string Returns null if flag does not exist + * + * @param string Flag Key + * + * @return AbstractFlag + */ + public static AbstractFlag getFlag(final String string) { + for (final AbstractFlag flag : flags) { + if (flag.getKey().equalsIgnoreCase(string)) { + return flag; + } + } + return null; + } + + /** + * Get an AbstractFlag by a string + * + * @param string Flag Key + * @param create If to create the flag if it does not exist + * + * @return AbstractFlag + */ + public static AbstractFlag getFlag(final String string, final boolean create) { + if (getFlag(string) == null && create) { + return new AbstractFlag(string); + } + return getFlag(string); + } + + /** + * Remove a registered AbstractFlag + * + * @param flag Flag Key + * + * @return boolean Result of operation + */ + public static boolean removeFlag(final AbstractFlag flag) { + return flags.remove(flag); + } + + public static HashMap parseFlags(final List flagstrings) { + final HashMap map = new HashMap<>(); + for (final String key : flagstrings) { + final String[] split; + if (key.contains(";")) { + split = key.split(";"); + } else { + split = key.split(":"); + } + Flag flag; + if (split.length == 1) { + flag = new Flag(getFlag(split[0], true), ""); + } else { + flag = new Flag(getFlag(split[0], true), split[1]); + } + map.put(flag.getKey(), flag); + } + return map; + } +} diff --git a/src/main/java/com/intellectualcrafters/plot/flag/FlagValue.java b/Core/src/main/java/com/intellectualcrafters/plot/flag/FlagValue.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/flag/FlagValue.java rename to Core/src/main/java/com/intellectualcrafters/plot/flag/FlagValue.java diff --git a/src/main/java/com/intellectualcrafters/plot/generator/AugmentedUtils.java b/Core/src/main/java/com/intellectualcrafters/plot/generator/AugmentedUtils.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/generator/AugmentedUtils.java rename to Core/src/main/java/com/intellectualcrafters/plot/generator/AugmentedUtils.java diff --git a/src/main/java/com/intellectualcrafters/plot/generator/ClassicPlotManager.java b/Core/src/main/java/com/intellectualcrafters/plot/generator/ClassicPlotManager.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/generator/ClassicPlotManager.java rename to Core/src/main/java/com/intellectualcrafters/plot/generator/ClassicPlotManager.java diff --git a/src/main/java/com/intellectualcrafters/plot/generator/ClassicPlotWorld.java b/Core/src/main/java/com/intellectualcrafters/plot/generator/ClassicPlotWorld.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/generator/ClassicPlotWorld.java rename to Core/src/main/java/com/intellectualcrafters/plot/generator/ClassicPlotWorld.java diff --git a/src/main/java/com/intellectualcrafters/plot/generator/GeneratorManager.java b/Core/src/main/java/com/intellectualcrafters/plot/generator/GeneratorManager.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/generator/GeneratorManager.java rename to Core/src/main/java/com/intellectualcrafters/plot/generator/GeneratorManager.java diff --git a/src/main/java/com/intellectualcrafters/plot/generator/GeneratorWrapper.java b/Core/src/main/java/com/intellectualcrafters/plot/generator/GeneratorWrapper.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/generator/GeneratorWrapper.java rename to Core/src/main/java/com/intellectualcrafters/plot/generator/GeneratorWrapper.java diff --git a/src/main/java/com/intellectualcrafters/plot/generator/GridPlotManager.java b/Core/src/main/java/com/intellectualcrafters/plot/generator/GridPlotManager.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/generator/GridPlotManager.java rename to Core/src/main/java/com/intellectualcrafters/plot/generator/GridPlotManager.java diff --git a/src/main/java/com/intellectualcrafters/plot/generator/GridPlotWorld.java b/Core/src/main/java/com/intellectualcrafters/plot/generator/GridPlotWorld.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/generator/GridPlotWorld.java rename to Core/src/main/java/com/intellectualcrafters/plot/generator/GridPlotWorld.java diff --git a/src/main/java/com/intellectualcrafters/plot/generator/HybridGen.java b/Core/src/main/java/com/intellectualcrafters/plot/generator/HybridGen.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/generator/HybridGen.java rename to Core/src/main/java/com/intellectualcrafters/plot/generator/HybridGen.java diff --git a/src/main/java/com/intellectualcrafters/plot/generator/HybridPlotManager.java b/Core/src/main/java/com/intellectualcrafters/plot/generator/HybridPlotManager.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/generator/HybridPlotManager.java rename to Core/src/main/java/com/intellectualcrafters/plot/generator/HybridPlotManager.java diff --git a/src/main/java/com/intellectualcrafters/plot/generator/HybridPlotWorld.java b/Core/src/main/java/com/intellectualcrafters/plot/generator/HybridPlotWorld.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/generator/HybridPlotWorld.java rename to Core/src/main/java/com/intellectualcrafters/plot/generator/HybridPlotWorld.java diff --git a/src/main/java/com/intellectualcrafters/plot/generator/HybridUtils.java b/Core/src/main/java/com/intellectualcrafters/plot/generator/HybridUtils.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/generator/HybridUtils.java rename to Core/src/main/java/com/intellectualcrafters/plot/generator/HybridUtils.java diff --git a/src/main/java/com/intellectualcrafters/plot/generator/IndependentPlotGenerator.java b/Core/src/main/java/com/intellectualcrafters/plot/generator/IndependentPlotGenerator.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/generator/IndependentPlotGenerator.java rename to Core/src/main/java/com/intellectualcrafters/plot/generator/IndependentPlotGenerator.java diff --git a/src/main/java/com/intellectualcrafters/plot/generator/PlotGenerator.java b/Core/src/main/java/com/intellectualcrafters/plot/generator/PlotGenerator.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/generator/PlotGenerator.java rename to Core/src/main/java/com/intellectualcrafters/plot/generator/PlotGenerator.java diff --git a/src/main/java/com/intellectualcrafters/plot/generator/SquarePlotManager.java b/Core/src/main/java/com/intellectualcrafters/plot/generator/SquarePlotManager.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/generator/SquarePlotManager.java rename to Core/src/main/java/com/intellectualcrafters/plot/generator/SquarePlotManager.java diff --git a/src/main/java/com/intellectualcrafters/plot/generator/SquarePlotWorld.java b/Core/src/main/java/com/intellectualcrafters/plot/generator/SquarePlotWorld.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/generator/SquarePlotWorld.java rename to Core/src/main/java/com/intellectualcrafters/plot/generator/SquarePlotWorld.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/BO3.java b/Core/src/main/java/com/intellectualcrafters/plot/object/BO3.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/BO3.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/BO3.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/BlockLoc.java b/Core/src/main/java/com/intellectualcrafters/plot/object/BlockLoc.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/BlockLoc.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/BlockLoc.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/BlockWrapper.java b/Core/src/main/java/com/intellectualcrafters/plot/object/BlockWrapper.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/BlockWrapper.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/BlockWrapper.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/ChunkLoc.java b/Core/src/main/java/com/intellectualcrafters/plot/object/ChunkLoc.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/ChunkLoc.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/ChunkLoc.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/CmdInstance.java b/Core/src/main/java/com/intellectualcrafters/plot/object/CmdInstance.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/CmdInstance.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/CmdInstance.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/ConsolePlayer.java b/Core/src/main/java/com/intellectualcrafters/plot/object/ConsolePlayer.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/ConsolePlayer.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/ConsolePlayer.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/FileBytes.java b/Core/src/main/java/com/intellectualcrafters/plot/object/FileBytes.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/FileBytes.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/FileBytes.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/LazyBlock.java b/Core/src/main/java/com/intellectualcrafters/plot/object/LazyBlock.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/LazyBlock.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/LazyBlock.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/LazyResult.java b/Core/src/main/java/com/intellectualcrafters/plot/object/LazyResult.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/LazyResult.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/LazyResult.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/Location.java b/Core/src/main/java/com/intellectualcrafters/plot/object/Location.java similarity index 96% rename from src/main/java/com/intellectualcrafters/plot/object/Location.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/Location.java index d5b1fb205..bf7bf0fa0 100644 --- a/src/main/java/com/intellectualcrafters/plot/object/Location.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/object/Location.java @@ -1,222 +1,222 @@ -package com.intellectualcrafters.plot.object; - -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.util.MathMan; - -/** - * Created 2015-02-11 for PlotSquared - * - - */ -public class Location implements Cloneable, Comparable { - private int x, y, z; - private float yaw, pitch; - private String world; - private boolean built; - - public Location(final String world, final int x, final int y, final int z, final float yaw, final float pitch) { - this.world = world; - this.x = x; - this.y = y; - this.z = z; - this.yaw = yaw; - this.pitch = pitch; - built = false; - } - - public Location() { - this("", 0, 0, 0, 0, 0); - } - - public Location(final String world, final int x, final int y, final int z) { - this(world, x, y, z, 0f, 0f); - } - - @Override - public Location clone() { - return new Location(world, x, y, z, yaw, pitch); - } - - public int getX() { - return x; - } - - public void setX(final int x) { - this.x = x; - built = false; - } - - public int getY() { - return y; - } - - public void setY(final int y) { - this.y = y; - built = false; - } - - public int getZ() { - return z; - } - - public void setZ(final int z) { - this.z = z; - built = false; - } - - public String getWorld() { - return world; - } - - public void setWorld(final String world) { - this.world = world; - built = false; - } - - public PlotArea getPlotArea() { - return PS.get().getPlotAreaAbs(this); - } - - public Plot getOwnedPlot() { - PlotArea area = PS.get().getPlotAreaAbs(this); - return area != null ? area.getOwnedPlot(this) : null; - } - - public Plot getOwnedPlotAbs() { - PlotArea area = PS.get().getPlotAreaAbs(this); - return area != null ? area.getOwnedPlotAbs(this) : null; - } - - public boolean isPlotArea() { - return PS.get().getPlotAreaAbs(this) != null; - } - - public boolean isPlotRoad() { - PlotArea area = PS.get().getPlotAreaAbs(this); - return area != null && area.getPlotAbs(this) == null; - } - - public boolean isUnownedPlotArea() { - PlotArea area = PS.get().getPlotAreaAbs(this); - return area != null && area.getOwnedPlotAbs(this) == null; - } - - public PlotManager getPlotManager() { - PlotArea pa = getPlotArea(); - return pa != null ? pa.getPlotManager() : null; - } - - public Plot getPlotAbs() { - PlotArea area = PS.get().getPlotAreaAbs(this); - return area != null ? area.getPlotAbs(this) : null; - } - - public Plot getPlot() { - PlotArea area = PS.get().getPlotAreaAbs(this); - return area != null ? area.getPlot(this) : null; - } - - public ChunkLoc getChunkLoc() { - return new ChunkLoc(x >> 4, z >> 4); - } - - public float getYaw() { - return yaw; - } - - public void setYaw(final float yaw) { - this.yaw = yaw; - built = false; - } - - public float getPitch() { - return pitch; - } - - public void setPitch(final float pitch) { - this.pitch = pitch; - built = false; - } - - public Location add(final int x, final int y, final int z) { - this.x += x; - this.y += y; - this.z += z; - built = false; - return this; - } - - public double getEuclideanDistanceSquared(final Location l2) { - final double x = getX() - l2.getX(); - final double y = getY() - l2.getY(); - final double z = getZ() - l2.getZ(); - return x * x + y * y + z * z; - } - - public double getEuclideanDistance(final Location l2) { - return Math.sqrt(getEuclideanDistanceSquared(l2)); - } - - public boolean isInSphere(final Location origin, final int radius) { - return getEuclideanDistanceSquared(origin) < radius * radius; - } - - @Override - public int hashCode() { - return MathMan.pair((short) x, (short) z) * 17 + y; - } - - public boolean isInAABB(final Location min, final Location max) { - return x >= min.getX() && x <= max.getX() && y >= min.getY() && y <= max.getY() && z >= min.getX() && z < max.getZ(); - } - - public void lookTowards(final int x, final int y) { - final double l = this.x - x; - final double c = Math.sqrt(l * l + 0.0); - if (Math.asin(0 / c) / Math.PI * 180 > 90) { - setYaw((float) (180 - -Math.asin(l / c) / Math.PI * 180)); - } else { - setYaw((float) (-Math.asin(l / c) / Math.PI * 180)); - } - built = false; - } - - public Location subtract(final int x, final int y, final int z) { - this.x -= x; - this.y -= y; - this.z -= z; - built = false; - return this; - } - - @Override - public boolean equals(final Object o) { - if (o == null) { - return false; - } - if (!(o instanceof Location)) { - return false; - } - final Location l = (Location) o; - return x == l.getX() && y == l.getY() && z == l.getZ() && world.equals(l.getWorld()) && yaw == l.getY() && pitch == l.getPitch(); - } - - @Override - public int compareTo(final Location o) { - if (o == null) { - throw new NullPointerException("Specified object was null"); - } - if (x == o.getX() && y == o.getY() || z == o.getZ()) { - return 0; - } - if (x < o.getX() && y < o.getY() && z < o.getZ()) { - return -1; - } - return 1; - } - - @Override - public String toString() { - return "\"plotsquaredlocation\":{" + "\"x\":" + x + ",\"y\":" + y + ",\"z\":" + z + ",\"yaw\":" + yaw + ",\"pitch\":" + pitch + ",\"world\":\"" + world + "\"}"; - } -} +package com.intellectualcrafters.plot.object; + +import com.intellectualcrafters.plot.PS; +import com.intellectualcrafters.plot.util.MathMan; + +/** + * Created 2015-02-11 for PlotSquared + * + + */ +public class Location implements Cloneable, Comparable { + private int x, y, z; + private float yaw, pitch; + private String world; + private boolean built; + + public Location(final String world, final int x, final int y, final int z, final float yaw, final float pitch) { + this.world = world; + this.x = x; + this.y = y; + this.z = z; + this.yaw = yaw; + this.pitch = pitch; + built = false; + } + + public Location() { + this("", 0, 0, 0, 0, 0); + } + + public Location(final String world, final int x, final int y, final int z) { + this(world, x, y, z, 0f, 0f); + } + + @Override + public Location clone() { + return new Location(world, x, y, z, yaw, pitch); + } + + public int getX() { + return x; + } + + public void setX(final int x) { + this.x = x; + built = false; + } + + public int getY() { + return y; + } + + public void setY(final int y) { + this.y = y; + built = false; + } + + public int getZ() { + return z; + } + + public void setZ(final int z) { + this.z = z; + built = false; + } + + public String getWorld() { + return world; + } + + public void setWorld(final String world) { + this.world = world; + built = false; + } + + public PlotArea getPlotArea() { + return PS.get().getPlotAreaAbs(this); + } + + public Plot getOwnedPlot() { + PlotArea area = PS.get().getPlotAreaAbs(this); + return area != null ? area.getOwnedPlot(this) : null; + } + + public Plot getOwnedPlotAbs() { + PlotArea area = PS.get().getPlotAreaAbs(this); + return area != null ? area.getOwnedPlotAbs(this) : null; + } + + public boolean isPlotArea() { + return PS.get().getPlotAreaAbs(this) != null; + } + + public boolean isPlotRoad() { + PlotArea area = PS.get().getPlotAreaAbs(this); + return area != null && area.getPlotAbs(this) == null; + } + + public boolean isUnownedPlotArea() { + PlotArea area = PS.get().getPlotAreaAbs(this); + return area != null && area.getOwnedPlotAbs(this) == null; + } + + public PlotManager getPlotManager() { + PlotArea pa = getPlotArea(); + return pa != null ? pa.getPlotManager() : null; + } + + public Plot getPlotAbs() { + PlotArea area = PS.get().getPlotAreaAbs(this); + return area != null ? area.getPlotAbs(this) : null; + } + + public Plot getPlot() { + PlotArea area = PS.get().getPlotAreaAbs(this); + return area != null ? area.getPlot(this) : null; + } + + public ChunkLoc getChunkLoc() { + return new ChunkLoc(x >> 4, z >> 4); + } + + public float getYaw() { + return yaw; + } + + public void setYaw(final float yaw) { + this.yaw = yaw; + built = false; + } + + public float getPitch() { + return pitch; + } + + public void setPitch(final float pitch) { + this.pitch = pitch; + built = false; + } + + public Location add(final int x, final int y, final int z) { + this.x += x; + this.y += y; + this.z += z; + built = false; + return this; + } + + public double getEuclideanDistanceSquared(final Location l2) { + final double x = getX() - l2.getX(); + final double y = getY() - l2.getY(); + final double z = getZ() - l2.getZ(); + return x * x + y * y + z * z; + } + + public double getEuclideanDistance(final Location l2) { + return Math.sqrt(getEuclideanDistanceSquared(l2)); + } + + public boolean isInSphere(final Location origin, final int radius) { + return getEuclideanDistanceSquared(origin) < radius * radius; + } + + @Override + public int hashCode() { + return MathMan.pair((short) x, (short) z) * 17 + y; + } + + public boolean isInAABB(final Location min, final Location max) { + return x >= min.getX() && x <= max.getX() && y >= min.getY() && y <= max.getY() && z >= min.getX() && z < max.getZ(); + } + + public void lookTowards(final int x, final int y) { + final double l = this.x - x; + final double c = Math.sqrt(l * l + 0.0); + if (Math.asin(0 / c) / Math.PI * 180 > 90) { + setYaw((float) (180 - -Math.asin(l / c) / Math.PI * 180)); + } else { + setYaw((float) (-Math.asin(l / c) / Math.PI * 180)); + } + built = false; + } + + public Location subtract(final int x, final int y, final int z) { + this.x -= x; + this.y -= y; + this.z -= z; + built = false; + return this; + } + + @Override + public boolean equals(final Object o) { + if (o == null) { + return false; + } + if (!(o instanceof Location)) { + return false; + } + final Location l = (Location) o; + return x == l.getX() && y == l.getY() && z == l.getZ() && world.equals(l.getWorld()) && yaw == l.getY() && pitch == l.getPitch(); + } + + @Override + public int compareTo(final Location o) { + if (o == null) { + throw new NullPointerException("Specified object was null"); + } + if (x == o.getX() && y == o.getY() || z == o.getZ()) { + return 0; + } + if (x < o.getX() && y < o.getY() && z < o.getZ()) { + return -1; + } + return 1; + } + + @Override + public String toString() { + return "\"plotsquaredlocation\":{" + "\"x\":" + x + ",\"y\":" + y + ",\"z\":" + z + ",\"yaw\":" + yaw + ",\"pitch\":" + pitch + ",\"world\":\"" + world + "\"}"; + } +} diff --git a/src/main/java/com/intellectualcrafters/plot/object/OfflinePlotPlayer.java b/Core/src/main/java/com/intellectualcrafters/plot/object/OfflinePlotPlayer.java similarity index 93% rename from src/main/java/com/intellectualcrafters/plot/object/OfflinePlotPlayer.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/OfflinePlotPlayer.java index 2f31cb58f..26c3cdc6e 100644 --- a/src/main/java/com/intellectualcrafters/plot/object/OfflinePlotPlayer.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/object/OfflinePlotPlayer.java @@ -1,18 +1,18 @@ -package com.intellectualcrafters.plot.object; - -import java.util.UUID; - -/** - * Created 2015-02-20 for PlotSquared - * - - */ -public interface OfflinePlotPlayer { - UUID getUUID(); - - long getLastPlayed(); - - boolean isOnline(); - - String getName(); -} +package com.intellectualcrafters.plot.object; + +import java.util.UUID; + +/** + * Created 2015-02-20 for PlotSquared + * + + */ +public interface OfflinePlotPlayer { + UUID getUUID(); + + long getLastPlayed(); + + boolean isOnline(); + + String getName(); +} diff --git a/src/main/java/com/intellectualcrafters/plot/object/Plot.java b/Core/src/main/java/com/intellectualcrafters/plot/object/Plot.java similarity index 97% rename from src/main/java/com/intellectualcrafters/plot/object/Plot.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/Plot.java index d1574c9f1..a6b5d317d 100644 --- a/src/main/java/com/intellectualcrafters/plot/object/Plot.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/object/Plot.java @@ -1,2728 +1,2728 @@ -//////////////////////////////////////////////////////////////////////////////////////////////////// -// PlotSquared - A plot manager and world generator for the Bukkit API / -// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / -// / -// This program is free software; you can redistribute it and/or modify / -// it under the terms of the GNU General Public License as published by / -// the Free Software Foundation; either version 3 of the License, or / -// (at your option) any later version. / -// / -// This program is distributed in the hope that it will be useful, / -// but WITHOUT ANY WARRANTY; without even the implied warranty of / -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / -// GNU General Public License for more details. / -// / -// You should have received a copy of the GNU General Public License / -// along with this program; if not, write to the Free Software Foundation, / -// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / -// / -// You can contact us via: support@intellectualsites.com / -//////////////////////////////////////////////////////////////////////////////////////////////////// -package com.intellectualcrafters.plot.object; - -import java.awt.Rectangle; -import java.awt.geom.Area; -import java.awt.geom.PathIterator; -import java.io.File; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map.Entry; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicInteger; - -import com.google.common.collect.BiMap; -import com.intellectualcrafters.jnbt.CompoundTag; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Configuration; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.flag.Flag; -import com.intellectualcrafters.plot.flag.FlagManager; -import com.intellectualcrafters.plot.util.BO3Handler; -import com.intellectualcrafters.plot.util.ChunkManager; -import com.intellectualcrafters.plot.util.EventUtil; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.SchematicHandler; -import com.intellectualcrafters.plot.util.SetQueue; -import com.intellectualcrafters.plot.util.TaskManager; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.intellectualcrafters.plot.util.WorldUtil; -import com.plotsquared.listener.PlotListener; - -/** - * The plot class - */ -@SuppressWarnings("javadoc") -public class Plot { - /** - * @deprecated raw access is deprecated - */ - @Deprecated - private static HashSet connected_cache; - private static HashSet regions_cache; - /** - * plot ID - * Direct access is Deprecated: use getId() - */ - @Deprecated - public final PlotId id; - /** - * plot owner - * (Merged plots can have multiple owners) - * Direct access is Deprecated: use getOwners() - */ - @Deprecated - public UUID owner; - /** - * Plot creation timestamp (not accurate if the plot was created before this was implemented)
- * - Milliseconds since the epoch
- * Direct access is Deprecated: use {@link #getTimestamp() getTimestamp} - */ - @Deprecated - public long timestamp; - /** - * List of trusted (with plot permissions) - * Direct access is Deprecated: use getTrusted() - */ - @Deprecated - public HashSet trusted; - /** - * List of members users (with plot permissions) - * Direct access is Deprecated: use getMembers() - */ - @Deprecated - public HashSet members; - /** - * List of denied players - * Direct access is Deprecated: use getDenied() - */ - @Deprecated - public HashSet denied; - /** - * External settings class
- * - Please favor the methods over direct access to this class
- * - The methods are more likely to be left unchanged from version changes
- * Direct access is Deprecated: use getSettings() - */ - @Deprecated - public PlotSettings settings; - /** - * Has the plot changed since the last save cycle? - */ - public boolean countsTowardsMax = true; - /** - * Represents whatever the database manager needs it to:
- * - A value of -1 usually indicates the plot will not be stored in the DB
- * - A value of 0 usually indicates that the DB manager hasn't set a value
- * @deprecated magical - */ - @Deprecated - public int temp; - /** - * plot world - * Direct access is Deprecated: use getWorld() - */ - private PlotArea area; - /** - * Session only plot metadata (session is until the server stops)
- *
- * For persistent metadata use the flag system - * @see FlagManager - */ - private ConcurrentHashMap meta; - /** - * The cached origin plot
- * - The origin plot is used for plot grouping and relational data - */ - private Plot origin; - - /** - * Constructor for a new plot
- * (Only changes after plot.create() will be properly set in the database) - * - * @see Plot#getPlot(Location) for existing plots - * - * @param area - * @param id - * @param owner - */ - public Plot(final PlotArea area, final PlotId id, final UUID owner) { - this.area = area; - this.id = id; - this.owner = owner; - } - - /** - * Constructor for an unowned plot
- * (Only changes after plot.create() will be properly set in the database) - * - * @see Plot#getPlot(Location) for existing plots - * - * @param area - * @param id - */ - public Plot(final PlotArea area, final PlotId id) { - this.area = area; - this.id = id; - } - - /** - * Constructor for a temporary plot (use -1 for temp)
- * The database will ignore any queries regarding temporary plots. - * Please note that some bulk plot management functions may still affect temporary plots (TODO: fix this) - * - * @see Plot#getPlot(Location) for existing plots - * - * @param area - * @param id - * @param owner - * @param temp - */ - public Plot(final PlotArea area, final PlotId id, final UUID owner, final int temp) { - this.area = area; - this.id = id; - this.owner = owner; - this.temp = temp; - } - - /** - * Constructor for a saved plots (Used by the database manager when plots are fetched) - * - * @see Plot#getPlot(Location) for existing plots - * - * @param id - * @param owner - * @param trusted - * @param denied - * @param merged - */ - public Plot(final PlotId id, final UUID owner, final HashSet trusted, final HashSet members, final HashSet denied, final String alias, final BlockLoc position, - final Collection flags, final PlotArea area, final boolean[] merged, final long timestamp, final int temp) { - this.id = id; - this.area = area; - this.owner = owner; - this.settings = new PlotSettings(); - this.members = members; - this.trusted = trusted; - this.denied = denied; - this.settings.setAlias(alias); - this.settings.setPosition(position); - this.settings.setMerged(merged); - if (flags != null) { - for (final Flag flag : flags) { - this.settings.flags.put(flag.getKey(), flag); - } - } - this.timestamp = timestamp; - this.temp = temp; - } - - public static Plot fromString(final PlotArea defaultArea, final String string) { - final String[] split = string.split(";|,"); - if (split.length == 2) { - if (defaultArea != null) { - final PlotId id = PlotId.fromString(split[0] + ";" + split[1]); - return id != null ? defaultArea.getPlotAbs(id) : null; - } - } else if (split.length == 3) { - final PlotArea pa = PS.get().getPlotArea(split[0], null); - if (pa != null) { - final PlotId id = PlotId.fromString(split[1] + ";" + split[2]); - return pa.getPlotAbs(id); - } - } else if (split.length == 4) { - final PlotArea pa = PS.get().getPlotArea(split[0], split[1]); - if (pa != null) { - final PlotId id = PlotId.fromString(split[1] + ";" + split[2]); - return pa.getPlotAbs(id); - } - } - return null; - } - - /** - * Return a new/cached plot object at a given location - * - * @see PlotPlayer#getCurrentPlot() if a player is expected here. - * - * @param loc - * @return - */ - public static Plot getPlot(final Location loc) { - final PlotArea pa = PS.get().getPlotAreaAbs(loc); - if (pa != null) { - return pa.getPlot(loc); - } - return null; - } - - /** - * Session only plot metadata (session is until the server stops)
- *
- * For persistent metadata use the flag system - * @see FlagManager - * @param key - * @param value - */ - public void setMeta(final String key, final Object value) { - if (this.meta == null) { - this.meta = new ConcurrentHashMap<>(); - } - this.meta.put(key, value); - } - - /** - * Get the metadata for a key
- *
- * For persistent metadata use the flag system - * @param key - * @return - */ - public Object getMeta(final String key) { - if (this.meta != null) { - return this.meta.get(key); - } - return null; - } - - /** - * Delete the metadata for a key
- * - metadata is session only - * - deleting other plugin's metadata may cause issues - * @param key - */ - public void deleteMeta(final String key) { - if (this.meta != null) { - this.meta.remove(key); - } - } - - /** - * Get the cluster this plot is associated with - * @return the PlotCluster object, or null - */ - public PlotCluster getCluster() { - return this.getArea().getCluster(this.id); - } - - /** - * Efficiently get the players currently inside this plot
- * - Will return an empty list if no players are in the plot
- * - Remember, you can cast a PlotPlayer to it's respective implementation (BukkitPlayer, SpongePlayer) to obtain the player object - * @return list of PlotPlayer(s) or an empty list - */ - public List getPlayersInPlot() { - final ArrayList players = new ArrayList<>(); - for (final Entry entry : UUIDHandler.getPlayers().entrySet()) { - final PlotPlayer pp = entry.getValue(); - if (this.equals(pp.getCurrentPlot())) { - players.add(pp); - } - } - return players; - } - - /** - * Check if the plot has a set owner - * - * @return false if there is no owner - */ - public boolean hasOwner() { - return this.owner != null; - } - - /** - * Check if a UUID is a plot owner (merged plots may have multiple owners) - * @param uuid - * @return - */ - public boolean isOwner(final UUID uuid) { - if (uuid.equals(owner)) { - return true; - } - if (!isMerged()) { - return false; - } - HashSet connected = getConnectedPlots(); - for (Plot current : connected) { - if (uuid.equals(current.owner)) { - return true; - } - } - return false; - } - - public boolean isOwnerAbs(final UUID uuid) { - return uuid.equals(owner); - } - - /** - * Get a list of owner UUIDs for a plot (supports multi-owner mega-plots) - * @return - */ - public HashSet getOwners() { - if (owner == null) { - return new HashSet(); - } - if (isMerged()) { - HashSet plots = getConnectedPlots(); - final HashSet owners = new HashSet(2); - UUID last = owner; - owners.add(owner); - for (Plot current : plots) { - if (last == null || current.owner.getMostSignificantBits() != last.getMostSignificantBits()) { - owners.add(current.owner); - last = current.owner; - } - } - return owners; - } - return new HashSet<>(Collections.singletonList(owner)); - } - - /** - * Check if the player is either the owner or on the trusted/added list - * - * @param uuid - * - * @return true if the player is added/trusted or is the owner - */ - public boolean isAdded(final UUID uuid) { - if (owner == null) { - return false; - } - if (getDenied().contains(uuid)) { - return false; - } - if (getTrusted().contains(uuid) || getTrusted().contains(DBFunc.everyone)) { - return true; - } - if (isOwner(uuid)) { - return true; - } - if (getMembers().contains(uuid) || getMembers().contains(DBFunc.everyone)) { - if (isOnline()) { - return true; - } - } - return false; - } - - /** - * Should the player be denied from entering? - * - * @param uuid - * - * @return boolean false if the player is allowed to enter - */ - public boolean isDenied(final UUID uuid) { - return (this.denied != null) && ((this.denied.contains(DBFunc.everyone) && !this.isAdded(uuid)) || (!this.isAdded(uuid) && this.denied.contains(uuid))); - } - - /** - * Get the plot ID - */ - public PlotId getId() { - return this.id; - } - - /** - * Get the plot world object for this plot
- * - The generic PlotArea object can be casted to its respective class for more control (e.g. HybridPlotWorld) - * @return PlotArea - */ - public PlotArea getArea() { - return this.area; - } - - public void setArea(final PlotArea area) { - if (this.getArea() != null) { - this.area.removePlot(this.id); - } - this.area = area; - area.addPlot(this); - } - - /** - * Get the plot manager object for this plot
- * - The generic PlotManager object can be casted to its respective class for more control (e.g. HybridPlotManager) - * @return PlotManager - */ - public PlotManager getManager() { - return this.area.getPlotManager(); - } - - /** - * Get or create plot settings - * @return PlotSettings - * @deprecated use equivalent plot method; - */ - @Deprecated - public PlotSettings getSettings() { - if (this.settings == null) { - this.settings = new PlotSettings(); - } - return this.settings; - } - - /** - * Returns true if the plot is not merged, or it is the base plot of multiple merged plots - * @return - */ - public boolean isBasePlot() { - if ((this.settings == null) || !this.isMerged()) { - return true; - } - return this.equals(this.getBasePlot(false)); - } - - /** - * The base plot is an arbitrary but specific connected plot. It is useful for the following:
- * - Merged plots need to be treated as a single plot for most purposes
- * - Some data such as home location needs to be associated with the group rather than each plot
- * - If the plot is not merged it will return itself.
- * - The result is cached locally - * @return base Plot - */ - public Plot getBasePlot(final boolean recalculate) { - if ((this.origin != null) && !recalculate) { - if (this.equals(this.origin)) { - return this; - } - return this.origin.getBasePlot(false); - } - if (!this.isMerged()) { - this.origin = this; - return this.origin; - } - this.origin = this; - PlotId min = this.id; - for (final Plot plot : this.getConnectedPlots()) { - if ((plot.id.y < min.y) || (plot.id.y.equals(min.y) && (plot.id.x < min.x))) { - this.origin = plot; - min = plot.id; - } - } - for (final Plot plot : this.getConnectedPlots()) { - plot.origin = this.origin; - } - return this.origin; - } - - /** - * Check if the plot is merged in any direction - * @return - */ - public boolean isMerged() { - if (this.settings == null) { - return false; - } - return this.settings.getMerged(0) || this.settings.getMerged(2) || this.settings.getMerged(1) || this.settings.getMerged(3); - } - - /** - * Get the timestamp of when the plot was created (unreliable)
- * - not accurate if the plot was created before this was implemented
- * - Milliseconds since the epoch
- * @return - */ - public long getTimestamp() { - if (this.timestamp == 0) { - this.timestamp = System.currentTimeMillis(); - } - return this.timestamp; - } - - /** - * Get if the plot is merged in a direction
- * ------- Actual -------
- * 0 = north
- * 1 = east
- * 2 = south
- * 3 = west
- * ----- Artificial -----
- * 4 = north-east
- * 5 = south-east
- * 6 = south-west
- * 7 = north-west
- * ----------
- * Note: A plot that is merged north and east will not be merged northeast if the northeast plot is not part of the same group
- * @param direction - * @return true if merged in that direction - */ - public boolean getMerged(final int direction) { - if (this.settings == null) { - return false; - } - switch (direction) { - case 0: - case 1: - case 2: - case 3: - return this.settings.getMerged(direction); - case 7: - int i = direction - 4; - int i2 = 0; - if (this.settings.getMerged(i2)) { - if (this.settings.getMerged(i)) { - if (this.area.getPlotAbs(this.id.getRelative(i)).getMerged(i2)) { - if (this.area.getPlotAbs(this.id.getRelative(i2)).getMerged(i)) { - return true; - } - } - } - } - return false; - case 4: - case 5: - case 6: - i = direction - 4; - i2 = direction - 3; - return this.settings.getMerged(i2) - && this.settings.getMerged(i) - && this.area.getPlotAbs(this.id.getRelative(i)).getMerged(i2) - && this.area.getPlotAbs(this.id.getRelative(i2)).getMerged(i); - - } - return false; - } - - /** - * Get the denied users - * @return - */ - public HashSet getDenied() { - if (this.denied == null) { - this.denied = new HashSet<>(); - } - return this.denied; - } - - /** - * Set the denied users for this plot - * @param uuids - */ - public void setDenied(final Set uuids) { - boolean larger = uuids.size() > getDenied().size(); - HashSet intersection = new HashSet<>(larger ? getDenied() : uuids); - intersection.retainAll(larger ? uuids : getDenied()); - uuids.removeAll(intersection); - HashSet toRemove = new HashSet<>(getDenied()); - toRemove.removeAll(intersection); - for (UUID uuid : toRemove) { - removeDenied(uuid); - } - for (UUID uuid : uuids) { - addDenied(uuid); - } - } - - /** - * Get the trusted users - * @return - */ - public HashSet getTrusted() { - if (this.trusted == null) { - this.trusted = new HashSet<>(); - } - return this.trusted; - } - - /** - * Set the trusted users for this plot - * @param uuids - */ - public void setTrusted(final Set uuids) { - boolean larger = uuids.size() > getTrusted().size(); - HashSet intersection = new HashSet<>(larger ? getTrusted() : uuids); - intersection.retainAll(larger ? uuids : getTrusted()); - uuids.removeAll(intersection); - HashSet toRemove = new HashSet<>(getTrusted()); - toRemove.removeAll(intersection); - for (UUID uuid : toRemove) { - removeTrusted(uuid); - } - for (UUID uuid : uuids) { - addTrusted(uuid); - } - } - - /** - * Get the members - * @return - */ - public HashSet getMembers() { - if (this.members == null) { - this.members = new HashSet<>(); - } - return this.members; - } - - /** - * Set the members for this plot - * @param uuids - */ - public void setMembers(final Set uuids) { - boolean larger = uuids.size() > getMembers().size(); - HashSet intersection = new HashSet<>(larger ? getMembers() : uuids); - intersection.retainAll(larger ? uuids : getMembers()); - uuids.removeAll(intersection); - HashSet toRemove = new HashSet<>(getMembers()); - toRemove.removeAll(intersection); - for (UUID uuid : toRemove) { - removeMember(uuid); - } - for (UUID uuid : uuids) { - addMember(uuid); - } - } - - /** - * Deny someone (updates database as well) - * @param uuid - */ - public void addDenied(final UUID uuid) { - for (Plot current : getConnectedPlots()) { - if (current.getDenied().add(uuid)) { - DBFunc.setDenied(current, uuid); - } - } - } - - /** - * Add someone as a helper (updates database as well) - * - * @param uuid - */ - public void addTrusted(final UUID uuid) { - for (Plot current : getConnectedPlots()) { - if (current.getTrusted().add(uuid)) { - DBFunc.setTrusted(current, uuid); - } - } - } - - /** - * Add someone as a trusted user (updates database as well) - * - * @param uuid - */ - public void addMember(final UUID uuid) { - for (Plot current : getConnectedPlots()) { - if (current.getMembers().add(uuid)) { - DBFunc.setMember(current, uuid); - } - } - } - - /** - * Set the plot owner (and update the database) - * @param owner - */ - public void setOwner(final UUID owner) { - if (!hasOwner()) { - this.owner = owner; - create(); - return; - } - if (!isMerged()) { - if (!this.owner.equals(owner)) { - this.owner = owner; - DBFunc.setOwner(this, owner); - } - return; - } - for (Plot current : getConnectedPlots()) { - if (!owner.equals(current.owner)) { - current.owner = owner; - DBFunc.setOwner(current, owner); - } - } - } - - /** - * Clear a plot - * @see this#clear(Runnable) - * @see this#clear(boolean, boolean, Runnable) - * @see #deletePlot(Runnable) to clear and delete a plot - * @param whenDone A runnable to execute when clearing finishes, or null - */ - public void clear(final Runnable whenDone) { - this.clear(false, false, whenDone); - } - - public boolean clear(final boolean checkRunning, final boolean isDelete, final Runnable whenDone) { - if (checkRunning && (this.getRunning() != 0)) { - return false; - } - if (!EventUtil.manager.callClear(this)) { - return false; - } - final HashSet regions = this.getRegions(); - final HashSet plots = this.getConnectedPlots(); - final ArrayDeque queue = new ArrayDeque<>(plots); - if (isDelete) { - this.removeSign(); - } - this.unlinkPlot(true, !isDelete); - final PlotManager manager = this.area.getPlotManager(); - final Runnable run = new Runnable() { - @Override - public void run() { - if (queue.isEmpty()) { - final AtomicInteger finished = new AtomicInteger(0); - final Runnable run = new Runnable() { - @Override - public void run() { - if (finished.incrementAndGet() >= plots.size()) { - for (final RegionWrapper region : regions) { - final Location[] corners = region.getCorners(Plot.this.area.worldname); - ChunkManager.manager.clearAllEntities(corners[0], corners[1]); - } - TaskManager.runTask(whenDone); - } - } - }; - if (isDelete) { - for (final Plot current : plots) { - manager.unclaimPlot(Plot.this.area, current, run); - } - } else { - for (final Plot current : plots) { - manager.claimPlot(Plot.this.area, current); - SetQueue.IMP.addTask(run); - } - } - return; - } - final Plot current = queue.poll(); - if ((Plot.this.area.TERRAIN != 0) || Settings.FAST_CLEAR) { - ChunkManager.manager.regenerateRegion(current.getBottomAbs(), current.getTopAbs(), false, this); - return; - } - manager.clearPlot(Plot.this.area, current, this); - } - }; - run.run(); - return true; - } - - /** - * Set the biome for a plot asynchronously - * @param biome The biome e.g. "forest" - * @param whenDone The task to run when finished, or null - */ - public void setBiome(final String biome, final Runnable whenDone) { - final ArrayDeque regions = new ArrayDeque<>(this.getRegions()); - final Runnable run = new Runnable() { - @Override - public void run() { - if (regions.isEmpty()) { - Plot.this.refreshChunks(); - TaskManager.runTask(whenDone); - return; - } - final RegionWrapper region = regions.poll(); - final Location pos1 = new Location(Plot.this.area.worldname, region.minX, region.minY, region.minZ); - final Location pos2 = new Location(Plot.this.area.worldname, region.maxX, region.maxY, region.maxZ); - ChunkManager.chunkTask(pos1, pos2, new RunnableVal() { - @Override - public void run(final int[] value) { - final ChunkLoc loc = new ChunkLoc(value[0], value[1]); - ChunkManager.manager.loadChunk(Plot.this.area.worldname, loc, false); - MainUtil.setBiome(Plot.this.area.worldname, value[2], value[3], value[4], value[5], biome); - ChunkManager.manager.unloadChunk(Plot.this.area.worldname, loc, true, true); - } - }, this, 5); - - } - }; - run.run(); - } - - /** - * Unlink the plot and all connected plots - * @param createSign - * @param createRoad - * @return - */ - public boolean unlinkPlot(final boolean createRoad, final boolean createSign) { - if (!this.isMerged()) { - return false; - } - final HashSet plots = this.getConnectedPlots(); - final ArrayList ids = new ArrayList<>(plots.size()); - for (final Plot current : plots) { - current.setHome(null); - ids.add(current.getId()); - } - final boolean result = EventUtil.manager.callUnlink(this.area, ids); - if (!result) { - return false; - } - this.clearRatings(); - if (createSign) { - this.removeSign(); - } - final PlotManager manager = this.area.getPlotManager(); - if (createRoad) { - manager.startPlotUnlink(this.area, ids); - } - if ((this.area.TERRAIN != 3) && createRoad) { - for (final Plot current : plots) { - if (current.getMerged(1)) { - manager.createRoadEast(current.area, current); - if (current.getMerged(2)) { - manager.createRoadSouth(current.area, current); - if (current.getMerged(5)) { - manager.createRoadSouthEast(current.area, current); - } - } - } else if (current.getMerged(2)) { - manager.createRoadSouth(current.area, current); - } - } - } - for (final Plot current : plots) { - final boolean[] merged = new boolean[] { false, false, false, false }; - current.setMerged(merged); - if (createSign) { - current.setSign(MainUtil.getName(current.owner)); - } - } - if (createRoad) { - manager.finishPlotUnlink(this.area, ids); - } - return true; - } - - /** - * Set the sign for a plot to a specific name - * @param name - */ - public void setSign(final String name) { - if (!PS.get().isMainThread(Thread.currentThread())) { - TaskManager.runTask(new Runnable() { - @Override - public void run() { - Plot.this.setSign(name); - } - }); - return; - } - final String rename = name == null ? "unknown" : name; - final PlotManager manager = this.area.getPlotManager(); - if (this.area.ALLOW_SIGNS) { - final Location loc = manager.getSignLoc(this.area, this); - final String id = this.id.x + ";" + this.id.y; - final String[] lines = new String[] { - C.OWNER_SIGN_LINE_1.formatted().replaceAll("%id%", id), - C.OWNER_SIGN_LINE_2.formatted().replaceAll("%id%", id).replaceAll("%plr%", rename), - C.OWNER_SIGN_LINE_3.formatted().replaceAll("%id%", id).replaceAll("%plr%", rename), - C.OWNER_SIGN_LINE_4.formatted().replaceAll("%id%", id).replaceAll("%plr%", rename) }; - WorldUtil.IMP.setSign(this.area.worldname, loc.getX(), loc.getY(), loc.getZ(), lines); - } - } - - /** - * This will return null if the plot hasn't been analyzed - * @return analysis of plot - */ - public PlotAnalysis getComplexity() { - return PlotAnalysis.getAnalysis(this); - } - - public void analyze(final RunnableVal whenDone) { - PlotAnalysis.analyzePlot(this, whenDone); - } - - /** - * Set a flag for this plot - * @param flag - * @param value - */ - public void setFlag(final String flag, final Object value) { - FlagManager.addPlotFlag(this, new Flag(FlagManager.getFlag(flag), value)); - } - - /** - * Remove a flag from this plot - * @param flag - */ - public void removeFlag(final String flag) { - FlagManager.removePlotFlag(this, flag); - } - - /** - * Get the flag for a given key - * @param key - */ - public Flag getFlag(final String key) { - return FlagManager.getPlotFlagRaw(this, key); - } - - /** - * Delete a plot (use null for the runnable if you don't need to be notified on completion) - * @see PS#removePlot(Plot, boolean) - * @see #clear(Runnable) to simply clear a plot - */ - public boolean deletePlot(final Runnable whenDone) { - if (!this.hasOwner()) { - return false; - } - final HashSet plots = this.getConnectedPlots(); - this.clear(false, true, new Runnable() { - @Override - public void run() { - for (final Plot current : plots) { - current.unclaim(); - } - TaskManager.runTask(whenDone); - } - }); - return true; - } - - /** - * Count the entities in a plot - * @see ChunkManager#countEntities(Plot) - * 0 = Entity - * 1 = Animal - * 2 = Monster - * 3 = Mob - * 4 = Boat - * 5 = Misc - * @return - */ - public int[] countEntities() { - final int[] count = new int[6]; - for (final Plot current : this.getConnectedPlots()) { - final int[] result = ChunkManager.manager.countEntities(current); - count[0] += result[0]; - count[1] += result[1]; - count[2] += result[2]; - count[3] += result[3]; - count[4] += result[4]; - count[5] += result[5]; - } - return count; - } - - /** - * Returns true if a previous task was running - * @return - */ - public int addRunning() { - final int value = this.getRunning(); - for (final Plot plot : this.getConnectedPlots()) { - plot.setMeta("running", value + 1); - } - return value; - } - - public int removeRunning() { - final int value = this.getRunning(); - if (value < 2) { - for (final Plot plot : this.getConnectedPlots()) { - plot.deleteMeta("running"); - } - } else { - for (final Plot plot : this.getConnectedPlots()) { - plot.setMeta("running", value - 1); - } - } - return value; - } - - public int getRunning() { - final Integer value = (Integer) this.getMeta("running"); - return value == null ? 0 : value; - } - - public boolean unclaim() { - if (owner == null) { - return false; - } - for (Plot current : getConnectedPlots()) { - getArea().removePlot(getId()); - DBFunc.delete(current); - current.settings = null; - } - return true; - } - - /** - * Unlink a plot and remove the roads - * @see this#unlinkPlot(boolean, boolean) - * @return true if plot was linked - */ - public boolean unlink() { - return this.unlinkPlot(true, true); - } - - public Location getCenter() { - final Location top = this.getTop(); - final Location bot = this.getBottom(); - return new Location(this.area.worldname, (top.getX() + bot.getX()) / 2, (top.getY() + bot.getY()) / 2, (top.getZ() + bot.getZ()) / 2); - } - - /** - * Return the home location for the plot - * @return Home location - */ - public Location getHome() { - final BlockLoc home = this.getPosition(); - if ((home == null) || ((home.x == 0) && (home.z == 0))) { - return this.getDefaultHome(); - } else { - final Location bot = this.getBottomAbs(); - final Location loc = new Location(bot.getWorld(), bot.getX() + home.x, bot.getY() + home.y, bot.getZ() + home.z, home.yaw, home.pitch); - if (WorldUtil.IMP.getBlock(loc).id != 0) { - loc.setY(Math.max(WorldUtil.IMP.getHighestBlock(this.area.worldname, loc.getX(), loc.getZ()), bot.getY())); - } - return loc; - } - } - - /** - * Set the home location - * @param loc - */ - public void setHome(final BlockLoc loc) { - final BlockLoc pos = this.getSettings().getPosition(); - if ((((pos == null) || pos.equals(new BlockLoc(0, 0, 0))) && (loc == null)) || ((pos != null) && pos.equals(loc))) { - return; - } - final Plot plot = this.getBasePlot(false); - plot.getSettings().setPosition(loc); - if (plot.getSettings().getPosition() == null) { - DBFunc.setPosition(plot, ""); - } else { - DBFunc.setPosition(plot, this.getSettings().getPosition().toString()); - } - } - - /** - * Get the default home location for a plot
- * - Ignores any home location set for that specific plot - * @return - */ - public Location getDefaultHome() { - final Plot plot = this.getBasePlot(false); - if (this.area.DEFAULT_HOME != null) { - final int x; - final int z; - if ((this.area.DEFAULT_HOME.x == Integer.MAX_VALUE) && (this.area.DEFAULT_HOME.z == Integer.MAX_VALUE)) { - // center - final RegionWrapper largest = plot.getLargestRegion(); - x = ((largest.maxX - largest.minX) / 2) + largest.minX; - z = ((largest.maxZ - largest.minZ) / 2) + largest.minZ; - } else { - // specific - final Location bot = plot.getBottomAbs(); - x = bot.getX() + this.area.DEFAULT_HOME.x; - z = bot.getZ() + this.area.DEFAULT_HOME.z; - } - final int y = WorldUtil.IMP.getHighestBlock(plot.area.worldname, x, z); - return new Location(plot.area.worldname, x, y + 1, z); - } - // Side - final RegionWrapper largest = plot.getLargestRegion(); - final int x = ((largest.maxX - largest.minX) / 2) + largest.minX; - final int z = largest.minZ - 1; - final PlotManager manager = plot.getManager(); - final int y = Math.max(WorldUtil.IMP.getHighestBlock(plot.area.worldname, x, z), manager.getSignLoc(plot.area, plot).getY()); - return new Location(plot.area.worldname, x, y + 1, z); - } - - /** - * Get the average rating of the plot. This is the value displayed in /plot info - * @return average rating as double - */ - public double getAverageRating() { - double sum = 0; - final Collection ratings = this.getRatings().values(); - for (final Rating rating : ratings) { - sum += rating.getAverageRating(); - } - return sum / ratings.size(); - } - - /** - * Set a rating for a user
- * - If the user has already rated, the following will return false - * @param uuid - * @param rating - * @return - */ - public boolean addRating(final UUID uuid, final Rating rating) { - final Plot base = this.getBasePlot(false); - final PlotSettings baseSettings = base.getSettings(); - if (baseSettings.getRatings().containsKey(uuid)) { - return false; - } - baseSettings.getRatings().put(uuid, rating.getAggregate()); - DBFunc.setRating(base, uuid, this.temp); - return true; - } - - /** - * Clear the ratings for this plot - */ - public void clearRatings() { - final Plot base = this.getBasePlot(false); - final PlotSettings baseSettings = base.getSettings(); - if ((baseSettings.ratings != null) && !baseSettings.ratings.isEmpty()) { - DBFunc.deleteRatings(base); - baseSettings.ratings = null; - } - } - - /** - * Get the ratings associated with a plot
- * - The rating object may contain multiple categories - * @return Map of user who rated to the rating - */ - public HashMap getRatings() { - final Plot base = this.getBasePlot(false); - final HashMap map = new HashMap<>(); - if (base.getSettings().ratings == null) { - return map; - } - for (final Entry entry : base.getSettings().ratings.entrySet()) { - map.put(entry.getKey(), new Rating(entry.getValue())); - } - return map; - } - - public boolean hasRatings() { - Plot base = this.getBasePlot(false); - return base.settings != null && base.settings.ratings != null; - } - - /** - * Resend all chunks inside the plot to nearby players
- * This should not need to be called - */ - public void refreshChunks() { - TaskManager.runTask(new Runnable() { - @Override - public void run() { - final HashSet chunks = new HashSet<>(); - for (final RegionWrapper region : Plot.this.getRegions()) { - for (int x = region.minX >> 4; x <= (region.maxX >> 4); x++) { - for (int z = region.minZ >> 4; z <= (region.maxZ >> 4); z++) { - chunks.add(new ChunkLoc(x, z)); - } - } - } - SetQueue.IMP.queue.sendChunk(Plot.this.area.worldname, chunks); - } - }); - } - - /** - * Remove the plot sign if it is set - */ - public void removeSign() { - final PlotManager manager = this.area.getPlotManager(); - if (!this.area.ALLOW_SIGNS) { - return; - } - final Location loc = manager.getSignLoc(this.area, this); - SetQueue.IMP.setBlock(this.area.worldname, loc.getX(), loc.getY(), loc.getZ(), 0); - } - - /** - * Set the plot sign if plot signs are enabled - */ - public void setSign() { - if (this.owner == null) { - this.setSign(null); - return; - } - this.setSign(UUIDHandler.getName(this.owner)); - } - - /** - * Register a plot and create it in the database
- * - The plot will not be created if the owner is null
- * - Any setting from before plot creation will not be saved until the server is stopped properly. i.e. Set any values/options after plot creation. - * @return true if plot was created successfully - */ - public boolean create() { - return this.create(this.owner, true); - } - - /** - * Register a plot and create it in the database
- * - The plot will not be created if the owner is null
- * - Any setting from before plot creation will not be saved until the server is stopped properly. i.e. Set any values/options after plot creation. - * @return true if plot was created successfully - */ - public boolean create(final UUID uuid, final boolean notify) { - if (uuid == null) { - throw new IllegalArgumentException("UUID cannot be null"); - } - this.owner = uuid; - final Plot existing = this.area.getOwnedPlotAbs(this.id); - if (existing != null) { - throw new IllegalStateException("Plot already exists!"); - } - if (notify) { - final Integer meta = (Integer) this.area.getMeta("worldBorder"); - if (meta != null) { - this.updateWorldBorder(); - } - } - connected_cache = null; - regions_cache = null; - this.getTrusted().clear(); - this.getMembers().clear(); - this.getDenied().clear(); - this.settings = new PlotSettings(); - if (this.area.addPlot(this)) { - DBFunc.createPlotAndSettings(Plot.this, new Runnable() { - @Override - public void run() { - final PlotArea plotworld = Plot.this.area; - if (notify && plotworld.AUTO_MERGE) { - Plot.this.autoMerge(-1, Integer.MAX_VALUE, uuid, true); - } - } - }); - return true; - } - return false; - } - - /** - * Set components such as border, wall, floor - * (components are generator specific) - */ - public boolean setComponent(final String component, final String blocks) { - final PlotBlock[] parsed = Configuration.BLOCKLIST.parseString(blocks); - if ((parsed == null) || (parsed.length == 0)) { - return false; - } - return this.setComponent(component, parsed); - } - - /** - * Get the biome (String) - */ - public String getBiome() { - final Location loc = this.getBottomAbs(); - return WorldUtil.IMP.getBiome(loc.getWorld(), loc.getX(), loc.getZ()); - } - - /** - * Return the top location for the plot - * @return - */ - public Location getTopAbs() { - return this.area.getPlotManager().getPlotTopLocAbs(this.area, this.id); - } - - /** - * Return the bottom location for the plot - * @return - */ - public Location getBottomAbs() { - return this.area.getPlotManager().getPlotBottomLocAbs(this.area, this.id); - } - - /** - * Swap the settings for two plots - * @param p2 - * @param whenDone - * @return - */ - public boolean swapData(final Plot p2, final Runnable whenDone) { - if (this.owner == null) { - if ((p2 != null) && p2.hasOwner()) { - p2.moveData(this, whenDone); - return true; - } - return false; - } - if ((p2 == null) || (p2.owner == null)) { - this.moveData(p2, whenDone); - return true; - } - // Swap cached - final PlotId temp = new PlotId(this.getId().x, this.getId().y); - this.getId().x = p2.getId().x; - this.getId().y = p2.getId().y; - p2.getId().x = temp.x; - p2.getId().y = temp.y; - this.area.removePlot(this.getId()); - p2.area.removePlot(p2.getId()); - this.getId().recalculateHash(); - p2.getId().recalculateHash(); - this.area.addPlotAbs(this); - p2.area.addPlotAbs(p2); - // Swap database - DBFunc.dbManager.swapPlots(p2, this); - TaskManager.runTaskLater(whenDone, 1); - return true; - } - - /** - * Move the settings for a plot - * @param pos2 - * @param whenDone - * @return - */ - public boolean moveData(final Plot pos2, final Runnable whenDone) { - if (this.owner == null) { - PS.debug(pos2 + " is unowned (single)"); - TaskManager.runTask(whenDone); - return false; - } - if (pos2.hasOwner()) { - PS.debug(pos2 + " is unowned (multi)"); - TaskManager.runTask(whenDone); - return false; - } - this.area.removePlot(this.id); - this.getId().x = pos2.getId().x; - this.getId().y = pos2.getId().y; - this.getId().recalculateHash(); - this.area.addPlotAbs(this); - DBFunc.movePlot(this, pos2); - TaskManager.runTaskLater(whenDone, 1); - return true; - } - - /** - * Gets the top loc of a plot (if mega, returns top loc of that mega plot) - If you would like each plot treated as - * a small plot use getPlotTopLocAbs(...) - * - * @return Location top of mega plot - */ - public Location getExtendedTopAbs() { - final Location top = this.getTopAbs(); - if (!this.isMerged()) { - return top; - } - if (this.getMerged(2)) { - top.setZ(this.getRelative(2).getBottomAbs().getZ() - 1); - } - if (this.getMerged(1)) { - top.setX(this.getRelative(1).getBottomAbs().getX() - 1); - } - return top; - } - - /** - * Gets the bottom location for a plot.
- * - Does not respect mega plots
- * - Merged plots, only the road will be considered part of the plot
- * - * @return Location bottom of mega plot - */ - public Location getExtendedBottomAbs() { - final Location bot = this.getBottomAbs(); - if (!this.isMerged()) { - return bot; - } - if (this.getMerged(0)) { - bot.setZ(this.getRelative(0).getTopAbs().getZ() + 1); - } - if (this.getMerged(3)) { - bot.setX(this.getRelative(3).getTopAbs().getX() + 1); - } - return bot; - } - - /** - * Returns the top and bottom location.
- * - If the plot is not connected, it will return its own corners
- * - the returned locations will not necessarily correspond to claimed plots if the connected plots do not form a rectangular shape - * @deprecated as merged plots no longer need to be rectangular - * @return new Location[] { bottom, top } - */ - @Deprecated - public Location[] getCorners() { - if (!this.isMerged()) { - return new Location[] { this.getBottomAbs(), this.getTopAbs() }; - } - return MainUtil.getCorners(this.area.worldname, this.getRegions()); - } - - /** - * Remove the east road section of a plot
- * - Used when a plot is merged
- */ - public void removeRoadEast() { - if ((this.area.TYPE != 0) && (this.area.TERRAIN > 1)) { - if (this.area.TERRAIN == 3) { - return; - } - final Plot other = this.getRelative(1); - final Location bot = other.getBottomAbs(); - final Location top = this.getTopAbs(); - final Location pos1 = new Location(this.area.worldname, top.getX(), 0, bot.getZ()); - final Location pos2 = new Location(this.area.worldname, bot.getX(), 256, top.getZ()); - ChunkManager.manager.regenerateRegion(pos1, pos2, true, null); - } else { - this.area.getPlotManager().removeRoadEast(this.area, this); - } - } - - /** - * Returns the top and bottom plot id.
- * - If the plot is not connected, it will return itself for the top/bottom
- * - the returned ids will not necessarily correspond to claimed plots if the connected plots do not form a rectangular shape - * @deprecated as merged plots no longer need to be rectangular - * @return new Plot[] { bottom, top } - */ - @Deprecated - public PlotId[] getCornerIds() { - if (!this.isMerged()) { - return new PlotId[] { this.getId(), this.getId() }; - } - final PlotId min = new PlotId(this.getId().x, this.getId().y); - final PlotId max = new PlotId(this.getId().x, this.getId().y); - for (final Plot current : this.getConnectedPlots()) { - if (current.getId().x < min.x) { - min.x = current.getId().x; - } else if (current.getId().x > max.x) { - max.x = current.getId().x; - } - if (current.getId().y < min.y) { - min.y = current.getId().y; - } else if (current.getId().y > max.y) { - max.y = current.getId().y; - } - } - return new PlotId[] { min, max }; - } - - /** - * @deprecated in favor of getCorners()[0];
- * @return - */ - @Deprecated - public Location getBottom() { - return this.getCorners()[0]; - } - - /** - * @deprecated in favor of getCorners()[1]; - * @return - */ - @Deprecated - public Location getTop() { - return this.getCorners()[0]; - } - - /** - * Swap the plot contents and settings with another location
- * - The destination must correspond to a valid plot of equal dimensions - * @see ChunkManager#swap(Location, Location, Location, Location, Runnable) to swap terrain - * @see this#swapData(Plot, Runnable) to swap plot settings - * @param destination The other plot to swap with - * @param whenDone A task to run when finished, or null - * @see this#swapData(Plot, Runnable) - * @return boolean if swap was successful - */ - public boolean swap(final Plot destination, final Runnable whenDone) { - return this.move(destination, whenDone, true); - } - - /** - * Move the plot to an empty location
- * - The location must be empty - * @param destination Where to move the plot - * @param whenDone A task to run when done, or null - * @return if the move was successful - */ - public boolean move(final Plot destination, final Runnable whenDone) { - return this.move(destination, whenDone, false); - } - - /** - * Get plot display name - * - * @return alias if set, else id - */ - @Override - public String toString() { - if ((this.settings != null) && (this.settings.getAlias().length() > 1)) { - return this.settings.getAlias(); - } - return this.area + ";" + this.id.x + ";" + this.id.y; - } - - /** - * Remove a denied player (use DBFunc as well)
- * Using the * uuid will remove all users - * @param uuid - */ - public boolean removeDenied(final UUID uuid) { - if (uuid == DBFunc.everyone) { - boolean result = false; - for (final UUID other : getDenied()) { - result = result || rmvDenied(other); - } - return result; - } - return rmvDenied(uuid); - } - - private boolean rmvDenied(UUID uuid) { - for (Plot current : this.getConnectedPlots()) { - if (current.getDenied().remove(uuid)) { - DBFunc.removeDenied(current, uuid); - } else { - return false; - } - } - return true; - } - /** - * Remove a helper (use DBFunc as well)
- * Using the * uuid will remove all users - * @param uuid - */ - public boolean removeTrusted(final UUID uuid) { - if (uuid == DBFunc.everyone) { - boolean result = false; - for (final UUID other : getTrusted()) { - result = result || rmvTrusted(other); - } - return result; - } - return rmvTrusted(uuid); - } - - private boolean rmvTrusted(UUID uuid) { - for (Plot plot : this.getConnectedPlots()) { - if (plot.getTrusted().remove(uuid)) { - DBFunc.removeTrusted(plot, uuid); - } else { - return false; - } - } - return true; - } - - /** - * Remove a trusted user (use DBFunc as well)
- * Using the * uuid will remove all users - * @param uuid - */ - public boolean removeMember(final UUID uuid) { - if (this.members == null) { - return false; - } - if (uuid == DBFunc.everyone) { - boolean result = false; - for (final UUID other : new HashSet<>(this.members)) { - result = result || rmvMember(other); - } - return result; - } - return rmvMember(uuid); - } - - private boolean rmvMember(UUID uuid) { - for (Plot current : this.getConnectedPlots()) { - if (current.getMembers().remove(uuid)) { - DBFunc.removeMember(current, uuid); - } else { - return false; - } - } - return true; - } - - /** - * Export the plot as a schematic to the configured output directory - * @return - */ - public void export(final RunnableVal whenDone) { - SchematicHandler.manager.getCompoundTag(this, new RunnableVal() { - @Override - public void run(final CompoundTag value) { - if (value == null) { - if (whenDone != null) { - whenDone.value = false; - TaskManager.runTask(whenDone); - } - } else { - TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { - final String name = Plot.this.id + "," + Plot.this.area + "," + MainUtil.getName(Plot.this.owner); - final boolean result = SchematicHandler.manager.save(value, Settings.SCHEMATIC_SAVE_PATH + File.separator + name + ".schematic"); - if (whenDone != null) { - whenDone.value = result; - TaskManager.runTask(whenDone); - } - } - }); - } - } - }); - } - - /** - * Export the plot as a BO3 object
- * - bedrock, floor and main block are ignored in their respective sections - * - air is ignored - * - The center is considered to be on top of the plot in the center - * @param whenDone value will be false if exporting fails - */ - public void exportBO3(final RunnableVal whenDone) { - final boolean result = BO3Handler.saveBO3(this); - if (whenDone != null) { - whenDone.value = result; - } - TaskManager.runTask(whenDone); - } - - /** - * Upload the plot as a schematic to the configured web interface - * @param whenDone value will be null if uploading fails - */ - public void upload(final RunnableVal whenDone) { - SchematicHandler.manager.getCompoundTag(this, new RunnableVal() { - @Override - public void run(final CompoundTag value) { - TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { - final URL url = SchematicHandler.manager.upload(value, null, null); - if (whenDone != null) { - whenDone.value = url; - } - TaskManager.runTask(whenDone); - } - }); - } - }); - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (this.getClass() != obj.getClass()) { - return false; - } - final Plot other = (Plot) obj; - return (this.hashCode() == other.hashCode()) && this.id.x.equals(other.id.x) && this.id.y.equals(other.id.y) && (this.area == other.area); - } - - /** - * Get the plot hashcode - * - * @return integer. - */ - @Override - public int hashCode() { - return this.id.hashCode(); - } - - /** - * Get the flags specific to this plot
- * - Does not take default flags into account
- * @return - */ - public HashMap getFlags() { - if (this.settings == null) { - return new HashMap<>(0); - } - return this.settings.flags; - } - - /** - * Set a flag for this plot - * @param flags - */ - public void setFlags(final Set flags) { - FlagManager.setPlotFlags(this, flags); - } - - /** - * Get the plot Alias
- * - Returns an empty string if no alias is set - * @return - */ - public String getAlias() { - if (this.settings == null) { - return ""; - } - return this.settings.getAlias(); - } - - /** - * Set the plot alias - * @param alias - */ - public void setAlias(String alias) { - for (final Plot current : this.getConnectedPlots()) { - final String name = this.getSettings().getAlias(); - if (alias == null) { - alias = ""; - } - if (name.equals(alias)) { - return; - } - current.getSettings().setAlias(alias); - DBFunc.setAlias(current, alias); - } - } - - /** - * Set the raw merge data
- * - Updates DB
- * - Does not modify terrain
- * ----------
- * 0 = north
- * 1 = east
- * 2 = south
- * 3 = west
- * ----------
- * @param direction - * @param value - */ - public void setMerged(final int direction, final boolean value) { - if (this.getSettings().setMerged(direction, value)) { - if (value) { - final Plot other = this.getRelative(direction).getBasePlot(false); - if (!other.equals(this.getBasePlot(false))) { - final Plot base = (other.id.y < this.id.y) || (other.id.y.equals(this.id.y) && (other.id.x < this.id.x)) ? other : this.origin; - this.origin.origin = base; - other.origin = base; - this.origin = base; - connected_cache = null; - } - } else { - if (this.origin != null) { - this.origin.origin = null; - this.origin = null; - } - connected_cache = null; - } - DBFunc.setMerged(this, this.getSettings().getMerged()); - regions_cache = null; - } - } - - /** - * Get the merged array - * @return boolean [ north, east, south, west ] - */ - public boolean[] getMerged() { - if (this.settings == null) { - return new boolean[] { false, false, false, false }; - } - return this.settings.getMerged(); - } - - /** - * Set the raw merge data
- * - Updates DB
- * - Does not modify terrain
- * Get if the plot is merged in a direction
- * ----------
- * 0 = north
- * 1 = east
- * 2 = south
- * 3 = west
- * ----------
- * Note: Diagonal merging (4-7) must be done by merging the corresponding plots. - * @param merged - */ - public void setMerged(final boolean[] merged) { - this.getSettings().setMerged(merged); - DBFunc.setMerged(this, merged); - connected_cache = null; - regions_cache = null; - if (this.origin != null) { - this.origin.origin = null; - this.origin = null; - } - } - - /** - * Get the set home location or 0,0,0 if no location is set
- * - Does not take the default home location into account - * @see #getHome() - * @return - */ - public BlockLoc getPosition() { - if (this.settings == null) { - return new BlockLoc(0, 0, 0); - } - return this.settings.getPosition(); - } - - public boolean canClaim(final PlotPlayer player) { - if (Settings.ENABLE_CLUSTERS) { - final PlotCluster cluster = this.getCluster(); - if (cluster != null) { - if (!cluster.isAdded(player.getUUID()) && !Permissions.hasPermission(player, "plots.admin.command.claim")) { - return false; - } - } - } - return this.guessOwner() == null; - } - - public UUID guessOwner() { - if (this.hasOwner()) { - return this.owner; - } - if (!this.area.ALLOW_SIGNS) { - return null; - } - try { - final Location loc = this.getManager().getSignLoc(this.area, this); - ChunkManager.manager.loadChunk(loc.getWorld(), loc.getChunkLoc(), false); - final String[] lines = WorldUtil.IMP.getSign(loc); - if (lines == null) { - return null; - } - loop: for (int i = 4; i > 0; i--) { - final String caption = C.valueOf("OWNER_SIGN_LINE_" + i).s(); - final int index = caption.indexOf("%plr%"); - if (index == -1) { - continue; - } - final String name = lines[i - 1].substring(index); - if (name.isEmpty()) { - return null; - } - final UUID owner = UUIDHandler.getUUID(name, null); - if (owner != null) { - this.owner = owner; - break; - } - if (lines[i - 1].length() == 15) { - final BiMap map = UUIDHandler.getUuidMap(); - for (final Entry entry : map.entrySet()) { - final String key = entry.getKey().value; - if ((key.length() > name.length()) && key.startsWith(name)) { - this.owner = entry.getValue(); - break loop; - } - } - } - this.owner = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(StandardCharsets.UTF_8)); - break; - } - if (this.hasOwner()) { - this.create(); - } - return this.owner; - } catch (final IllegalArgumentException e) { - return null; - } - } - - /** - * Remove the south road section of a plot
- * - Used when a plot is merged
- */ - public void removeRoadSouth() { - if ((this.area.TYPE != 0) && (this.area.TERRAIN > 1)) { - if (this.area.TERRAIN == 3) { - return; - } - final Plot other = this.getRelative(2); - final Location bot = other.getBottomAbs(); - final Location top = this.getTopAbs(); - final Location pos1 = new Location(this.area.worldname, bot.getX(), 0, top.getZ()); - final Location pos2 = new Location(this.area.worldname, top.getX(), 256, bot.getZ()); - ChunkManager.manager.regenerateRegion(pos1, pos2, true, null); - } else { - this.getManager().removeRoadSouth(this.area, this); - } - } - - /** - * Auto merge a plot in a specific direction
- * @param dir The direction to merge
- * -1 = All directions
- * 0 = north
- * 1 = east
- * 2 = south
- * 3 = west
- * @param max The max number of merges to do - * @param uuid The UUID it is allowed to merge with - * @param removeRoads Whether to remove roads - * @return true if a merge takes place - */ - public boolean autoMerge(final int dir, int max, final UUID uuid, final boolean removeRoads) { - if (this.owner == null) { - return false; - } - final HashSet visited = new HashSet<>(); - final HashSet merged = new HashSet<>(); - final HashSet connected = this.getConnectedPlots(); - for (final Plot current : connected) { - merged.add(current.getId()); - } - final ArrayDeque frontier = new ArrayDeque<>(connected); - Plot current; - boolean toReturn = false; - while (((current = frontier.poll()) != null) && (max >= 0)) { - if (visited.contains(current)) { - continue; - } - visited.add(current); - Set plots; - if ((max >= 0) && ((dir == -1) || (dir == 0)) && !current.getMerged(0)) { - final Plot other = current.getRelative(0); - if ((other != null) - && other.isOwner(uuid) - && (other.getBasePlot(false).equals(current.getBasePlot(false)) || (((plots = other.getConnectedPlots()).size() <= max) && frontier.addAll(plots) && ((max -= plots.size()) != -1)))) { - current.mergePlot(other, removeRoads); - merged.add(current.getId()); - merged.add(other.getId()); - toReturn = true; - } - } - if ((max >= 0) && ((dir == -1) || (dir == 1)) && !current.getMerged(1)) { - final Plot other = current.getRelative(1); - if ((other != null) - && other.isOwner(uuid) - && (other.getBasePlot(false).equals(current.getBasePlot(false)) || (((plots = other.getConnectedPlots()).size() <= max) && frontier.addAll(plots) && ((max -= plots.size()) != -1)))) { - current.mergePlot(other, removeRoads); - merged.add(current.getId()); - merged.add(other.getId()); - toReturn = true; - } - } - if ((max >= 0) && ((dir == -1) || (dir == 2)) && !current.getMerged(2)) { - final Plot other = current.getRelative(2); - if ((other != null) - && other.isOwner(uuid) - && (other.getBasePlot(false).equals(current.getBasePlot(false)) || (((plots = other.getConnectedPlots()).size() <= max) && frontier.addAll(plots) && ((max -= plots.size()) != -1)))) { - current.mergePlot(other, removeRoads); - merged.add(current.getId()); - merged.add(other.getId()); - toReturn = true; - } - } - if ((max >= 0) && ((dir == -1) || (dir == 3)) && !current.getMerged(3)) { - final Plot other = current.getRelative(3); - if ((other != null) - && other.isOwner(uuid) - && (other.getBasePlot(false).equals(current.getBasePlot(false)) || (((plots = other.getConnectedPlots()).size() <= max) && frontier.addAll(plots) && ((max -= plots.size()) != -1)))) { - current.mergePlot(other, removeRoads); - merged.add(current.getId()); - merged.add(other.getId()); - toReturn = true; - } - } - } - if (removeRoads && toReturn) { - final ArrayList ids = new ArrayList<>(merged); - this.getManager().finishPlotMerge(this.area, ids); - } - return toReturn; - } - - /** - * Merge the plot settings
- * - Used when a plot is merged
- * @param b - */ - public void mergeData(final Plot b) { - final HashMap flags1 = this.getFlags(); - final HashMap flags2 = b.getFlags(); - if ((!flags1.isEmpty() || !flags2.isEmpty()) && !flags1.equals(flags2)) { - final boolean greater = flags1.size() > flags2.size(); - if (greater) { - flags1.putAll(flags2); - } else { - flags2.putAll(flags1); - } - final HashSet net = new HashSet<>((greater ? flags1 : flags2).values()); - this.setFlags(net); - b.setFlags(net); - } - if (!this.getAlias().isEmpty()) { - b.setAlias(this.getAlias()); - } else if (!b.getAlias().isEmpty()) { - this.setAlias(b.getAlias()); - } - for (final UUID uuid : this.getTrusted()) { - b.addTrusted(uuid); - } - for (final UUID uuid : b.getTrusted()) { - this.addTrusted(uuid); - } - for (final UUID uuid : this.getMembers()) { - b.addMember(uuid); - } - for (final UUID uuid : b.getMembers()) { - this.addMember(uuid); - } - - for (final UUID uuid : this.getDenied()) { - b.addDenied(uuid); - } - for (final UUID uuid : b.getDenied()) { - this.addDenied(uuid); - } - } - - public void removeRoadSouthEast() { - if ((this.area.TYPE != 0) && (this.area.TERRAIN > 1)) { - if (this.area.TERRAIN == 3) { - return; - } - final Plot other = this.getRelative(1, 1); - final Location pos1 = this.getTopAbs().add(1, 0, 1); - final Location pos2 = other.getBottomAbs().subtract(1, 0, 1); - pos1.setY(0); - pos2.setY(256); - ChunkManager.manager.regenerateRegion(pos1, pos2, true, null); - } else { - this.area.getPlotManager().removeRoadSouthEast(this.area, this); - } - } - - public Plot getRelative(final int x, final int y) { - return this.area.getPlotAbs(this.id.getRelative(x, y)); - } - - public Plot getRelative(final int direction) { - return this.area.getPlotAbs(this.id.getRelative(direction)); - } - - /** - * Get a set of plots connected (and including) this plot
- * - This result is cached globally - * @return - */ - public HashSet getConnectedPlots() { - if (this.settings == null) { - return new HashSet<>(Collections.singletonList(this)); - } - boolean[] merged = this.getMerged(); - final int hash = MainUtil.hash(merged); - if (hash == 0) { - return new HashSet<>(Collections.singletonList(this)); - } - if ((connected_cache != null) && connected_cache.contains(this)) { - return connected_cache; - } - regions_cache = null; - connected_cache = new HashSet<>(); - final ArrayDeque frontier = new ArrayDeque<>(); - final HashSet queuecache = new HashSet<>(); - connected_cache.add(this); - Plot tmp; - if (merged[0]) { - tmp = this.area.getPlotAbs(this.id.getRelative(0)); - if (!tmp.getMerged(2)) { - // invalid merge - PS.debug("Fixing invalid merge: " + this); - if (tmp.isOwnerAbs(owner)) { - tmp.getSettings().setMerged(2, true); - DBFunc.setMerged(tmp, tmp.settings.getMerged()); - } else { - this.getSettings().setMerged(0, false); - DBFunc.setMerged(this, this.settings.getMerged()); - } - } - queuecache.add(tmp); - frontier.add(tmp); - } - if (merged[1]) { - tmp = this.area.getPlotAbs(this.id.getRelative(1)); - if (!tmp.getMerged(3)) { - // invalid merge - PS.debug("Fixing invalid merge: " + this); - if (tmp.isOwnerAbs(owner)) { - tmp.getSettings().setMerged(3, true); - DBFunc.setMerged(tmp, tmp.settings.getMerged()); - } else { - this.getSettings().setMerged(1, false); - DBFunc.setMerged(this, this.settings.getMerged()); - } - } - queuecache.add(tmp); - frontier.add(tmp); - } - if (merged[2]) { - tmp = this.area.getPlotAbs(this.id.getRelative(2)); - if (!tmp.getMerged(0)) { - // invalid merge - PS.debug("Fixing invalid merge: " + this); - if (tmp.isOwnerAbs(owner)) { - tmp.getSettings().setMerged(0, true); - DBFunc.setMerged(tmp, tmp.settings.getMerged()); - } else { - this.getSettings().setMerged(2, false); - DBFunc.setMerged(this, this.settings.getMerged()); - } - } - queuecache.add(tmp); - frontier.add(tmp); - } - if (merged[3]) { - tmp = this.area.getPlotAbs(this.id.getRelative(3)); - if (!tmp.getMerged(1)) { - // invalid merge - PS.debug("Fixing invalid merge: " + this); - if (tmp.isOwnerAbs(owner)) { - tmp.getSettings().setMerged(1, true); - DBFunc.setMerged(tmp, tmp.settings.getMerged()); - } else { - this.getSettings().setMerged(3, false); - DBFunc.setMerged(this, this.settings.getMerged()); - } - } - queuecache.add(tmp); - frontier.add(tmp); - } - Plot current; - while ((current = frontier.poll()) != null) { - if ((current.owner == null) || (current.settings == null)) { - // Invalid plot - // merged onto unclaimed plot - PS.debug("Ignoring invalid merged plot: " + current + " | " + current.owner); - continue; - } - connected_cache.add(current); - queuecache.remove(current); - merged = current.getMerged(); - if (merged[0]) { - tmp = current.area.getPlotAbs(current.id.getRelative(0)); - if ((tmp != null) && !queuecache.contains(tmp) && !connected_cache.contains(tmp)) { - queuecache.add(tmp); - frontier.add(tmp); - } - } - if (merged[1]) { - tmp = current.area.getPlotAbs(current.id.getRelative(1)); - if ((tmp != null) && !queuecache.contains(tmp) && !connected_cache.contains(tmp)) { - queuecache.add(tmp); - frontier.add(tmp); - } - } - if (merged[2]) { - tmp = current.area.getPlotAbs(current.id.getRelative(2)); - if ((tmp != null) && !queuecache.contains(tmp) && !connected_cache.contains(tmp)) { - queuecache.add(tmp); - frontier.add(tmp); - } - } - if (merged[3]) { - tmp = current.area.getPlotAbs(current.id.getRelative(3)); - if ((tmp != null) && !queuecache.contains(tmp) && !connected_cache.contains(tmp)) { - queuecache.add(tmp); - frontier.add(tmp); - } - } - } - return connected_cache; - } - - /** - * This will combine each plot into effective rectangular regions
- * - This result is cached globally
- * - Useful for handling non rectangular shapes - * @return - */ - public HashSet getRegions() { - if ((regions_cache != null) && (connected_cache != null) && connected_cache.contains(this)) { - return regions_cache; - } - if (!this.isMerged()) { - final Location pos1 = this.getBottomAbs(); - final Location pos2 = this.getTopAbs(); - connected_cache = new HashSet<>(Collections.singletonList(this)); - regions_cache = new HashSet<>(1); - regions_cache.add(new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getY(), pos2.getY(), pos1.getZ(), pos2.getZ())); - return regions_cache; - } - final HashSet plots = this.getConnectedPlots(); - regions_cache = new HashSet<>(); - final HashSet visited = new HashSet<>(); - for (final Plot current : plots) { - if (visited.contains(current.getId())) { - continue; - } - boolean merge = true; - final PlotId bot = new PlotId(current.getId().x, current.getId().y); - final PlotId top = new PlotId(current.getId().x, current.getId().y); - while (merge) { - merge = false; - ArrayList ids = MainUtil.getPlotSelectionIds(new PlotId(bot.x, bot.y - 1), new PlotId(top.x, bot.y - 1)); - boolean tmp = true; - for (final PlotId id : ids) { - final Plot plot = this.area.getPlotAbs(id); - if ((plot == null) || !plot.getMerged(2) || visited.contains(plot.getId())) { - tmp = false; - } - } - if (tmp) { - merge = true; - bot.y--; - } - ids = MainUtil.getPlotSelectionIds(new PlotId(top.x + 1, bot.y), new PlotId(top.x + 1, top.y)); - tmp = true; - for (final PlotId id : ids) { - final Plot plot = this.area.getPlotAbs(id); - if ((plot == null) || !plot.getMerged(3) || visited.contains(plot.getId())) { - tmp = false; - } - } - if (tmp) { - merge = true; - top.x++; - } - ids = MainUtil.getPlotSelectionIds(new PlotId(bot.x, top.y + 1), new PlotId(top.x, top.y + 1)); - tmp = true; - for (final PlotId id : ids) { - final Plot plot = this.area.getPlotAbs(id); - if ((plot == null) || !plot.getMerged(0) || visited.contains(plot.getId())) { - tmp = false; - } - } - if (tmp) { - merge = true; - top.y++; - } - ids = MainUtil.getPlotSelectionIds(new PlotId(bot.x - 1, bot.y), new PlotId(bot.x - 1, top.y)); - tmp = true; - for (final PlotId id : ids) { - final Plot plot = this.area.getPlotAbs(id); - if ((plot == null) || !plot.getMerged(1) || visited.contains(plot.getId())) { - tmp = false; - } - } - if (tmp) { - merge = true; - bot.x--; - } - } - final Location gtopabs = this.area.getPlotAbs(top).getTopAbs(); - final Location gbotabs = this.area.getPlotAbs(bot).getBottomAbs(); - for (final PlotId id : MainUtil.getPlotSelectionIds(bot, top)) { - visited.add(id); - } - for (int x = bot.x; x <= top.x; x++) { - final Plot plot = this.area.getPlotAbs(new PlotId(x, top.y)); - if (plot.getMerged(2)) { - // south wedge - final Location toploc = plot.getExtendedTopAbs(); - final Location botabs = plot.getBottomAbs(); - final Location topabs = plot.getTopAbs(); - regions_cache.add(new RegionWrapper(botabs.getX(), topabs.getX(), topabs.getZ() + 1, toploc.getZ())); - if (plot.getMerged(5)) { - regions_cache.add(new RegionWrapper(topabs.getX() + 1, toploc.getX(), topabs.getZ() + 1, toploc.getZ())); - // intersection - } - } - } - - for (int y = bot.y; y <= top.y; y++) { - final Plot plot = this.area.getPlotAbs(new PlotId(top.x, y)); - if (plot.getMerged(1)) { - // east wedge - final Location toploc = plot.getExtendedTopAbs(); - final Location botabs = plot.getBottomAbs(); - final Location topabs = plot.getTopAbs(); - regions_cache.add(new RegionWrapper(topabs.getX() + 1, toploc.getX(), botabs.getZ(), topabs.getZ())); - if (plot.getMerged(5)) { - regions_cache.add(new RegionWrapper(topabs.getX() + 1, toploc.getX(), topabs.getZ() + 1, toploc.getZ())); - // intersection - } - } - } - regions_cache.add(new RegionWrapper(gbotabs.getX(), gtopabs.getX(), gbotabs.getZ(), gtopabs.getZ())); - } - return regions_cache; - } - - /** - * Attempt to find the largest rectangular region in a plot (as plots can form non rectangular shapes) - * @return - */ - public RegionWrapper getLargestRegion() { - final HashSet regions = this.getRegions(); - RegionWrapper max = null; - int area = 0; - for (final RegionWrapper region : regions) { - final int current = ((region.maxX - region.minX) + 1) * ((region.maxZ - region.minZ) + 1); - if (current > area) { - max = region; - area = current; - } - } - return max; - } - - public void reEnter() { - TaskManager.runTaskLater(new Runnable() { - @Override - public void run() { - for (final PlotPlayer pp : Plot.this.getPlayersInPlot()) { - PlotListener.plotExit(pp, Plot.this); - PlotListener.plotEntry(pp, Plot.this); - } - } - }, 1); - } - - /** - * Get all the corners of the plot (supports non-rectangular shapes)
- * @return - */ - public List getAllCorners() { - final Area area = new Area(); - for (final RegionWrapper region : this.getRegions()) { - final Area rectArea = new Area(new Rectangle(region.minX, region.minZ, region.maxX - region.minX, region.maxZ - region.minZ)); - area.add(rectArea); - } - final List locs = new ArrayList<>(); - double[] coords = new double[6]; - for (PathIterator pi = area.getPathIterator(null); !pi.isDone(); pi.next()) { - int type = pi.currentSegment(coords); - final int x = (int) coords[0]; - final int z = (int) coords[1]; - if (type != 4) { - locs.add(new Location(this.area.worldname, x, 0, z)); - } - } - return locs; - } - - /** - * Teleport a player to a plot and send them the teleport message. - * @param player - * @return If the teleportation is allowed. - */ - public boolean teleportPlayer(final PlotPlayer player) { - final Plot plot = this.getBasePlot(false); - final boolean result = EventUtil.manager.callTeleport(player, player.getLocation(), plot); - if (result) { - final Location location; - if (this.area.HOME_ALLOW_NONMEMBER || plot.isAdded(player.getUUID())) { - location = this.getHome(); - } else { - location = this.getDefaultHome(); - } - if ((Settings.TELEPORT_DELAY == 0) || Permissions.hasPermission(player, "plots.teleport.delay.bypass")) { - MainUtil.sendMessage(player, C.TELEPORTED_TO_PLOT); - player.teleport(location); - return true; - } - MainUtil.sendMessage(player, C.TELEPORT_IN_SECONDS, Settings.TELEPORT_DELAY + ""); - final String name = player.getName(); - TaskManager.TELEPORT_QUEUE.add(name); - TaskManager.runTaskLater(new Runnable() { - @Override - public void run() { - if (!TaskManager.TELEPORT_QUEUE.contains(name)) { - MainUtil.sendMessage(player, C.TELEPORT_FAILED); - return; - } - TaskManager.TELEPORT_QUEUE.remove(name); - if (!player.isOnline()) { - return; - } - MainUtil.sendMessage(player, C.TELEPORTED_TO_PLOT); - player.teleport(location); - } - }, Settings.TELEPORT_DELAY * 20); - return true; - } - return result; - } - - public boolean isOnline() { - if (owner == null) { - return false; - } - if (!isMerged()) { - return UUIDHandler.getPlayer(owner) != null; - } - for (Plot current : getConnectedPlots()) { - if (current.hasOwner() && UUIDHandler.getPlayer(current.owner) != null) { - return true; - } - } - return false; - } - - /** - * Set a component for a plot to the provided blocks
- * - E.g. floor, wall, border etc.
- * - The available components depend on the generator being used
- * @param component - * @param blocks - * @return - */ - public boolean setComponent(final String component, final PlotBlock[] blocks) { - return this.getManager().setComponent(this.area, this.getId(), component, blocks); - } - - /** - * Expand the world border to include the provided plot (if applicable) - */ - public void updateWorldBorder() { - if (this.owner == null) { - return; - } - final int border = this.area.getBorder(); - if (border == Integer.MAX_VALUE) { - return; - } - final PlotId id = new PlotId(Math.abs(this.getId().x) + 1, Math.abs(this.getId().x) + 1); - final PlotManager manager = this.getManager(); - final Location bot = manager.getPlotBottomLocAbs(this.area, id); - final Location top = manager.getPlotTopLocAbs(this.area, id); - final int botmax = Math.max(Math.abs(bot.getX()), Math.abs(bot.getZ())); - final int topmax = Math.max(Math.abs(top.getX()), Math.abs(top.getZ())); - final int max = Math.max(botmax, topmax); - if (max > border) { - this.area.setMeta("worldBorder", max); - } - } - - /** - * Merges 2 plots Removes the road inbetween
- Assumes plots are directly next to each other
- saves to DB - * - * @param lesserPlot - * @param removeRoads - */ - public void mergePlot(Plot lesserPlot, final boolean removeRoads) { - Plot greaterPlot = this; - if (lesserPlot.getId().x.equals(greaterPlot.getId().x)) { - if (lesserPlot.getId().y > greaterPlot.getId().y) { - final Plot tmp = lesserPlot; - lesserPlot = greaterPlot; - greaterPlot = tmp; - } - if (!lesserPlot.getMerged(2)) { - lesserPlot.clearRatings(); - greaterPlot.clearRatings(); - lesserPlot.setMerged(2, true); - greaterPlot.setMerged(0, true); - lesserPlot.mergeData(greaterPlot); - if (removeRoads) { - if (lesserPlot.getMerged(5)) { - lesserPlot.removeRoadSouthEast(); - } - lesserPlot.removeRoadSouth(); - final Plot other = this.getRelative(3); - if (other.getMerged(2) && other.getMerged(1)) { - other.removeRoadEast(); - greaterPlot.mergePlot(other, removeRoads); - } - } - } - } else { - if (lesserPlot.getId().x > greaterPlot.getId().x) { - final Plot tmp = lesserPlot; - lesserPlot = greaterPlot; - greaterPlot = tmp; - } - if (!lesserPlot.getMerged(1)) { - lesserPlot.clearRatings(); - greaterPlot.clearRatings(); - lesserPlot.setMerged(1, true); - greaterPlot.setMerged(3, true); - lesserPlot.mergeData(greaterPlot); - if (removeRoads) { - lesserPlot.removeRoadEast(); - if (lesserPlot.getMerged(5)) { - lesserPlot.removeRoadSouthEast(); - } - final Plot other = lesserPlot.getRelative(0); - if (other.getMerged(2) && other.getMerged(1)) { - other.removeRoadSouthEast(); - greaterPlot.mergePlot(other, removeRoads); - } - } - } - } - } - - /** - * Move a plot physically, as well as the corresponding settings. - * @param destination - * @param whenDone - * @param allowSwap - * @return - */ - public boolean move(final Plot destination, final Runnable whenDone, final boolean allowSwap) { - final PlotId offset = new PlotId(destination.getId().x - this.getId().x, destination.getId().y - this.getId().y); - final Location db = destination.getBottomAbs(); - final Location ob = this.getBottomAbs(); - final int offsetX = db.getX() - ob.getX(); - final int offsetZ = db.getZ() - ob.getZ(); - if (this.owner == null) { - TaskManager.runTaskLater(whenDone, 1); - return false; - } - boolean occupied = false; - final HashSet plots = this.getConnectedPlots(); - for (final Plot plot : plots) { - final Plot other = plot.getRelative(offset.x, offset.y); - if (other.hasOwner()) { - if (!allowSwap) { - TaskManager.runTaskLater(whenDone, 1); - return false; - } - occupied = true; - } - } - // world border - destination.updateWorldBorder(); - final ArrayDeque regions = new ArrayDeque<>(this.getRegions()); - // move / swap data - for (final Plot plot : plots) { - final Plot other = plot.getRelative(offset.x, offset.y); - plot.swapData(other, null); - } - // copy terrain - final Runnable move = new Runnable() { - @Override - public void run() { - if (regions.isEmpty()) { - TaskManager.runTask(whenDone); - return; - } - final Runnable task = this; - final RegionWrapper region = regions.poll(); - final Location[] corners = region.getCorners(Plot.this.area.worldname); - final Location pos1 = corners[0]; - final Location pos2 = corners[1]; - final Location newPos = pos1.clone().add(offsetX, 0, offsetZ); - newPos.setWorld(destination.area.worldname); - ChunkManager.manager.regenerateRegion(pos1, pos2, false, task); - } - }; - final Runnable swap = new Runnable() { - @Override - public void run() { - if (regions.isEmpty()) { - TaskManager.runTask(whenDone); - return; - } - final RegionWrapper region = regions.poll(); - final Location[] corners = region.getCorners(Plot.this.area.worldname); - final Location pos1 = corners[0]; - final Location pos2 = corners[1]; - final Location pos3 = pos1.clone().add(offsetX, 0, offsetZ); - final Location pos4 = pos2.clone().add(offsetX, 0, offsetZ); - pos3.setWorld(destination.area.worldname); - pos4.setWorld(destination.area.worldname); - ChunkManager.manager.swap(pos1, pos2, pos3, pos4, this); - } - }; - if (occupied) { - swap.run(); - } else { - move.run(); - } - return true; - } - - /** - * Copy a plot to a location, both physically and the settings - * @param destination - * @param whenDone - * @return - */ - public boolean copy(final Plot destination, final Runnable whenDone) { - final PlotId offset = new PlotId(destination.getId().x - this.getId().x, destination.getId().y - this.getId().y); - final Location db = destination.getBottomAbs(); - final Location ob = this.getBottomAbs(); - final int offsetX = db.getX() - ob.getX(); - final int offsetZ = db.getZ() - ob.getZ(); - if (this.owner == null) { - TaskManager.runTaskLater(whenDone, 1); - return false; - } - final HashSet plots = this.getConnectedPlots(); - for (final Plot plot : plots) { - final Plot other = plot.getRelative(offset.x, offset.y); - if (other.hasOwner()) { - TaskManager.runTaskLater(whenDone, 1); - return false; - } - } - // world border - destination.updateWorldBorder(); - // copy data - for (final Plot plot : plots) { - final Plot other = plot.getRelative(offset.x, offset.y); - other.create(other.owner, false); - if ((plot.getFlags() != null) && !plot.getFlags().isEmpty()) { - other.getSettings().flags = plot.getFlags(); - DBFunc.setFlags(other, plot.getFlags().values()); - } - if (plot.isMerged()) { - other.setMerged(plot.getMerged()); - } - if ((plot.members != null) && !plot.members.isEmpty()) { - other.members = plot.members; - for (final UUID member : other.members) { - DBFunc.setMember(other, member); - } - } - if ((plot.trusted != null) && !plot.trusted.isEmpty()) { - other.trusted = plot.trusted; - for (final UUID trusted : other.trusted) { - DBFunc.setTrusted(other, trusted); - } - } - if ((plot.denied != null) && !plot.denied.isEmpty()) { - other.denied = plot.denied; - for (final UUID denied : other.denied) { - DBFunc.setDenied(other, denied); - } - } - PS.get().updatePlot(other); - } - // copy terrain - final ArrayDeque regions = new ArrayDeque<>(this.getRegions()); - final Runnable run = new Runnable() { - @Override - public void run() { - if (regions.isEmpty()) { - TaskManager.runTask(whenDone); - return; - } - final RegionWrapper region = regions.poll(); - final Location[] corners = region.getCorners(Plot.this.area.worldname); - final Location pos1 = corners[0]; - final Location pos2 = corners[1]; - final Location newPos = pos1.clone().add(offsetX, 0, offsetZ); - newPos.setWorld(destination.area.worldname); - ChunkManager.manager.copyRegion(pos1, pos2, newPos, this); - } - }; - run.run(); - return true; - } -} +//////////////////////////////////////////////////////////////////////////////////////////////////// +// PlotSquared - A plot manager and world generator for the Bukkit API / +// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / +// / +// This program is free software; you can redistribute it and/or modify / +// it under the terms of the GNU General Public License as published by / +// the Free Software Foundation; either version 3 of the License, or / +// (at your option) any later version. / +// / +// This program is distributed in the hope that it will be useful, / +// but WITHOUT ANY WARRANTY; without even the implied warranty of / +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / +// GNU General Public License for more details. / +// / +// You should have received a copy of the GNU General Public License / +// along with this program; if not, write to the Free Software Foundation, / +// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / +// / +// You can contact us via: support@intellectualsites.com / +//////////////////////////////////////////////////////////////////////////////////////////////////// +package com.intellectualcrafters.plot.object; + +import java.awt.Rectangle; +import java.awt.geom.Area; +import java.awt.geom.PathIterator; +import java.io.File; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map.Entry; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; + +import com.google.common.collect.BiMap; +import com.intellectualcrafters.jnbt.CompoundTag; +import com.intellectualcrafters.plot.PS; +import com.intellectualcrafters.plot.config.C; +import com.intellectualcrafters.plot.config.Configuration; +import com.intellectualcrafters.plot.config.Settings; +import com.intellectualcrafters.plot.database.DBFunc; +import com.intellectualcrafters.plot.flag.Flag; +import com.intellectualcrafters.plot.flag.FlagManager; +import com.intellectualcrafters.plot.util.BO3Handler; +import com.intellectualcrafters.plot.util.ChunkManager; +import com.intellectualcrafters.plot.util.EventUtil; +import com.intellectualcrafters.plot.util.MainUtil; +import com.intellectualcrafters.plot.util.Permissions; +import com.intellectualcrafters.plot.util.SchematicHandler; +import com.intellectualcrafters.plot.util.SetQueue; +import com.intellectualcrafters.plot.util.TaskManager; +import com.intellectualcrafters.plot.util.UUIDHandler; +import com.intellectualcrafters.plot.util.WorldUtil; +import com.plotsquared.listener.PlotListener; + +/** + * The plot class + */ +@SuppressWarnings("javadoc") +public class Plot { + /** + * @deprecated raw access is deprecated + */ + @Deprecated + private static HashSet connected_cache; + private static HashSet regions_cache; + /** + * plot ID + * Direct access is Deprecated: use getId() + */ + @Deprecated + public final PlotId id; + /** + * plot owner + * (Merged plots can have multiple owners) + * Direct access is Deprecated: use getOwners() + */ + @Deprecated + public UUID owner; + /** + * Plot creation timestamp (not accurate if the plot was created before this was implemented)
+ * - Milliseconds since the epoch
+ * Direct access is Deprecated: use {@link #getTimestamp() getTimestamp} + */ + @Deprecated + public long timestamp; + /** + * List of trusted (with plot permissions) + * Direct access is Deprecated: use getTrusted() + */ + @Deprecated + public HashSet trusted; + /** + * List of members users (with plot permissions) + * Direct access is Deprecated: use getMembers() + */ + @Deprecated + public HashSet members; + /** + * List of denied players + * Direct access is Deprecated: use getDenied() + */ + @Deprecated + public HashSet denied; + /** + * External settings class
+ * - Please favor the methods over direct access to this class
+ * - The methods are more likely to be left unchanged from version changes
+ * Direct access is Deprecated: use getSettings() + */ + @Deprecated + public PlotSettings settings; + /** + * Has the plot changed since the last save cycle? + */ + public boolean countsTowardsMax = true; + /** + * Represents whatever the database manager needs it to:
+ * - A value of -1 usually indicates the plot will not be stored in the DB
+ * - A value of 0 usually indicates that the DB manager hasn't set a value
+ * @deprecated magical + */ + @Deprecated + public int temp; + /** + * plot world + * Direct access is Deprecated: use getWorld() + */ + private PlotArea area; + /** + * Session only plot metadata (session is until the server stops)
+ *
+ * For persistent metadata use the flag system + * @see FlagManager + */ + private ConcurrentHashMap meta; + /** + * The cached origin plot
+ * - The origin plot is used for plot grouping and relational data + */ + private Plot origin; + + /** + * Constructor for a new plot
+ * (Only changes after plot.create() will be properly set in the database) + * + * @see Plot#getPlot(Location) for existing plots + * + * @param area + * @param id + * @param owner + */ + public Plot(final PlotArea area, final PlotId id, final UUID owner) { + this.area = area; + this.id = id; + this.owner = owner; + } + + /** + * Constructor for an unowned plot
+ * (Only changes after plot.create() will be properly set in the database) + * + * @see Plot#getPlot(Location) for existing plots + * + * @param area + * @param id + */ + public Plot(final PlotArea area, final PlotId id) { + this.area = area; + this.id = id; + } + + /** + * Constructor for a temporary plot (use -1 for temp)
+ * The database will ignore any queries regarding temporary plots. + * Please note that some bulk plot management functions may still affect temporary plots (TODO: fix this) + * + * @see Plot#getPlot(Location) for existing plots + * + * @param area + * @param id + * @param owner + * @param temp + */ + public Plot(final PlotArea area, final PlotId id, final UUID owner, final int temp) { + this.area = area; + this.id = id; + this.owner = owner; + this.temp = temp; + } + + /** + * Constructor for a saved plots (Used by the database manager when plots are fetched) + * + * @see Plot#getPlot(Location) for existing plots + * + * @param id + * @param owner + * @param trusted + * @param denied + * @param merged + */ + public Plot(final PlotId id, final UUID owner, final HashSet trusted, final HashSet members, final HashSet denied, final String alias, final BlockLoc position, + final Collection flags, final PlotArea area, final boolean[] merged, final long timestamp, final int temp) { + this.id = id; + this.area = area; + this.owner = owner; + this.settings = new PlotSettings(); + this.members = members; + this.trusted = trusted; + this.denied = denied; + this.settings.setAlias(alias); + this.settings.setPosition(position); + this.settings.setMerged(merged); + if (flags != null) { + for (final Flag flag : flags) { + this.settings.flags.put(flag.getKey(), flag); + } + } + this.timestamp = timestamp; + this.temp = temp; + } + + public static Plot fromString(final PlotArea defaultArea, final String string) { + final String[] split = string.split(";|,"); + if (split.length == 2) { + if (defaultArea != null) { + final PlotId id = PlotId.fromString(split[0] + ";" + split[1]); + return id != null ? defaultArea.getPlotAbs(id) : null; + } + } else if (split.length == 3) { + final PlotArea pa = PS.get().getPlotArea(split[0], null); + if (pa != null) { + final PlotId id = PlotId.fromString(split[1] + ";" + split[2]); + return pa.getPlotAbs(id); + } + } else if (split.length == 4) { + final PlotArea pa = PS.get().getPlotArea(split[0], split[1]); + if (pa != null) { + final PlotId id = PlotId.fromString(split[1] + ";" + split[2]); + return pa.getPlotAbs(id); + } + } + return null; + } + + /** + * Return a new/cached plot object at a given location + * + * @see PlotPlayer#getCurrentPlot() if a player is expected here. + * + * @param loc + * @return + */ + public static Plot getPlot(final Location loc) { + final PlotArea pa = PS.get().getPlotAreaAbs(loc); + if (pa != null) { + return pa.getPlot(loc); + } + return null; + } + + /** + * Session only plot metadata (session is until the server stops)
+ *
+ * For persistent metadata use the flag system + * @see FlagManager + * @param key + * @param value + */ + public void setMeta(final String key, final Object value) { + if (this.meta == null) { + this.meta = new ConcurrentHashMap<>(); + } + this.meta.put(key, value); + } + + /** + * Get the metadata for a key
+ *
+ * For persistent metadata use the flag system + * @param key + * @return + */ + public Object getMeta(final String key) { + if (this.meta != null) { + return this.meta.get(key); + } + return null; + } + + /** + * Delete the metadata for a key
+ * - metadata is session only + * - deleting other plugin's metadata may cause issues + * @param key + */ + public void deleteMeta(final String key) { + if (this.meta != null) { + this.meta.remove(key); + } + } + + /** + * Get the cluster this plot is associated with + * @return the PlotCluster object, or null + */ + public PlotCluster getCluster() { + return this.getArea().getCluster(this.id); + } + + /** + * Efficiently get the players currently inside this plot
+ * - Will return an empty list if no players are in the plot
+ * - Remember, you can cast a PlotPlayer to it's respective implementation (BukkitPlayer, SpongePlayer) to obtain the player object + * @return list of PlotPlayer(s) or an empty list + */ + public List getPlayersInPlot() { + final ArrayList players = new ArrayList<>(); + for (final Entry entry : UUIDHandler.getPlayers().entrySet()) { + final PlotPlayer pp = entry.getValue(); + if (this.equals(pp.getCurrentPlot())) { + players.add(pp); + } + } + return players; + } + + /** + * Check if the plot has a set owner + * + * @return false if there is no owner + */ + public boolean hasOwner() { + return this.owner != null; + } + + /** + * Check if a UUID is a plot owner (merged plots may have multiple owners) + * @param uuid + * @return + */ + public boolean isOwner(final UUID uuid) { + if (uuid.equals(owner)) { + return true; + } + if (!isMerged()) { + return false; + } + HashSet connected = getConnectedPlots(); + for (Plot current : connected) { + if (uuid.equals(current.owner)) { + return true; + } + } + return false; + } + + public boolean isOwnerAbs(final UUID uuid) { + return uuid.equals(owner); + } + + /** + * Get a list of owner UUIDs for a plot (supports multi-owner mega-plots) + * @return + */ + public HashSet getOwners() { + if (owner == null) { + return new HashSet(); + } + if (isMerged()) { + HashSet plots = getConnectedPlots(); + final HashSet owners = new HashSet(2); + UUID last = owner; + owners.add(owner); + for (Plot current : plots) { + if (last == null || current.owner.getMostSignificantBits() != last.getMostSignificantBits()) { + owners.add(current.owner); + last = current.owner; + } + } + return owners; + } + return new HashSet<>(Collections.singletonList(owner)); + } + + /** + * Check if the player is either the owner or on the trusted/added list + * + * @param uuid + * + * @return true if the player is added/trusted or is the owner + */ + public boolean isAdded(final UUID uuid) { + if (owner == null) { + return false; + } + if (getDenied().contains(uuid)) { + return false; + } + if (getTrusted().contains(uuid) || getTrusted().contains(DBFunc.everyone)) { + return true; + } + if (isOwner(uuid)) { + return true; + } + if (getMembers().contains(uuid) || getMembers().contains(DBFunc.everyone)) { + if (isOnline()) { + return true; + } + } + return false; + } + + /** + * Should the player be denied from entering? + * + * @param uuid + * + * @return boolean false if the player is allowed to enter + */ + public boolean isDenied(final UUID uuid) { + return (this.denied != null) && ((this.denied.contains(DBFunc.everyone) && !this.isAdded(uuid)) || (!this.isAdded(uuid) && this.denied.contains(uuid))); + } + + /** + * Get the plot ID + */ + public PlotId getId() { + return this.id; + } + + /** + * Get the plot world object for this plot
+ * - The generic PlotArea object can be casted to its respective class for more control (e.g. HybridPlotWorld) + * @return PlotArea + */ + public PlotArea getArea() { + return this.area; + } + + public void setArea(final PlotArea area) { + if (this.getArea() != null) { + this.area.removePlot(this.id); + } + this.area = area; + area.addPlot(this); + } + + /** + * Get the plot manager object for this plot
+ * - The generic PlotManager object can be casted to its respective class for more control (e.g. HybridPlotManager) + * @return PlotManager + */ + public PlotManager getManager() { + return this.area.getPlotManager(); + } + + /** + * Get or create plot settings + * @return PlotSettings + * @deprecated use equivalent plot method; + */ + @Deprecated + public PlotSettings getSettings() { + if (this.settings == null) { + this.settings = new PlotSettings(); + } + return this.settings; + } + + /** + * Returns true if the plot is not merged, or it is the base plot of multiple merged plots + * @return + */ + public boolean isBasePlot() { + if ((this.settings == null) || !this.isMerged()) { + return true; + } + return this.equals(this.getBasePlot(false)); + } + + /** + * The base plot is an arbitrary but specific connected plot. It is useful for the following:
+ * - Merged plots need to be treated as a single plot for most purposes
+ * - Some data such as home location needs to be associated with the group rather than each plot
+ * - If the plot is not merged it will return itself.
+ * - The result is cached locally + * @return base Plot + */ + public Plot getBasePlot(final boolean recalculate) { + if ((this.origin != null) && !recalculate) { + if (this.equals(this.origin)) { + return this; + } + return this.origin.getBasePlot(false); + } + if (!this.isMerged()) { + this.origin = this; + return this.origin; + } + this.origin = this; + PlotId min = this.id; + for (final Plot plot : this.getConnectedPlots()) { + if ((plot.id.y < min.y) || (plot.id.y.equals(min.y) && (plot.id.x < min.x))) { + this.origin = plot; + min = plot.id; + } + } + for (final Plot plot : this.getConnectedPlots()) { + plot.origin = this.origin; + } + return this.origin; + } + + /** + * Check if the plot is merged in any direction + * @return + */ + public boolean isMerged() { + if (this.settings == null) { + return false; + } + return this.settings.getMerged(0) || this.settings.getMerged(2) || this.settings.getMerged(1) || this.settings.getMerged(3); + } + + /** + * Get the timestamp of when the plot was created (unreliable)
+ * - not accurate if the plot was created before this was implemented
+ * - Milliseconds since the epoch
+ * @return + */ + public long getTimestamp() { + if (this.timestamp == 0) { + this.timestamp = System.currentTimeMillis(); + } + return this.timestamp; + } + + /** + * Get if the plot is merged in a direction
+ * ------- Actual -------
+ * 0 = north
+ * 1 = east
+ * 2 = south
+ * 3 = west
+ * ----- Artificial -----
+ * 4 = north-east
+ * 5 = south-east
+ * 6 = south-west
+ * 7 = north-west
+ * ----------
+ * Note: A plot that is merged north and east will not be merged northeast if the northeast plot is not part of the same group
+ * @param direction + * @return true if merged in that direction + */ + public boolean getMerged(final int direction) { + if (this.settings == null) { + return false; + } + switch (direction) { + case 0: + case 1: + case 2: + case 3: + return this.settings.getMerged(direction); + case 7: + int i = direction - 4; + int i2 = 0; + if (this.settings.getMerged(i2)) { + if (this.settings.getMerged(i)) { + if (this.area.getPlotAbs(this.id.getRelative(i)).getMerged(i2)) { + if (this.area.getPlotAbs(this.id.getRelative(i2)).getMerged(i)) { + return true; + } + } + } + } + return false; + case 4: + case 5: + case 6: + i = direction - 4; + i2 = direction - 3; + return this.settings.getMerged(i2) + && this.settings.getMerged(i) + && this.area.getPlotAbs(this.id.getRelative(i)).getMerged(i2) + && this.area.getPlotAbs(this.id.getRelative(i2)).getMerged(i); + + } + return false; + } + + /** + * Get the denied users + * @return + */ + public HashSet getDenied() { + if (this.denied == null) { + this.denied = new HashSet<>(); + } + return this.denied; + } + + /** + * Set the denied users for this plot + * @param uuids + */ + public void setDenied(final Set uuids) { + boolean larger = uuids.size() > getDenied().size(); + HashSet intersection = new HashSet<>(larger ? getDenied() : uuids); + intersection.retainAll(larger ? uuids : getDenied()); + uuids.removeAll(intersection); + HashSet toRemove = new HashSet<>(getDenied()); + toRemove.removeAll(intersection); + for (UUID uuid : toRemove) { + removeDenied(uuid); + } + for (UUID uuid : uuids) { + addDenied(uuid); + } + } + + /** + * Get the trusted users + * @return + */ + public HashSet getTrusted() { + if (this.trusted == null) { + this.trusted = new HashSet<>(); + } + return this.trusted; + } + + /** + * Set the trusted users for this plot + * @param uuids + */ + public void setTrusted(final Set uuids) { + boolean larger = uuids.size() > getTrusted().size(); + HashSet intersection = new HashSet<>(larger ? getTrusted() : uuids); + intersection.retainAll(larger ? uuids : getTrusted()); + uuids.removeAll(intersection); + HashSet toRemove = new HashSet<>(getTrusted()); + toRemove.removeAll(intersection); + for (UUID uuid : toRemove) { + removeTrusted(uuid); + } + for (UUID uuid : uuids) { + addTrusted(uuid); + } + } + + /** + * Get the members + * @return + */ + public HashSet getMembers() { + if (this.members == null) { + this.members = new HashSet<>(); + } + return this.members; + } + + /** + * Set the members for this plot + * @param uuids + */ + public void setMembers(final Set uuids) { + boolean larger = uuids.size() > getMembers().size(); + HashSet intersection = new HashSet<>(larger ? getMembers() : uuids); + intersection.retainAll(larger ? uuids : getMembers()); + uuids.removeAll(intersection); + HashSet toRemove = new HashSet<>(getMembers()); + toRemove.removeAll(intersection); + for (UUID uuid : toRemove) { + removeMember(uuid); + } + for (UUID uuid : uuids) { + addMember(uuid); + } + } + + /** + * Deny someone (updates database as well) + * @param uuid + */ + public void addDenied(final UUID uuid) { + for (Plot current : getConnectedPlots()) { + if (current.getDenied().add(uuid)) { + DBFunc.setDenied(current, uuid); + } + } + } + + /** + * Add someone as a helper (updates database as well) + * + * @param uuid + */ + public void addTrusted(final UUID uuid) { + for (Plot current : getConnectedPlots()) { + if (current.getTrusted().add(uuid)) { + DBFunc.setTrusted(current, uuid); + } + } + } + + /** + * Add someone as a trusted user (updates database as well) + * + * @param uuid + */ + public void addMember(final UUID uuid) { + for (Plot current : getConnectedPlots()) { + if (current.getMembers().add(uuid)) { + DBFunc.setMember(current, uuid); + } + } + } + + /** + * Set the plot owner (and update the database) + * @param owner + */ + public void setOwner(final UUID owner) { + if (!hasOwner()) { + this.owner = owner; + create(); + return; + } + if (!isMerged()) { + if (!this.owner.equals(owner)) { + this.owner = owner; + DBFunc.setOwner(this, owner); + } + return; + } + for (Plot current : getConnectedPlots()) { + if (!owner.equals(current.owner)) { + current.owner = owner; + DBFunc.setOwner(current, owner); + } + } + } + + /** + * Clear a plot + * @see this#clear(Runnable) + * @see this#clear(boolean, boolean, Runnable) + * @see #deletePlot(Runnable) to clear and delete a plot + * @param whenDone A runnable to execute when clearing finishes, or null + */ + public void clear(final Runnable whenDone) { + this.clear(false, false, whenDone); + } + + public boolean clear(final boolean checkRunning, final boolean isDelete, final Runnable whenDone) { + if (checkRunning && (this.getRunning() != 0)) { + return false; + } + if (!EventUtil.manager.callClear(this)) { + return false; + } + final HashSet regions = this.getRegions(); + final HashSet plots = this.getConnectedPlots(); + final ArrayDeque queue = new ArrayDeque<>(plots); + if (isDelete) { + this.removeSign(); + } + this.unlinkPlot(true, !isDelete); + final PlotManager manager = this.area.getPlotManager(); + final Runnable run = new Runnable() { + @Override + public void run() { + if (queue.isEmpty()) { + final AtomicInteger finished = new AtomicInteger(0); + final Runnable run = new Runnable() { + @Override + public void run() { + if (finished.incrementAndGet() >= plots.size()) { + for (final RegionWrapper region : regions) { + final Location[] corners = region.getCorners(Plot.this.area.worldname); + ChunkManager.manager.clearAllEntities(corners[0], corners[1]); + } + TaskManager.runTask(whenDone); + } + } + }; + if (isDelete) { + for (final Plot current : plots) { + manager.unclaimPlot(Plot.this.area, current, run); + } + } else { + for (final Plot current : plots) { + manager.claimPlot(Plot.this.area, current); + SetQueue.IMP.addTask(run); + } + } + return; + } + final Plot current = queue.poll(); + if ((Plot.this.area.TERRAIN != 0) || Settings.FAST_CLEAR) { + ChunkManager.manager.regenerateRegion(current.getBottomAbs(), current.getTopAbs(), false, this); + return; + } + manager.clearPlot(Plot.this.area, current, this); + } + }; + run.run(); + return true; + } + + /** + * Set the biome for a plot asynchronously + * @param biome The biome e.g. "forest" + * @param whenDone The task to run when finished, or null + */ + public void setBiome(final String biome, final Runnable whenDone) { + final ArrayDeque regions = new ArrayDeque<>(this.getRegions()); + final Runnable run = new Runnable() { + @Override + public void run() { + if (regions.isEmpty()) { + Plot.this.refreshChunks(); + TaskManager.runTask(whenDone); + return; + } + final RegionWrapper region = regions.poll(); + final Location pos1 = new Location(Plot.this.area.worldname, region.minX, region.minY, region.minZ); + final Location pos2 = new Location(Plot.this.area.worldname, region.maxX, region.maxY, region.maxZ); + ChunkManager.chunkTask(pos1, pos2, new RunnableVal() { + @Override + public void run(final int[] value) { + final ChunkLoc loc = new ChunkLoc(value[0], value[1]); + ChunkManager.manager.loadChunk(Plot.this.area.worldname, loc, false); + MainUtil.setBiome(Plot.this.area.worldname, value[2], value[3], value[4], value[5], biome); + ChunkManager.manager.unloadChunk(Plot.this.area.worldname, loc, true, true); + } + }, this, 5); + + } + }; + run.run(); + } + + /** + * Unlink the plot and all connected plots + * @param createSign + * @param createRoad + * @return + */ + public boolean unlinkPlot(final boolean createRoad, final boolean createSign) { + if (!this.isMerged()) { + return false; + } + final HashSet plots = this.getConnectedPlots(); + final ArrayList ids = new ArrayList<>(plots.size()); + for (final Plot current : plots) { + current.setHome(null); + ids.add(current.getId()); + } + final boolean result = EventUtil.manager.callUnlink(this.area, ids); + if (!result) { + return false; + } + this.clearRatings(); + if (createSign) { + this.removeSign(); + } + final PlotManager manager = this.area.getPlotManager(); + if (createRoad) { + manager.startPlotUnlink(this.area, ids); + } + if ((this.area.TERRAIN != 3) && createRoad) { + for (final Plot current : plots) { + if (current.getMerged(1)) { + manager.createRoadEast(current.area, current); + if (current.getMerged(2)) { + manager.createRoadSouth(current.area, current); + if (current.getMerged(5)) { + manager.createRoadSouthEast(current.area, current); + } + } + } else if (current.getMerged(2)) { + manager.createRoadSouth(current.area, current); + } + } + } + for (final Plot current : plots) { + final boolean[] merged = new boolean[] { false, false, false, false }; + current.setMerged(merged); + if (createSign) { + current.setSign(MainUtil.getName(current.owner)); + } + } + if (createRoad) { + manager.finishPlotUnlink(this.area, ids); + } + return true; + } + + /** + * Set the sign for a plot to a specific name + * @param name + */ + public void setSign(final String name) { + if (!PS.get().isMainThread(Thread.currentThread())) { + TaskManager.runTask(new Runnable() { + @Override + public void run() { + Plot.this.setSign(name); + } + }); + return; + } + final String rename = name == null ? "unknown" : name; + final PlotManager manager = this.area.getPlotManager(); + if (this.area.ALLOW_SIGNS) { + final Location loc = manager.getSignLoc(this.area, this); + final String id = this.id.x + ";" + this.id.y; + final String[] lines = new String[] { + C.OWNER_SIGN_LINE_1.formatted().replaceAll("%id%", id), + C.OWNER_SIGN_LINE_2.formatted().replaceAll("%id%", id).replaceAll("%plr%", rename), + C.OWNER_SIGN_LINE_3.formatted().replaceAll("%id%", id).replaceAll("%plr%", rename), + C.OWNER_SIGN_LINE_4.formatted().replaceAll("%id%", id).replaceAll("%plr%", rename) }; + WorldUtil.IMP.setSign(this.area.worldname, loc.getX(), loc.getY(), loc.getZ(), lines); + } + } + + /** + * This will return null if the plot hasn't been analyzed + * @return analysis of plot + */ + public PlotAnalysis getComplexity() { + return PlotAnalysis.getAnalysis(this); + } + + public void analyze(final RunnableVal whenDone) { + PlotAnalysis.analyzePlot(this, whenDone); + } + + /** + * Set a flag for this plot + * @param flag + * @param value + */ + public void setFlag(final String flag, final Object value) { + FlagManager.addPlotFlag(this, new Flag(FlagManager.getFlag(flag), value)); + } + + /** + * Remove a flag from this plot + * @param flag + */ + public void removeFlag(final String flag) { + FlagManager.removePlotFlag(this, flag); + } + + /** + * Get the flag for a given key + * @param key + */ + public Flag getFlag(final String key) { + return FlagManager.getPlotFlagRaw(this, key); + } + + /** + * Delete a plot (use null for the runnable if you don't need to be notified on completion) + * @see PS#removePlot(Plot, boolean) + * @see #clear(Runnable) to simply clear a plot + */ + public boolean deletePlot(final Runnable whenDone) { + if (!this.hasOwner()) { + return false; + } + final HashSet plots = this.getConnectedPlots(); + this.clear(false, true, new Runnable() { + @Override + public void run() { + for (final Plot current : plots) { + current.unclaim(); + } + TaskManager.runTask(whenDone); + } + }); + return true; + } + + /** + * Count the entities in a plot + * @see ChunkManager#countEntities(Plot) + * 0 = Entity + * 1 = Animal + * 2 = Monster + * 3 = Mob + * 4 = Boat + * 5 = Misc + * @return + */ + public int[] countEntities() { + final int[] count = new int[6]; + for (final Plot current : this.getConnectedPlots()) { + final int[] result = ChunkManager.manager.countEntities(current); + count[0] += result[0]; + count[1] += result[1]; + count[2] += result[2]; + count[3] += result[3]; + count[4] += result[4]; + count[5] += result[5]; + } + return count; + } + + /** + * Returns true if a previous task was running + * @return + */ + public int addRunning() { + final int value = this.getRunning(); + for (final Plot plot : this.getConnectedPlots()) { + plot.setMeta("running", value + 1); + } + return value; + } + + public int removeRunning() { + final int value = this.getRunning(); + if (value < 2) { + for (final Plot plot : this.getConnectedPlots()) { + plot.deleteMeta("running"); + } + } else { + for (final Plot plot : this.getConnectedPlots()) { + plot.setMeta("running", value - 1); + } + } + return value; + } + + public int getRunning() { + final Integer value = (Integer) this.getMeta("running"); + return value == null ? 0 : value; + } + + public boolean unclaim() { + if (owner == null) { + return false; + } + for (Plot current : getConnectedPlots()) { + getArea().removePlot(getId()); + DBFunc.delete(current); + current.settings = null; + } + return true; + } + + /** + * Unlink a plot and remove the roads + * @see this#unlinkPlot(boolean, boolean) + * @return true if plot was linked + */ + public boolean unlink() { + return this.unlinkPlot(true, true); + } + + public Location getCenter() { + final Location top = this.getTop(); + final Location bot = this.getBottom(); + return new Location(this.area.worldname, (top.getX() + bot.getX()) / 2, (top.getY() + bot.getY()) / 2, (top.getZ() + bot.getZ()) / 2); + } + + /** + * Return the home location for the plot + * @return Home location + */ + public Location getHome() { + final BlockLoc home = this.getPosition(); + if ((home == null) || ((home.x == 0) && (home.z == 0))) { + return this.getDefaultHome(); + } else { + final Location bot = this.getBottomAbs(); + final Location loc = new Location(bot.getWorld(), bot.getX() + home.x, bot.getY() + home.y, bot.getZ() + home.z, home.yaw, home.pitch); + if (WorldUtil.IMP.getBlock(loc).id != 0) { + loc.setY(Math.max(WorldUtil.IMP.getHighestBlock(this.area.worldname, loc.getX(), loc.getZ()), bot.getY())); + } + return loc; + } + } + + /** + * Set the home location + * @param loc + */ + public void setHome(final BlockLoc loc) { + final BlockLoc pos = this.getSettings().getPosition(); + if ((((pos == null) || pos.equals(new BlockLoc(0, 0, 0))) && (loc == null)) || ((pos != null) && pos.equals(loc))) { + return; + } + final Plot plot = this.getBasePlot(false); + plot.getSettings().setPosition(loc); + if (plot.getSettings().getPosition() == null) { + DBFunc.setPosition(plot, ""); + } else { + DBFunc.setPosition(plot, this.getSettings().getPosition().toString()); + } + } + + /** + * Get the default home location for a plot
+ * - Ignores any home location set for that specific plot + * @return + */ + public Location getDefaultHome() { + final Plot plot = this.getBasePlot(false); + if (this.area.DEFAULT_HOME != null) { + final int x; + final int z; + if ((this.area.DEFAULT_HOME.x == Integer.MAX_VALUE) && (this.area.DEFAULT_HOME.z == Integer.MAX_VALUE)) { + // center + final RegionWrapper largest = plot.getLargestRegion(); + x = ((largest.maxX - largest.minX) / 2) + largest.minX; + z = ((largest.maxZ - largest.minZ) / 2) + largest.minZ; + } else { + // specific + final Location bot = plot.getBottomAbs(); + x = bot.getX() + this.area.DEFAULT_HOME.x; + z = bot.getZ() + this.area.DEFAULT_HOME.z; + } + final int y = WorldUtil.IMP.getHighestBlock(plot.area.worldname, x, z); + return new Location(plot.area.worldname, x, y + 1, z); + } + // Side + final RegionWrapper largest = plot.getLargestRegion(); + final int x = ((largest.maxX - largest.minX) / 2) + largest.minX; + final int z = largest.minZ - 1; + final PlotManager manager = plot.getManager(); + final int y = Math.max(WorldUtil.IMP.getHighestBlock(plot.area.worldname, x, z), manager.getSignLoc(plot.area, plot).getY()); + return new Location(plot.area.worldname, x, y + 1, z); + } + + /** + * Get the average rating of the plot. This is the value displayed in /plot info + * @return average rating as double + */ + public double getAverageRating() { + double sum = 0; + final Collection ratings = this.getRatings().values(); + for (final Rating rating : ratings) { + sum += rating.getAverageRating(); + } + return sum / ratings.size(); + } + + /** + * Set a rating for a user
+ * - If the user has already rated, the following will return false + * @param uuid + * @param rating + * @return + */ + public boolean addRating(final UUID uuid, final Rating rating) { + final Plot base = this.getBasePlot(false); + final PlotSettings baseSettings = base.getSettings(); + if (baseSettings.getRatings().containsKey(uuid)) { + return false; + } + baseSettings.getRatings().put(uuid, rating.getAggregate()); + DBFunc.setRating(base, uuid, this.temp); + return true; + } + + /** + * Clear the ratings for this plot + */ + public void clearRatings() { + final Plot base = this.getBasePlot(false); + final PlotSettings baseSettings = base.getSettings(); + if ((baseSettings.ratings != null) && !baseSettings.ratings.isEmpty()) { + DBFunc.deleteRatings(base); + baseSettings.ratings = null; + } + } + + /** + * Get the ratings associated with a plot
+ * - The rating object may contain multiple categories + * @return Map of user who rated to the rating + */ + public HashMap getRatings() { + final Plot base = this.getBasePlot(false); + final HashMap map = new HashMap<>(); + if (base.getSettings().ratings == null) { + return map; + } + for (final Entry entry : base.getSettings().ratings.entrySet()) { + map.put(entry.getKey(), new Rating(entry.getValue())); + } + return map; + } + + public boolean hasRatings() { + Plot base = this.getBasePlot(false); + return base.settings != null && base.settings.ratings != null; + } + + /** + * Resend all chunks inside the plot to nearby players
+ * This should not need to be called + */ + public void refreshChunks() { + TaskManager.runTask(new Runnable() { + @Override + public void run() { + final HashSet chunks = new HashSet<>(); + for (final RegionWrapper region : Plot.this.getRegions()) { + for (int x = region.minX >> 4; x <= (region.maxX >> 4); x++) { + for (int z = region.minZ >> 4; z <= (region.maxZ >> 4); z++) { + chunks.add(new ChunkLoc(x, z)); + } + } + } + SetQueue.IMP.queue.sendChunk(Plot.this.area.worldname, chunks); + } + }); + } + + /** + * Remove the plot sign if it is set + */ + public void removeSign() { + final PlotManager manager = this.area.getPlotManager(); + if (!this.area.ALLOW_SIGNS) { + return; + } + final Location loc = manager.getSignLoc(this.area, this); + SetQueue.IMP.setBlock(this.area.worldname, loc.getX(), loc.getY(), loc.getZ(), 0); + } + + /** + * Set the plot sign if plot signs are enabled + */ + public void setSign() { + if (this.owner == null) { + this.setSign(null); + return; + } + this.setSign(UUIDHandler.getName(this.owner)); + } + + /** + * Register a plot and create it in the database
+ * - The plot will not be created if the owner is null
+ * - Any setting from before plot creation will not be saved until the server is stopped properly. i.e. Set any values/options after plot creation. + * @return true if plot was created successfully + */ + public boolean create() { + return this.create(this.owner, true); + } + + /** + * Register a plot and create it in the database
+ * - The plot will not be created if the owner is null
+ * - Any setting from before plot creation will not be saved until the server is stopped properly. i.e. Set any values/options after plot creation. + * @return true if plot was created successfully + */ + public boolean create(final UUID uuid, final boolean notify) { + if (uuid == null) { + throw new IllegalArgumentException("UUID cannot be null"); + } + this.owner = uuid; + final Plot existing = this.area.getOwnedPlotAbs(this.id); + if (existing != null) { + throw new IllegalStateException("Plot already exists!"); + } + if (notify) { + final Integer meta = (Integer) this.area.getMeta("worldBorder"); + if (meta != null) { + this.updateWorldBorder(); + } + } + connected_cache = null; + regions_cache = null; + this.getTrusted().clear(); + this.getMembers().clear(); + this.getDenied().clear(); + this.settings = new PlotSettings(); + if (this.area.addPlot(this)) { + DBFunc.createPlotAndSettings(Plot.this, new Runnable() { + @Override + public void run() { + final PlotArea plotworld = Plot.this.area; + if (notify && plotworld.AUTO_MERGE) { + Plot.this.autoMerge(-1, Integer.MAX_VALUE, uuid, true); + } + } + }); + return true; + } + return false; + } + + /** + * Set components such as border, wall, floor + * (components are generator specific) + */ + public boolean setComponent(final String component, final String blocks) { + final PlotBlock[] parsed = Configuration.BLOCKLIST.parseString(blocks); + if ((parsed == null) || (parsed.length == 0)) { + return false; + } + return this.setComponent(component, parsed); + } + + /** + * Get the biome (String) + */ + public String getBiome() { + final Location loc = this.getBottomAbs(); + return WorldUtil.IMP.getBiome(loc.getWorld(), loc.getX(), loc.getZ()); + } + + /** + * Return the top location for the plot + * @return + */ + public Location getTopAbs() { + return this.area.getPlotManager().getPlotTopLocAbs(this.area, this.id); + } + + /** + * Return the bottom location for the plot + * @return + */ + public Location getBottomAbs() { + return this.area.getPlotManager().getPlotBottomLocAbs(this.area, this.id); + } + + /** + * Swap the settings for two plots + * @param p2 + * @param whenDone + * @return + */ + public boolean swapData(final Plot p2, final Runnable whenDone) { + if (this.owner == null) { + if ((p2 != null) && p2.hasOwner()) { + p2.moveData(this, whenDone); + return true; + } + return false; + } + if ((p2 == null) || (p2.owner == null)) { + this.moveData(p2, whenDone); + return true; + } + // Swap cached + final PlotId temp = new PlotId(this.getId().x, this.getId().y); + this.getId().x = p2.getId().x; + this.getId().y = p2.getId().y; + p2.getId().x = temp.x; + p2.getId().y = temp.y; + this.area.removePlot(this.getId()); + p2.area.removePlot(p2.getId()); + this.getId().recalculateHash(); + p2.getId().recalculateHash(); + this.area.addPlotAbs(this); + p2.area.addPlotAbs(p2); + // Swap database + DBFunc.dbManager.swapPlots(p2, this); + TaskManager.runTaskLater(whenDone, 1); + return true; + } + + /** + * Move the settings for a plot + * @param pos2 + * @param whenDone + * @return + */ + public boolean moveData(final Plot pos2, final Runnable whenDone) { + if (this.owner == null) { + PS.debug(pos2 + " is unowned (single)"); + TaskManager.runTask(whenDone); + return false; + } + if (pos2.hasOwner()) { + PS.debug(pos2 + " is unowned (multi)"); + TaskManager.runTask(whenDone); + return false; + } + this.area.removePlot(this.id); + this.getId().x = pos2.getId().x; + this.getId().y = pos2.getId().y; + this.getId().recalculateHash(); + this.area.addPlotAbs(this); + DBFunc.movePlot(this, pos2); + TaskManager.runTaskLater(whenDone, 1); + return true; + } + + /** + * Gets the top loc of a plot (if mega, returns top loc of that mega plot) - If you would like each plot treated as + * a small plot use getPlotTopLocAbs(...) + * + * @return Location top of mega plot + */ + public Location getExtendedTopAbs() { + final Location top = this.getTopAbs(); + if (!this.isMerged()) { + return top; + } + if (this.getMerged(2)) { + top.setZ(this.getRelative(2).getBottomAbs().getZ() - 1); + } + if (this.getMerged(1)) { + top.setX(this.getRelative(1).getBottomAbs().getX() - 1); + } + return top; + } + + /** + * Gets the bottom location for a plot.
+ * - Does not respect mega plots
+ * - Merged plots, only the road will be considered part of the plot
+ * + * @return Location bottom of mega plot + */ + public Location getExtendedBottomAbs() { + final Location bot = this.getBottomAbs(); + if (!this.isMerged()) { + return bot; + } + if (this.getMerged(0)) { + bot.setZ(this.getRelative(0).getTopAbs().getZ() + 1); + } + if (this.getMerged(3)) { + bot.setX(this.getRelative(3).getTopAbs().getX() + 1); + } + return bot; + } + + /** + * Returns the top and bottom location.
+ * - If the plot is not connected, it will return its own corners
+ * - the returned locations will not necessarily correspond to claimed plots if the connected plots do not form a rectangular shape + * @deprecated as merged plots no longer need to be rectangular + * @return new Location[] { bottom, top } + */ + @Deprecated + public Location[] getCorners() { + if (!this.isMerged()) { + return new Location[] { this.getBottomAbs(), this.getTopAbs() }; + } + return MainUtil.getCorners(this.area.worldname, this.getRegions()); + } + + /** + * Remove the east road section of a plot
+ * - Used when a plot is merged
+ */ + public void removeRoadEast() { + if ((this.area.TYPE != 0) && (this.area.TERRAIN > 1)) { + if (this.area.TERRAIN == 3) { + return; + } + final Plot other = this.getRelative(1); + final Location bot = other.getBottomAbs(); + final Location top = this.getTopAbs(); + final Location pos1 = new Location(this.area.worldname, top.getX(), 0, bot.getZ()); + final Location pos2 = new Location(this.area.worldname, bot.getX(), 256, top.getZ()); + ChunkManager.manager.regenerateRegion(pos1, pos2, true, null); + } else { + this.area.getPlotManager().removeRoadEast(this.area, this); + } + } + + /** + * Returns the top and bottom plot id.
+ * - If the plot is not connected, it will return itself for the top/bottom
+ * - the returned ids will not necessarily correspond to claimed plots if the connected plots do not form a rectangular shape + * @deprecated as merged plots no longer need to be rectangular + * @return new Plot[] { bottom, top } + */ + @Deprecated + public PlotId[] getCornerIds() { + if (!this.isMerged()) { + return new PlotId[] { this.getId(), this.getId() }; + } + final PlotId min = new PlotId(this.getId().x, this.getId().y); + final PlotId max = new PlotId(this.getId().x, this.getId().y); + for (final Plot current : this.getConnectedPlots()) { + if (current.getId().x < min.x) { + min.x = current.getId().x; + } else if (current.getId().x > max.x) { + max.x = current.getId().x; + } + if (current.getId().y < min.y) { + min.y = current.getId().y; + } else if (current.getId().y > max.y) { + max.y = current.getId().y; + } + } + return new PlotId[] { min, max }; + } + + /** + * @deprecated in favor of getCorners()[0];
+ * @return + */ + @Deprecated + public Location getBottom() { + return this.getCorners()[0]; + } + + /** + * @deprecated in favor of getCorners()[1]; + * @return + */ + @Deprecated + public Location getTop() { + return this.getCorners()[0]; + } + + /** + * Swap the plot contents and settings with another location
+ * - The destination must correspond to a valid plot of equal dimensions + * @see ChunkManager#swap(Location, Location, Location, Location, Runnable) to swap terrain + * @see this#swapData(Plot, Runnable) to swap plot settings + * @param destination The other plot to swap with + * @param whenDone A task to run when finished, or null + * @see this#swapData(Plot, Runnable) + * @return boolean if swap was successful + */ + public boolean swap(final Plot destination, final Runnable whenDone) { + return this.move(destination, whenDone, true); + } + + /** + * Move the plot to an empty location
+ * - The location must be empty + * @param destination Where to move the plot + * @param whenDone A task to run when done, or null + * @return if the move was successful + */ + public boolean move(final Plot destination, final Runnable whenDone) { + return this.move(destination, whenDone, false); + } + + /** + * Get plot display name + * + * @return alias if set, else id + */ + @Override + public String toString() { + if ((this.settings != null) && (this.settings.getAlias().length() > 1)) { + return this.settings.getAlias(); + } + return this.area + ";" + this.id.x + ";" + this.id.y; + } + + /** + * Remove a denied player (use DBFunc as well)
+ * Using the * uuid will remove all users + * @param uuid + */ + public boolean removeDenied(final UUID uuid) { + if (uuid == DBFunc.everyone) { + boolean result = false; + for (final UUID other : getDenied()) { + result = result || rmvDenied(other); + } + return result; + } + return rmvDenied(uuid); + } + + private boolean rmvDenied(UUID uuid) { + for (Plot current : this.getConnectedPlots()) { + if (current.getDenied().remove(uuid)) { + DBFunc.removeDenied(current, uuid); + } else { + return false; + } + } + return true; + } + /** + * Remove a helper (use DBFunc as well)
+ * Using the * uuid will remove all users + * @param uuid + */ + public boolean removeTrusted(final UUID uuid) { + if (uuid == DBFunc.everyone) { + boolean result = false; + for (final UUID other : getTrusted()) { + result = result || rmvTrusted(other); + } + return result; + } + return rmvTrusted(uuid); + } + + private boolean rmvTrusted(UUID uuid) { + for (Plot plot : this.getConnectedPlots()) { + if (plot.getTrusted().remove(uuid)) { + DBFunc.removeTrusted(plot, uuid); + } else { + return false; + } + } + return true; + } + + /** + * Remove a trusted user (use DBFunc as well)
+ * Using the * uuid will remove all users + * @param uuid + */ + public boolean removeMember(final UUID uuid) { + if (this.members == null) { + return false; + } + if (uuid == DBFunc.everyone) { + boolean result = false; + for (final UUID other : new HashSet<>(this.members)) { + result = result || rmvMember(other); + } + return result; + } + return rmvMember(uuid); + } + + private boolean rmvMember(UUID uuid) { + for (Plot current : this.getConnectedPlots()) { + if (current.getMembers().remove(uuid)) { + DBFunc.removeMember(current, uuid); + } else { + return false; + } + } + return true; + } + + /** + * Export the plot as a schematic to the configured output directory + * @return + */ + public void export(final RunnableVal whenDone) { + SchematicHandler.manager.getCompoundTag(this, new RunnableVal() { + @Override + public void run(final CompoundTag value) { + if (value == null) { + if (whenDone != null) { + whenDone.value = false; + TaskManager.runTask(whenDone); + } + } else { + TaskManager.runTaskAsync(new Runnable() { + @Override + public void run() { + final String name = Plot.this.id + "," + Plot.this.area + "," + MainUtil.getName(Plot.this.owner); + final boolean result = SchematicHandler.manager.save(value, Settings.SCHEMATIC_SAVE_PATH + File.separator + name + ".schematic"); + if (whenDone != null) { + whenDone.value = result; + TaskManager.runTask(whenDone); + } + } + }); + } + } + }); + } + + /** + * Export the plot as a BO3 object
+ * - bedrock, floor and main block are ignored in their respective sections + * - air is ignored + * - The center is considered to be on top of the plot in the center + * @param whenDone value will be false if exporting fails + */ + public void exportBO3(final RunnableVal whenDone) { + final boolean result = BO3Handler.saveBO3(this); + if (whenDone != null) { + whenDone.value = result; + } + TaskManager.runTask(whenDone); + } + + /** + * Upload the plot as a schematic to the configured web interface + * @param whenDone value will be null if uploading fails + */ + public void upload(final RunnableVal whenDone) { + SchematicHandler.manager.getCompoundTag(this, new RunnableVal() { + @Override + public void run(final CompoundTag value) { + TaskManager.runTaskAsync(new Runnable() { + @Override + public void run() { + final URL url = SchematicHandler.manager.upload(value, null, null); + if (whenDone != null) { + whenDone.value = url; + } + TaskManager.runTask(whenDone); + } + }); + } + }); + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (this.getClass() != obj.getClass()) { + return false; + } + final Plot other = (Plot) obj; + return (this.hashCode() == other.hashCode()) && this.id.x.equals(other.id.x) && this.id.y.equals(other.id.y) && (this.area == other.area); + } + + /** + * Get the plot hashcode + * + * @return integer. + */ + @Override + public int hashCode() { + return this.id.hashCode(); + } + + /** + * Get the flags specific to this plot
+ * - Does not take default flags into account
+ * @return + */ + public HashMap getFlags() { + if (this.settings == null) { + return new HashMap<>(0); + } + return this.settings.flags; + } + + /** + * Set a flag for this plot + * @param flags + */ + public void setFlags(final Set flags) { + FlagManager.setPlotFlags(this, flags); + } + + /** + * Get the plot Alias
+ * - Returns an empty string if no alias is set + * @return + */ + public String getAlias() { + if (this.settings == null) { + return ""; + } + return this.settings.getAlias(); + } + + /** + * Set the plot alias + * @param alias + */ + public void setAlias(String alias) { + for (final Plot current : this.getConnectedPlots()) { + final String name = this.getSettings().getAlias(); + if (alias == null) { + alias = ""; + } + if (name.equals(alias)) { + return; + } + current.getSettings().setAlias(alias); + DBFunc.setAlias(current, alias); + } + } + + /** + * Set the raw merge data
+ * - Updates DB
+ * - Does not modify terrain
+ * ----------
+ * 0 = north
+ * 1 = east
+ * 2 = south
+ * 3 = west
+ * ----------
+ * @param direction + * @param value + */ + public void setMerged(final int direction, final boolean value) { + if (this.getSettings().setMerged(direction, value)) { + if (value) { + final Plot other = this.getRelative(direction).getBasePlot(false); + if (!other.equals(this.getBasePlot(false))) { + final Plot base = (other.id.y < this.id.y) || (other.id.y.equals(this.id.y) && (other.id.x < this.id.x)) ? other : this.origin; + this.origin.origin = base; + other.origin = base; + this.origin = base; + connected_cache = null; + } + } else { + if (this.origin != null) { + this.origin.origin = null; + this.origin = null; + } + connected_cache = null; + } + DBFunc.setMerged(this, this.getSettings().getMerged()); + regions_cache = null; + } + } + + /** + * Get the merged array + * @return boolean [ north, east, south, west ] + */ + public boolean[] getMerged() { + if (this.settings == null) { + return new boolean[] { false, false, false, false }; + } + return this.settings.getMerged(); + } + + /** + * Set the raw merge data
+ * - Updates DB
+ * - Does not modify terrain
+ * Get if the plot is merged in a direction
+ * ----------
+ * 0 = north
+ * 1 = east
+ * 2 = south
+ * 3 = west
+ * ----------
+ * Note: Diagonal merging (4-7) must be done by merging the corresponding plots. + * @param merged + */ + public void setMerged(final boolean[] merged) { + this.getSettings().setMerged(merged); + DBFunc.setMerged(this, merged); + connected_cache = null; + regions_cache = null; + if (this.origin != null) { + this.origin.origin = null; + this.origin = null; + } + } + + /** + * Get the set home location or 0,0,0 if no location is set
+ * - Does not take the default home location into account + * @see #getHome() + * @return + */ + public BlockLoc getPosition() { + if (this.settings == null) { + return new BlockLoc(0, 0, 0); + } + return this.settings.getPosition(); + } + + public boolean canClaim(final PlotPlayer player) { + if (Settings.ENABLE_CLUSTERS) { + final PlotCluster cluster = this.getCluster(); + if (cluster != null) { + if (!cluster.isAdded(player.getUUID()) && !Permissions.hasPermission(player, "plots.admin.command.claim")) { + return false; + } + } + } + return this.guessOwner() == null; + } + + public UUID guessOwner() { + if (this.hasOwner()) { + return this.owner; + } + if (!this.area.ALLOW_SIGNS) { + return null; + } + try { + final Location loc = this.getManager().getSignLoc(this.area, this); + ChunkManager.manager.loadChunk(loc.getWorld(), loc.getChunkLoc(), false); + final String[] lines = WorldUtil.IMP.getSign(loc); + if (lines == null) { + return null; + } + loop: for (int i = 4; i > 0; i--) { + final String caption = C.valueOf("OWNER_SIGN_LINE_" + i).s(); + final int index = caption.indexOf("%plr%"); + if (index == -1) { + continue; + } + final String name = lines[i - 1].substring(index); + if (name.isEmpty()) { + return null; + } + final UUID owner = UUIDHandler.getUUID(name, null); + if (owner != null) { + this.owner = owner; + break; + } + if (lines[i - 1].length() == 15) { + final BiMap map = UUIDHandler.getUuidMap(); + for (final Entry entry : map.entrySet()) { + final String key = entry.getKey().value; + if ((key.length() > name.length()) && key.startsWith(name)) { + this.owner = entry.getValue(); + break loop; + } + } + } + this.owner = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(StandardCharsets.UTF_8)); + break; + } + if (this.hasOwner()) { + this.create(); + } + return this.owner; + } catch (final IllegalArgumentException e) { + return null; + } + } + + /** + * Remove the south road section of a plot
+ * - Used when a plot is merged
+ */ + public void removeRoadSouth() { + if ((this.area.TYPE != 0) && (this.area.TERRAIN > 1)) { + if (this.area.TERRAIN == 3) { + return; + } + final Plot other = this.getRelative(2); + final Location bot = other.getBottomAbs(); + final Location top = this.getTopAbs(); + final Location pos1 = new Location(this.area.worldname, bot.getX(), 0, top.getZ()); + final Location pos2 = new Location(this.area.worldname, top.getX(), 256, bot.getZ()); + ChunkManager.manager.regenerateRegion(pos1, pos2, true, null); + } else { + this.getManager().removeRoadSouth(this.area, this); + } + } + + /** + * Auto merge a plot in a specific direction
+ * @param dir The direction to merge
+ * -1 = All directions
+ * 0 = north
+ * 1 = east
+ * 2 = south
+ * 3 = west
+ * @param max The max number of merges to do + * @param uuid The UUID it is allowed to merge with + * @param removeRoads Whether to remove roads + * @return true if a merge takes place + */ + public boolean autoMerge(final int dir, int max, final UUID uuid, final boolean removeRoads) { + if (this.owner == null) { + return false; + } + final HashSet visited = new HashSet<>(); + final HashSet merged = new HashSet<>(); + final HashSet connected = this.getConnectedPlots(); + for (final Plot current : connected) { + merged.add(current.getId()); + } + final ArrayDeque frontier = new ArrayDeque<>(connected); + Plot current; + boolean toReturn = false; + while (((current = frontier.poll()) != null) && (max >= 0)) { + if (visited.contains(current)) { + continue; + } + visited.add(current); + Set plots; + if ((max >= 0) && ((dir == -1) || (dir == 0)) && !current.getMerged(0)) { + final Plot other = current.getRelative(0); + if ((other != null) + && other.isOwner(uuid) + && (other.getBasePlot(false).equals(current.getBasePlot(false)) || (((plots = other.getConnectedPlots()).size() <= max) && frontier.addAll(plots) && ((max -= plots.size()) != -1)))) { + current.mergePlot(other, removeRoads); + merged.add(current.getId()); + merged.add(other.getId()); + toReturn = true; + } + } + if ((max >= 0) && ((dir == -1) || (dir == 1)) && !current.getMerged(1)) { + final Plot other = current.getRelative(1); + if ((other != null) + && other.isOwner(uuid) + && (other.getBasePlot(false).equals(current.getBasePlot(false)) || (((plots = other.getConnectedPlots()).size() <= max) && frontier.addAll(plots) && ((max -= plots.size()) != -1)))) { + current.mergePlot(other, removeRoads); + merged.add(current.getId()); + merged.add(other.getId()); + toReturn = true; + } + } + if ((max >= 0) && ((dir == -1) || (dir == 2)) && !current.getMerged(2)) { + final Plot other = current.getRelative(2); + if ((other != null) + && other.isOwner(uuid) + && (other.getBasePlot(false).equals(current.getBasePlot(false)) || (((plots = other.getConnectedPlots()).size() <= max) && frontier.addAll(plots) && ((max -= plots.size()) != -1)))) { + current.mergePlot(other, removeRoads); + merged.add(current.getId()); + merged.add(other.getId()); + toReturn = true; + } + } + if ((max >= 0) && ((dir == -1) || (dir == 3)) && !current.getMerged(3)) { + final Plot other = current.getRelative(3); + if ((other != null) + && other.isOwner(uuid) + && (other.getBasePlot(false).equals(current.getBasePlot(false)) || (((plots = other.getConnectedPlots()).size() <= max) && frontier.addAll(plots) && ((max -= plots.size()) != -1)))) { + current.mergePlot(other, removeRoads); + merged.add(current.getId()); + merged.add(other.getId()); + toReturn = true; + } + } + } + if (removeRoads && toReturn) { + final ArrayList ids = new ArrayList<>(merged); + this.getManager().finishPlotMerge(this.area, ids); + } + return toReturn; + } + + /** + * Merge the plot settings
+ * - Used when a plot is merged
+ * @param b + */ + public void mergeData(final Plot b) { + final HashMap flags1 = this.getFlags(); + final HashMap flags2 = b.getFlags(); + if ((!flags1.isEmpty() || !flags2.isEmpty()) && !flags1.equals(flags2)) { + final boolean greater = flags1.size() > flags2.size(); + if (greater) { + flags1.putAll(flags2); + } else { + flags2.putAll(flags1); + } + final HashSet net = new HashSet<>((greater ? flags1 : flags2).values()); + this.setFlags(net); + b.setFlags(net); + } + if (!this.getAlias().isEmpty()) { + b.setAlias(this.getAlias()); + } else if (!b.getAlias().isEmpty()) { + this.setAlias(b.getAlias()); + } + for (final UUID uuid : this.getTrusted()) { + b.addTrusted(uuid); + } + for (final UUID uuid : b.getTrusted()) { + this.addTrusted(uuid); + } + for (final UUID uuid : this.getMembers()) { + b.addMember(uuid); + } + for (final UUID uuid : b.getMembers()) { + this.addMember(uuid); + } + + for (final UUID uuid : this.getDenied()) { + b.addDenied(uuid); + } + for (final UUID uuid : b.getDenied()) { + this.addDenied(uuid); + } + } + + public void removeRoadSouthEast() { + if ((this.area.TYPE != 0) && (this.area.TERRAIN > 1)) { + if (this.area.TERRAIN == 3) { + return; + } + final Plot other = this.getRelative(1, 1); + final Location pos1 = this.getTopAbs().add(1, 0, 1); + final Location pos2 = other.getBottomAbs().subtract(1, 0, 1); + pos1.setY(0); + pos2.setY(256); + ChunkManager.manager.regenerateRegion(pos1, pos2, true, null); + } else { + this.area.getPlotManager().removeRoadSouthEast(this.area, this); + } + } + + public Plot getRelative(final int x, final int y) { + return this.area.getPlotAbs(this.id.getRelative(x, y)); + } + + public Plot getRelative(final int direction) { + return this.area.getPlotAbs(this.id.getRelative(direction)); + } + + /** + * Get a set of plots connected (and including) this plot
+ * - This result is cached globally + * @return + */ + public HashSet getConnectedPlots() { + if (this.settings == null) { + return new HashSet<>(Collections.singletonList(this)); + } + boolean[] merged = this.getMerged(); + final int hash = MainUtil.hash(merged); + if (hash == 0) { + return new HashSet<>(Collections.singletonList(this)); + } + if ((connected_cache != null) && connected_cache.contains(this)) { + return connected_cache; + } + regions_cache = null; + connected_cache = new HashSet<>(); + final ArrayDeque frontier = new ArrayDeque<>(); + final HashSet queuecache = new HashSet<>(); + connected_cache.add(this); + Plot tmp; + if (merged[0]) { + tmp = this.area.getPlotAbs(this.id.getRelative(0)); + if (!tmp.getMerged(2)) { + // invalid merge + PS.debug("Fixing invalid merge: " + this); + if (tmp.isOwnerAbs(owner)) { + tmp.getSettings().setMerged(2, true); + DBFunc.setMerged(tmp, tmp.settings.getMerged()); + } else { + this.getSettings().setMerged(0, false); + DBFunc.setMerged(this, this.settings.getMerged()); + } + } + queuecache.add(tmp); + frontier.add(tmp); + } + if (merged[1]) { + tmp = this.area.getPlotAbs(this.id.getRelative(1)); + if (!tmp.getMerged(3)) { + // invalid merge + PS.debug("Fixing invalid merge: " + this); + if (tmp.isOwnerAbs(owner)) { + tmp.getSettings().setMerged(3, true); + DBFunc.setMerged(tmp, tmp.settings.getMerged()); + } else { + this.getSettings().setMerged(1, false); + DBFunc.setMerged(this, this.settings.getMerged()); + } + } + queuecache.add(tmp); + frontier.add(tmp); + } + if (merged[2]) { + tmp = this.area.getPlotAbs(this.id.getRelative(2)); + if (!tmp.getMerged(0)) { + // invalid merge + PS.debug("Fixing invalid merge: " + this); + if (tmp.isOwnerAbs(owner)) { + tmp.getSettings().setMerged(0, true); + DBFunc.setMerged(tmp, tmp.settings.getMerged()); + } else { + this.getSettings().setMerged(2, false); + DBFunc.setMerged(this, this.settings.getMerged()); + } + } + queuecache.add(tmp); + frontier.add(tmp); + } + if (merged[3]) { + tmp = this.area.getPlotAbs(this.id.getRelative(3)); + if (!tmp.getMerged(1)) { + // invalid merge + PS.debug("Fixing invalid merge: " + this); + if (tmp.isOwnerAbs(owner)) { + tmp.getSettings().setMerged(1, true); + DBFunc.setMerged(tmp, tmp.settings.getMerged()); + } else { + this.getSettings().setMerged(3, false); + DBFunc.setMerged(this, this.settings.getMerged()); + } + } + queuecache.add(tmp); + frontier.add(tmp); + } + Plot current; + while ((current = frontier.poll()) != null) { + if ((current.owner == null) || (current.settings == null)) { + // Invalid plot + // merged onto unclaimed plot + PS.debug("Ignoring invalid merged plot: " + current + " | " + current.owner); + continue; + } + connected_cache.add(current); + queuecache.remove(current); + merged = current.getMerged(); + if (merged[0]) { + tmp = current.area.getPlotAbs(current.id.getRelative(0)); + if ((tmp != null) && !queuecache.contains(tmp) && !connected_cache.contains(tmp)) { + queuecache.add(tmp); + frontier.add(tmp); + } + } + if (merged[1]) { + tmp = current.area.getPlotAbs(current.id.getRelative(1)); + if ((tmp != null) && !queuecache.contains(tmp) && !connected_cache.contains(tmp)) { + queuecache.add(tmp); + frontier.add(tmp); + } + } + if (merged[2]) { + tmp = current.area.getPlotAbs(current.id.getRelative(2)); + if ((tmp != null) && !queuecache.contains(tmp) && !connected_cache.contains(tmp)) { + queuecache.add(tmp); + frontier.add(tmp); + } + } + if (merged[3]) { + tmp = current.area.getPlotAbs(current.id.getRelative(3)); + if ((tmp != null) && !queuecache.contains(tmp) && !connected_cache.contains(tmp)) { + queuecache.add(tmp); + frontier.add(tmp); + } + } + } + return connected_cache; + } + + /** + * This will combine each plot into effective rectangular regions
+ * - This result is cached globally
+ * - Useful for handling non rectangular shapes + * @return + */ + public HashSet getRegions() { + if ((regions_cache != null) && (connected_cache != null) && connected_cache.contains(this)) { + return regions_cache; + } + if (!this.isMerged()) { + final Location pos1 = this.getBottomAbs(); + final Location pos2 = this.getTopAbs(); + connected_cache = new HashSet<>(Collections.singletonList(this)); + regions_cache = new HashSet<>(1); + regions_cache.add(new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getY(), pos2.getY(), pos1.getZ(), pos2.getZ())); + return regions_cache; + } + final HashSet plots = this.getConnectedPlots(); + regions_cache = new HashSet<>(); + final HashSet visited = new HashSet<>(); + for (final Plot current : plots) { + if (visited.contains(current.getId())) { + continue; + } + boolean merge = true; + final PlotId bot = new PlotId(current.getId().x, current.getId().y); + final PlotId top = new PlotId(current.getId().x, current.getId().y); + while (merge) { + merge = false; + ArrayList ids = MainUtil.getPlotSelectionIds(new PlotId(bot.x, bot.y - 1), new PlotId(top.x, bot.y - 1)); + boolean tmp = true; + for (final PlotId id : ids) { + final Plot plot = this.area.getPlotAbs(id); + if ((plot == null) || !plot.getMerged(2) || visited.contains(plot.getId())) { + tmp = false; + } + } + if (tmp) { + merge = true; + bot.y--; + } + ids = MainUtil.getPlotSelectionIds(new PlotId(top.x + 1, bot.y), new PlotId(top.x + 1, top.y)); + tmp = true; + for (final PlotId id : ids) { + final Plot plot = this.area.getPlotAbs(id); + if ((plot == null) || !plot.getMerged(3) || visited.contains(plot.getId())) { + tmp = false; + } + } + if (tmp) { + merge = true; + top.x++; + } + ids = MainUtil.getPlotSelectionIds(new PlotId(bot.x, top.y + 1), new PlotId(top.x, top.y + 1)); + tmp = true; + for (final PlotId id : ids) { + final Plot plot = this.area.getPlotAbs(id); + if ((plot == null) || !plot.getMerged(0) || visited.contains(plot.getId())) { + tmp = false; + } + } + if (tmp) { + merge = true; + top.y++; + } + ids = MainUtil.getPlotSelectionIds(new PlotId(bot.x - 1, bot.y), new PlotId(bot.x - 1, top.y)); + tmp = true; + for (final PlotId id : ids) { + final Plot plot = this.area.getPlotAbs(id); + if ((plot == null) || !plot.getMerged(1) || visited.contains(plot.getId())) { + tmp = false; + } + } + if (tmp) { + merge = true; + bot.x--; + } + } + final Location gtopabs = this.area.getPlotAbs(top).getTopAbs(); + final Location gbotabs = this.area.getPlotAbs(bot).getBottomAbs(); + for (final PlotId id : MainUtil.getPlotSelectionIds(bot, top)) { + visited.add(id); + } + for (int x = bot.x; x <= top.x; x++) { + final Plot plot = this.area.getPlotAbs(new PlotId(x, top.y)); + if (plot.getMerged(2)) { + // south wedge + final Location toploc = plot.getExtendedTopAbs(); + final Location botabs = plot.getBottomAbs(); + final Location topabs = plot.getTopAbs(); + regions_cache.add(new RegionWrapper(botabs.getX(), topabs.getX(), topabs.getZ() + 1, toploc.getZ())); + if (plot.getMerged(5)) { + regions_cache.add(new RegionWrapper(topabs.getX() + 1, toploc.getX(), topabs.getZ() + 1, toploc.getZ())); + // intersection + } + } + } + + for (int y = bot.y; y <= top.y; y++) { + final Plot plot = this.area.getPlotAbs(new PlotId(top.x, y)); + if (plot.getMerged(1)) { + // east wedge + final Location toploc = plot.getExtendedTopAbs(); + final Location botabs = plot.getBottomAbs(); + final Location topabs = plot.getTopAbs(); + regions_cache.add(new RegionWrapper(topabs.getX() + 1, toploc.getX(), botabs.getZ(), topabs.getZ())); + if (plot.getMerged(5)) { + regions_cache.add(new RegionWrapper(topabs.getX() + 1, toploc.getX(), topabs.getZ() + 1, toploc.getZ())); + // intersection + } + } + } + regions_cache.add(new RegionWrapper(gbotabs.getX(), gtopabs.getX(), gbotabs.getZ(), gtopabs.getZ())); + } + return regions_cache; + } + + /** + * Attempt to find the largest rectangular region in a plot (as plots can form non rectangular shapes) + * @return + */ + public RegionWrapper getLargestRegion() { + final HashSet regions = this.getRegions(); + RegionWrapper max = null; + int area = 0; + for (final RegionWrapper region : regions) { + final int current = ((region.maxX - region.minX) + 1) * ((region.maxZ - region.minZ) + 1); + if (current > area) { + max = region; + area = current; + } + } + return max; + } + + public void reEnter() { + TaskManager.runTaskLater(new Runnable() { + @Override + public void run() { + for (final PlotPlayer pp : Plot.this.getPlayersInPlot()) { + PlotListener.plotExit(pp, Plot.this); + PlotListener.plotEntry(pp, Plot.this); + } + } + }, 1); + } + + /** + * Get all the corners of the plot (supports non-rectangular shapes)
+ * @return + */ + public List getAllCorners() { + final Area area = new Area(); + for (final RegionWrapper region : this.getRegions()) { + final Area rectArea = new Area(new Rectangle(region.minX, region.minZ, region.maxX - region.minX, region.maxZ - region.minZ)); + area.add(rectArea); + } + final List locs = new ArrayList<>(); + double[] coords = new double[6]; + for (PathIterator pi = area.getPathIterator(null); !pi.isDone(); pi.next()) { + int type = pi.currentSegment(coords); + final int x = (int) coords[0]; + final int z = (int) coords[1]; + if (type != 4) { + locs.add(new Location(this.area.worldname, x, 0, z)); + } + } + return locs; + } + + /** + * Teleport a player to a plot and send them the teleport message. + * @param player + * @return If the teleportation is allowed. + */ + public boolean teleportPlayer(final PlotPlayer player) { + final Plot plot = this.getBasePlot(false); + final boolean result = EventUtil.manager.callTeleport(player, player.getLocation(), plot); + if (result) { + final Location location; + if (this.area.HOME_ALLOW_NONMEMBER || plot.isAdded(player.getUUID())) { + location = this.getHome(); + } else { + location = this.getDefaultHome(); + } + if ((Settings.TELEPORT_DELAY == 0) || Permissions.hasPermission(player, "plots.teleport.delay.bypass")) { + MainUtil.sendMessage(player, C.TELEPORTED_TO_PLOT); + player.teleport(location); + return true; + } + MainUtil.sendMessage(player, C.TELEPORT_IN_SECONDS, Settings.TELEPORT_DELAY + ""); + final String name = player.getName(); + TaskManager.TELEPORT_QUEUE.add(name); + TaskManager.runTaskLater(new Runnable() { + @Override + public void run() { + if (!TaskManager.TELEPORT_QUEUE.contains(name)) { + MainUtil.sendMessage(player, C.TELEPORT_FAILED); + return; + } + TaskManager.TELEPORT_QUEUE.remove(name); + if (!player.isOnline()) { + return; + } + MainUtil.sendMessage(player, C.TELEPORTED_TO_PLOT); + player.teleport(location); + } + }, Settings.TELEPORT_DELAY * 20); + return true; + } + return result; + } + + public boolean isOnline() { + if (owner == null) { + return false; + } + if (!isMerged()) { + return UUIDHandler.getPlayer(owner) != null; + } + for (Plot current : getConnectedPlots()) { + if (current.hasOwner() && UUIDHandler.getPlayer(current.owner) != null) { + return true; + } + } + return false; + } + + /** + * Set a component for a plot to the provided blocks
+ * - E.g. floor, wall, border etc.
+ * - The available components depend on the generator being used
+ * @param component + * @param blocks + * @return + */ + public boolean setComponent(final String component, final PlotBlock[] blocks) { + return this.getManager().setComponent(this.area, this.getId(), component, blocks); + } + + /** + * Expand the world border to include the provided plot (if applicable) + */ + public void updateWorldBorder() { + if (this.owner == null) { + return; + } + final int border = this.area.getBorder(); + if (border == Integer.MAX_VALUE) { + return; + } + final PlotId id = new PlotId(Math.abs(this.getId().x) + 1, Math.abs(this.getId().x) + 1); + final PlotManager manager = this.getManager(); + final Location bot = manager.getPlotBottomLocAbs(this.area, id); + final Location top = manager.getPlotTopLocAbs(this.area, id); + final int botmax = Math.max(Math.abs(bot.getX()), Math.abs(bot.getZ())); + final int topmax = Math.max(Math.abs(top.getX()), Math.abs(top.getZ())); + final int max = Math.max(botmax, topmax); + if (max > border) { + this.area.setMeta("worldBorder", max); + } + } + + /** + * Merges 2 plots Removes the road inbetween
- Assumes plots are directly next to each other
- saves to DB + * + * @param lesserPlot + * @param removeRoads + */ + public void mergePlot(Plot lesserPlot, final boolean removeRoads) { + Plot greaterPlot = this; + if (lesserPlot.getId().x.equals(greaterPlot.getId().x)) { + if (lesserPlot.getId().y > greaterPlot.getId().y) { + final Plot tmp = lesserPlot; + lesserPlot = greaterPlot; + greaterPlot = tmp; + } + if (!lesserPlot.getMerged(2)) { + lesserPlot.clearRatings(); + greaterPlot.clearRatings(); + lesserPlot.setMerged(2, true); + greaterPlot.setMerged(0, true); + lesserPlot.mergeData(greaterPlot); + if (removeRoads) { + if (lesserPlot.getMerged(5)) { + lesserPlot.removeRoadSouthEast(); + } + lesserPlot.removeRoadSouth(); + final Plot other = this.getRelative(3); + if (other.getMerged(2) && other.getMerged(1)) { + other.removeRoadEast(); + greaterPlot.mergePlot(other, removeRoads); + } + } + } + } else { + if (lesserPlot.getId().x > greaterPlot.getId().x) { + final Plot tmp = lesserPlot; + lesserPlot = greaterPlot; + greaterPlot = tmp; + } + if (!lesserPlot.getMerged(1)) { + lesserPlot.clearRatings(); + greaterPlot.clearRatings(); + lesserPlot.setMerged(1, true); + greaterPlot.setMerged(3, true); + lesserPlot.mergeData(greaterPlot); + if (removeRoads) { + lesserPlot.removeRoadEast(); + if (lesserPlot.getMerged(5)) { + lesserPlot.removeRoadSouthEast(); + } + final Plot other = lesserPlot.getRelative(0); + if (other.getMerged(2) && other.getMerged(1)) { + other.removeRoadSouthEast(); + greaterPlot.mergePlot(other, removeRoads); + } + } + } + } + } + + /** + * Move a plot physically, as well as the corresponding settings. + * @param destination + * @param whenDone + * @param allowSwap + * @return + */ + public boolean move(final Plot destination, final Runnable whenDone, final boolean allowSwap) { + final PlotId offset = new PlotId(destination.getId().x - this.getId().x, destination.getId().y - this.getId().y); + final Location db = destination.getBottomAbs(); + final Location ob = this.getBottomAbs(); + final int offsetX = db.getX() - ob.getX(); + final int offsetZ = db.getZ() - ob.getZ(); + if (this.owner == null) { + TaskManager.runTaskLater(whenDone, 1); + return false; + } + boolean occupied = false; + final HashSet plots = this.getConnectedPlots(); + for (final Plot plot : plots) { + final Plot other = plot.getRelative(offset.x, offset.y); + if (other.hasOwner()) { + if (!allowSwap) { + TaskManager.runTaskLater(whenDone, 1); + return false; + } + occupied = true; + } + } + // world border + destination.updateWorldBorder(); + final ArrayDeque regions = new ArrayDeque<>(this.getRegions()); + // move / swap data + for (final Plot plot : plots) { + final Plot other = plot.getRelative(offset.x, offset.y); + plot.swapData(other, null); + } + // copy terrain + final Runnable move = new Runnable() { + @Override + public void run() { + if (regions.isEmpty()) { + TaskManager.runTask(whenDone); + return; + } + final Runnable task = this; + final RegionWrapper region = regions.poll(); + final Location[] corners = region.getCorners(Plot.this.area.worldname); + final Location pos1 = corners[0]; + final Location pos2 = corners[1]; + final Location newPos = pos1.clone().add(offsetX, 0, offsetZ); + newPos.setWorld(destination.area.worldname); + ChunkManager.manager.regenerateRegion(pos1, pos2, false, task); + } + }; + final Runnable swap = new Runnable() { + @Override + public void run() { + if (regions.isEmpty()) { + TaskManager.runTask(whenDone); + return; + } + final RegionWrapper region = regions.poll(); + final Location[] corners = region.getCorners(Plot.this.area.worldname); + final Location pos1 = corners[0]; + final Location pos2 = corners[1]; + final Location pos3 = pos1.clone().add(offsetX, 0, offsetZ); + final Location pos4 = pos2.clone().add(offsetX, 0, offsetZ); + pos3.setWorld(destination.area.worldname); + pos4.setWorld(destination.area.worldname); + ChunkManager.manager.swap(pos1, pos2, pos3, pos4, this); + } + }; + if (occupied) { + swap.run(); + } else { + move.run(); + } + return true; + } + + /** + * Copy a plot to a location, both physically and the settings + * @param destination + * @param whenDone + * @return + */ + public boolean copy(final Plot destination, final Runnable whenDone) { + final PlotId offset = new PlotId(destination.getId().x - this.getId().x, destination.getId().y - this.getId().y); + final Location db = destination.getBottomAbs(); + final Location ob = this.getBottomAbs(); + final int offsetX = db.getX() - ob.getX(); + final int offsetZ = db.getZ() - ob.getZ(); + if (this.owner == null) { + TaskManager.runTaskLater(whenDone, 1); + return false; + } + final HashSet plots = this.getConnectedPlots(); + for (final Plot plot : plots) { + final Plot other = plot.getRelative(offset.x, offset.y); + if (other.hasOwner()) { + TaskManager.runTaskLater(whenDone, 1); + return false; + } + } + // world border + destination.updateWorldBorder(); + // copy data + for (final Plot plot : plots) { + final Plot other = plot.getRelative(offset.x, offset.y); + other.create(other.owner, false); + if ((plot.getFlags() != null) && !plot.getFlags().isEmpty()) { + other.getSettings().flags = plot.getFlags(); + DBFunc.setFlags(other, plot.getFlags().values()); + } + if (plot.isMerged()) { + other.setMerged(plot.getMerged()); + } + if ((plot.members != null) && !plot.members.isEmpty()) { + other.members = plot.members; + for (final UUID member : other.members) { + DBFunc.setMember(other, member); + } + } + if ((plot.trusted != null) && !plot.trusted.isEmpty()) { + other.trusted = plot.trusted; + for (final UUID trusted : other.trusted) { + DBFunc.setTrusted(other, trusted); + } + } + if ((plot.denied != null) && !plot.denied.isEmpty()) { + other.denied = plot.denied; + for (final UUID denied : other.denied) { + DBFunc.setDenied(other, denied); + } + } + PS.get().updatePlot(other); + } + // copy terrain + final ArrayDeque regions = new ArrayDeque<>(this.getRegions()); + final Runnable run = new Runnable() { + @Override + public void run() { + if (regions.isEmpty()) { + TaskManager.runTask(whenDone); + return; + } + final RegionWrapper region = regions.poll(); + final Location[] corners = region.getCorners(Plot.this.area.worldname); + final Location pos1 = corners[0]; + final Location pos2 = corners[1]; + final Location newPos = pos1.clone().add(offsetX, 0, offsetZ); + newPos.setWorld(destination.area.worldname); + ChunkManager.manager.copyRegion(pos1, pos2, newPos, this); + } + }; + run.run(); + return true; + } +} diff --git a/src/main/java/com/intellectualcrafters/plot/object/PlotAnalysis.java b/Core/src/main/java/com/intellectualcrafters/plot/object/PlotAnalysis.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/PlotAnalysis.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/PlotAnalysis.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/PlotArea.java b/Core/src/main/java/com/intellectualcrafters/plot/object/PlotArea.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/PlotArea.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/PlotArea.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/PlotBlock.java b/Core/src/main/java/com/intellectualcrafters/plot/object/PlotBlock.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/PlotBlock.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/PlotBlock.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/PlotCluster.java b/Core/src/main/java/com/intellectualcrafters/plot/object/PlotCluster.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/PlotCluster.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/PlotCluster.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/PlotFilter.java b/Core/src/main/java/com/intellectualcrafters/plot/object/PlotFilter.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/PlotFilter.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/PlotFilter.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/PlotHandler.java b/Core/src/main/java/com/intellectualcrafters/plot/object/PlotHandler.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/PlotHandler.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/PlotHandler.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/PlotId.java b/Core/src/main/java/com/intellectualcrafters/plot/object/PlotId.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/PlotId.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/PlotId.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/PlotInventory.java b/Core/src/main/java/com/intellectualcrafters/plot/object/PlotInventory.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/PlotInventory.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/PlotInventory.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/PlotItemStack.java b/Core/src/main/java/com/intellectualcrafters/plot/object/PlotItemStack.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/PlotItemStack.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/PlotItemStack.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/PlotLoc.java b/Core/src/main/java/com/intellectualcrafters/plot/object/PlotLoc.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/PlotLoc.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/PlotLoc.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/PlotManager.java b/Core/src/main/java/com/intellectualcrafters/plot/object/PlotManager.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/PlotManager.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/PlotManager.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/PlotMessage.java b/Core/src/main/java/com/intellectualcrafters/plot/object/PlotMessage.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/PlotMessage.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/PlotMessage.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/PlotPlayer.java b/Core/src/main/java/com/intellectualcrafters/plot/object/PlotPlayer.java similarity index 96% rename from src/main/java/com/intellectualcrafters/plot/object/PlotPlayer.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/PlotPlayer.java index 38e9ecd82..6ef6e4ba7 100644 --- a/src/main/java/com/intellectualcrafters/plot/object/PlotPlayer.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/object/PlotPlayer.java @@ -1,453 +1,453 @@ -package com.intellectualcrafters.plot.object; - -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.commands.RequiredType; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.util.CmdConfirm; -import com.intellectualcrafters.plot.util.EventUtil; -import com.intellectualcrafters.plot.util.ExpireManager; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.PlotGamemode; -import com.intellectualcrafters.plot.util.PlotWeather; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.plotsquared.general.commands.CommandCaller; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * The PlotPlayer class
- * - Can cast to: BukkitPlayer / SpongePlayer, which are the current implementations
- */ -public abstract class PlotPlayer implements CommandCaller { - - private Map metaMap = new HashMap<>(); - - /** - * The metadata map - */ - private ConcurrentHashMap meta; - - /** - * Efficiently wrap a Player, or OfflinePlayer object to get a PlotPlayer (or fetch if it's already cached)
- * - Accepts sponge/bukkit Player (online) - * - Accepts player name (online) - * - Accepts UUID - * - Accepts bukkit OfflinePlayer (offline) - * @param obj - * @return - */ - public static PlotPlayer wrap(final Object obj) { - return PS.get().IMP.wrapPlayer(obj); - } - - /** - * Get the cached PlotPlayer from a username
- * - This will return null if the player has not finished logging in or is not online - * @param name - * @return - */ - public static PlotPlayer get(final String name) { - return UUIDHandler.getPlayer(name); - } - - /** - * Set some session only metadata for the player - * @param key - * @param value - */ - public void setMeta(final String key, final Object value) { - if (meta == null) { - meta = new ConcurrentHashMap<>(); - } - meta.put(key, value); - } - - /** - * Get the metadata for a key - * @param - * @param key - * @return - */ - public T getMeta(final String key) { - if (meta != null) { - return (T) meta.get(key); - } - return null; - } - - public T getMeta(final String key, T def) { - if (meta != null) { - T value = (T) meta.get(key); - return value == null ? def : value; - } - return def; - } - - /** - * Delete the metadata for a key
- * - metadata is session only - * - deleting other plugin's metadata may cause issues - * @param key - */ - public Object deleteMeta(final String key) { - return meta == null ? null : meta.remove(key); - } - - /** - * Returns the player's name - * @see #getName() - */ - @Override - public String toString() { - return getName(); - } - - /** - * Get the player's current plot
- * - This will return null if the player is standing in the road, or not in a plot world/area - * - An unowned plot is still a plot, it just doesn't have any settings - * @return - */ - public Plot getCurrentPlot() { - return (Plot) getMeta("lastplot"); - } - - /** - * Get the total number of allowed plots - * Possibly relevant: (To increment the player's allowed plots, see the example script on the wiki) - * @return number of allowed plots within the scope (globally, or in the player's current world as defined in the settings.yml) - */ - public int getAllowedPlots() { - return Permissions.hasPermissionRange(this, "plots.plot", Settings.MAX_PLOTS); - } - - /** - * Get the number of plots the player owns - * - * @see #getPlotCount(String); - * @see #getPlots() - * - * @return number of plots within the scope (globally, or in the player's current world as defined in the settings.yml) - */ - public int getPlotCount() { - if (!Settings.GLOBAL_LIMIT) { - return getPlotCount(getLocation().getWorld()); - } - final AtomicInteger count = new AtomicInteger(0); - final UUID uuid = getUUID(); - PS.get().foreachPlotArea(new RunnableVal() { - @Override - public void run(PlotArea value) { - if (!Settings.DONE_COUNTS_TOWARDS_LIMIT) { - for (Plot plot : value.getPlotsAbs(uuid)) { - if (!plot.getFlags().containsKey("done")) { - count.incrementAndGet(); - } - } - } else { - count.addAndGet(value.getPlotsAbs(uuid).size()); - } - } - }); - return count.get(); - } - - /** - * Get the number of plots the player owns in the world - * @param world - * @return - */ - public int getPlotCount(final String world) { - final UUID uuid = getUUID(); - int count = 0; - for (PlotArea area : PS.get().getPlotAreas(world)) { - if (!Settings.DONE_COUNTS_TOWARDS_LIMIT) { - for (Plot plot : area.getPlotsAbs(uuid)) { - if (!plot.getFlags().containsKey("done")) { - count++; - } - } - } else { - count += area.getPlotsAbs(uuid).size(); - } - } - return count; - } - - /** - * Get the plots the player owns - * @see PS for more searching functions - * @see #getPlotCount() for the number of plots - * @return Set of plots - */ - public Set getPlots() { - return PS.get().getPlots(this); - } - - /** - * Return the PlotArea the player is currently in, or null - * @return - */ - public PlotArea getPlotAreaAbs() { - return PS.get().getPlotAreaAbs(getLocation()); - } - - public PlotArea getApplicablePlotArea() { - return PS.get().getApplicablePlotArea(getLocation()); - } - - @Override - public RequiredType getSuperCaller() { - return RequiredType.PLAYER; - } - - /////////////// PLAYER META /////////////// - - ////////////// PARTIALLY IMPLEMENTED /////////// - /** - * Get the player's last recorded location or null if they don't any plot relevant location - * @return The location - */ - public Location getLocation() { - final Location loc = getMeta("location"); - if (loc != null) { - return loc; - } - return null; - } - - //////////////////////////////////////////////// - - /** - * Get the previous time the player logged in - * @return - */ - public abstract long getPreviousLogin(); - - /** - * Get the player's full location (including yaw/pitch) - * @return - */ - public abstract Location getLocationFull(); - - /** - * Get the player's UUID
- * === !IMPORTANT ===
- * The UUID is dependent on the mode chosen in the settings.yml and may not be the same as Bukkit has - * (especially if using an old version of Bukkit that does not support UUIDs) - * - * @return UUID - */ - public abstract UUID getUUID(); - - /** - * Check the player's permissions
- * - Will be cached if permission caching is enabled - */ - @Override - public abstract boolean hasPermission(final String perm); - - /** - * Send the player a message - */ - @Override - public abstract void sendMessage(final String message); - - /** - * Teleport the player to a location - * @param loc - */ - public abstract void teleport(final Location loc); - - /** - * Is the player online - * @return - */ - public abstract boolean isOnline(); - - /** - * Get the player's name - * @return - */ - public abstract String getName(); - - /** - * Set the compass target - * @param loc - */ - public abstract void setCompassTarget(final Location loc); - - /** - * Load the player data from disk (if applicable) - * @deprecated hacky - */ - @Deprecated - public abstract void loadData(); - - /** - * Save the player data from disk (if applicable) - * @deprecated hacky - */ - @Deprecated - public abstract void saveData(); - - /** - * Set player data that will persist restarts - * - Please note that this is not intended to store large values - * - For session only data use meta - * @param key - */ - public abstract void setAttribute(final String key); - - /** - * The attribute will be either true or false - * @param key - */ - public abstract boolean getAttribute(final String key); - - /** - * Remove an attribute from a player - * @param key - */ - public abstract void removeAttribute(final String key); - - /** - * Set the player's local weather - * @param weather - */ - public abstract void setWeather(final PlotWeather weather); - - /** - * Get the player's gamemode - * @return - */ - public abstract PlotGamemode getGamemode(); - - /** - * Set the player's gamemode - * @param gamemode - */ - public abstract void setGamemode(final PlotGamemode gamemode); - - /** - * Set the player's local time (ticks) - * @param time - */ - public abstract void setTime(final long time); - - /** - * Set the player's fly mode - * @param fly - */ - public abstract void setFlight(final boolean fly); - - /** - * Play music at a location for the player - * @param loc - * @param id - */ - public abstract void playMusic(final Location loc, final int id); - - /** - * Check if the player is banned - * @return - */ - public abstract boolean isBanned(); - - /** - * Kick the player from the game - * @param message - */ - public abstract void kick(final String message); - - /** - * Called when the player quits - */ - public void unregister() { - final Plot plot = getCurrentPlot(); - if (plot != null) { - EventUtil.manager.callLeave(this, plot); - } - if (Settings.DELETE_PLOTS_ON_BAN && isBanned()) { - for (final Plot owned : getPlots()) { - owned.deletePlot(null); - PS.debug(String.format("&cPlot &6%s &cwas deleted + cleared due to &6%s&c getting banned", plot.getId(), getName())); - } - } - String name = getName(); - ExpireManager.dates.put(getUUID(), System.currentTimeMillis()); - CmdConfirm.removePending(name); - UUIDHandler.getPlayers().remove(name); - PS.get().IMP.unregister(this); - } - - public int getPlayerClusterCount(final String world) { - final UUID uuid = getUUID(); - int count = 0; - for (final PlotCluster cluster : PS.get().getClusters(world)) { - if (uuid.equals(cluster.owner)) { - count += cluster.getArea(); - } - } - return count; - } - - public int getPlayerClusterCount() { - final AtomicInteger count = new AtomicInteger(); - PS.get().foreachPlotArea(new RunnableVal() { - @Override - public void run(PlotArea value) { - count.addAndGet(value.getClusters().size()); - } - }); - return count.get(); - } - - public Set getPlots(String world) { - UUID uuid = getUUID(); - HashSet plots = new HashSet<>(); - for (Plot plot : PS.get().getPlots(world)) { - if (plot.isOwner(uuid)) { - plots.add(plot); - } - } - return plots; - } - - public void populatePersistentMetaMap() { - DBFunc.dbManager.getPersistentMeta(getUUID(), new RunnableVal>() { - @Override - public void run(Map value) { - PlotPlayer.this.metaMap = value; - } - }); - } - - public byte[] getPersistentMeta(String key) { - return metaMap.get(key); - } - - public void removePersistentMeta(String key) { - if (metaMap.containsKey(key)) { - metaMap.remove(key); - } - DBFunc.dbManager.removePersistentMeta(getUUID(), key); - } - - public void setPersistentMeta(String key, byte[] value) { - boolean delete = hasPersistentMeta(key); - metaMap.put(key, value); - DBFunc.dbManager.addPersistentMeta(getUUID(), key, value, delete); - } - - public boolean hasPersistentMeta(String key) { - return metaMap.containsKey(key); - } -} +package com.intellectualcrafters.plot.object; + +import com.intellectualcrafters.plot.PS; +import com.intellectualcrafters.plot.commands.RequiredType; +import com.intellectualcrafters.plot.config.Settings; +import com.intellectualcrafters.plot.database.DBFunc; +import com.intellectualcrafters.plot.util.CmdConfirm; +import com.intellectualcrafters.plot.util.EventUtil; +import com.intellectualcrafters.plot.util.ExpireManager; +import com.intellectualcrafters.plot.util.Permissions; +import com.intellectualcrafters.plot.util.PlotGamemode; +import com.intellectualcrafters.plot.util.PlotWeather; +import com.intellectualcrafters.plot.util.UUIDHandler; +import com.plotsquared.general.commands.CommandCaller; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * The PlotPlayer class
+ * - Can cast to: BukkitPlayer / SpongePlayer, which are the current implementations
+ */ +public abstract class PlotPlayer implements CommandCaller { + + private Map metaMap = new HashMap<>(); + + /** + * The metadata map + */ + private ConcurrentHashMap meta; + + /** + * Efficiently wrap a Player, or OfflinePlayer object to get a PlotPlayer (or fetch if it's already cached)
+ * - Accepts sponge/bukkit Player (online) + * - Accepts player name (online) + * - Accepts UUID + * - Accepts bukkit OfflinePlayer (offline) + * @param obj + * @return + */ + public static PlotPlayer wrap(final Object obj) { + return PS.get().IMP.wrapPlayer(obj); + } + + /** + * Get the cached PlotPlayer from a username
+ * - This will return null if the player has not finished logging in or is not online + * @param name + * @return + */ + public static PlotPlayer get(final String name) { + return UUIDHandler.getPlayer(name); + } + + /** + * Set some session only metadata for the player + * @param key + * @param value + */ + public void setMeta(final String key, final Object value) { + if (meta == null) { + meta = new ConcurrentHashMap<>(); + } + meta.put(key, value); + } + + /** + * Get the metadata for a key + * @param + * @param key + * @return + */ + public T getMeta(final String key) { + if (meta != null) { + return (T) meta.get(key); + } + return null; + } + + public T getMeta(final String key, T def) { + if (meta != null) { + T value = (T) meta.get(key); + return value == null ? def : value; + } + return def; + } + + /** + * Delete the metadata for a key
+ * - metadata is session only + * - deleting other plugin's metadata may cause issues + * @param key + */ + public Object deleteMeta(final String key) { + return meta == null ? null : meta.remove(key); + } + + /** + * Returns the player's name + * @see #getName() + */ + @Override + public String toString() { + return getName(); + } + + /** + * Get the player's current plot
+ * - This will return null if the player is standing in the road, or not in a plot world/area + * - An unowned plot is still a plot, it just doesn't have any settings + * @return + */ + public Plot getCurrentPlot() { + return (Plot) getMeta("lastplot"); + } + + /** + * Get the total number of allowed plots + * Possibly relevant: (To increment the player's allowed plots, see the example script on the wiki) + * @return number of allowed plots within the scope (globally, or in the player's current world as defined in the settings.yml) + */ + public int getAllowedPlots() { + return Permissions.hasPermissionRange(this, "plots.plot", Settings.MAX_PLOTS); + } + + /** + * Get the number of plots the player owns + * + * @see #getPlotCount(String); + * @see #getPlots() + * + * @return number of plots within the scope (globally, or in the player's current world as defined in the settings.yml) + */ + public int getPlotCount() { + if (!Settings.GLOBAL_LIMIT) { + return getPlotCount(getLocation().getWorld()); + } + final AtomicInteger count = new AtomicInteger(0); + final UUID uuid = getUUID(); + PS.get().foreachPlotArea(new RunnableVal() { + @Override + public void run(PlotArea value) { + if (!Settings.DONE_COUNTS_TOWARDS_LIMIT) { + for (Plot plot : value.getPlotsAbs(uuid)) { + if (!plot.getFlags().containsKey("done")) { + count.incrementAndGet(); + } + } + } else { + count.addAndGet(value.getPlotsAbs(uuid).size()); + } + } + }); + return count.get(); + } + + /** + * Get the number of plots the player owns in the world + * @param world + * @return + */ + public int getPlotCount(final String world) { + final UUID uuid = getUUID(); + int count = 0; + for (PlotArea area : PS.get().getPlotAreas(world)) { + if (!Settings.DONE_COUNTS_TOWARDS_LIMIT) { + for (Plot plot : area.getPlotsAbs(uuid)) { + if (!plot.getFlags().containsKey("done")) { + count++; + } + } + } else { + count += area.getPlotsAbs(uuid).size(); + } + } + return count; + } + + /** + * Get the plots the player owns + * @see PS for more searching functions + * @see #getPlotCount() for the number of plots + * @return Set of plots + */ + public Set getPlots() { + return PS.get().getPlots(this); + } + + /** + * Return the PlotArea the player is currently in, or null + * @return + */ + public PlotArea getPlotAreaAbs() { + return PS.get().getPlotAreaAbs(getLocation()); + } + + public PlotArea getApplicablePlotArea() { + return PS.get().getApplicablePlotArea(getLocation()); + } + + @Override + public RequiredType getSuperCaller() { + return RequiredType.PLAYER; + } + + /////////////// PLAYER META /////////////// + + ////////////// PARTIALLY IMPLEMENTED /////////// + /** + * Get the player's last recorded location or null if they don't any plot relevant location + * @return The location + */ + public Location getLocation() { + final Location loc = getMeta("location"); + if (loc != null) { + return loc; + } + return null; + } + + //////////////////////////////////////////////// + + /** + * Get the previous time the player logged in + * @return + */ + public abstract long getPreviousLogin(); + + /** + * Get the player's full location (including yaw/pitch) + * @return + */ + public abstract Location getLocationFull(); + + /** + * Get the player's UUID
+ * === !IMPORTANT ===
+ * The UUID is dependent on the mode chosen in the settings.yml and may not be the same as Bukkit has + * (especially if using an old version of Bukkit that does not support UUIDs) + * + * @return UUID + */ + public abstract UUID getUUID(); + + /** + * Check the player's permissions
+ * - Will be cached if permission caching is enabled + */ + @Override + public abstract boolean hasPermission(final String perm); + + /** + * Send the player a message + */ + @Override + public abstract void sendMessage(final String message); + + /** + * Teleport the player to a location + * @param loc + */ + public abstract void teleport(final Location loc); + + /** + * Is the player online + * @return + */ + public abstract boolean isOnline(); + + /** + * Get the player's name + * @return + */ + public abstract String getName(); + + /** + * Set the compass target + * @param loc + */ + public abstract void setCompassTarget(final Location loc); + + /** + * Load the player data from disk (if applicable) + * @deprecated hacky + */ + @Deprecated + public abstract void loadData(); + + /** + * Save the player data from disk (if applicable) + * @deprecated hacky + */ + @Deprecated + public abstract void saveData(); + + /** + * Set player data that will persist restarts + * - Please note that this is not intended to store large values + * - For session only data use meta + * @param key + */ + public abstract void setAttribute(final String key); + + /** + * The attribute will be either true or false + * @param key + */ + public abstract boolean getAttribute(final String key); + + /** + * Remove an attribute from a player + * @param key + */ + public abstract void removeAttribute(final String key); + + /** + * Set the player's local weather + * @param weather + */ + public abstract void setWeather(final PlotWeather weather); + + /** + * Get the player's gamemode + * @return + */ + public abstract PlotGamemode getGamemode(); + + /** + * Set the player's gamemode + * @param gamemode + */ + public abstract void setGamemode(final PlotGamemode gamemode); + + /** + * Set the player's local time (ticks) + * @param time + */ + public abstract void setTime(final long time); + + /** + * Set the player's fly mode + * @param fly + */ + public abstract void setFlight(final boolean fly); + + /** + * Play music at a location for the player + * @param loc + * @param id + */ + public abstract void playMusic(final Location loc, final int id); + + /** + * Check if the player is banned + * @return + */ + public abstract boolean isBanned(); + + /** + * Kick the player from the game + * @param message + */ + public abstract void kick(final String message); + + /** + * Called when the player quits + */ + public void unregister() { + final Plot plot = getCurrentPlot(); + if (plot != null) { + EventUtil.manager.callLeave(this, plot); + } + if (Settings.DELETE_PLOTS_ON_BAN && isBanned()) { + for (final Plot owned : getPlots()) { + owned.deletePlot(null); + PS.debug(String.format("&cPlot &6%s &cwas deleted + cleared due to &6%s&c getting banned", plot.getId(), getName())); + } + } + String name = getName(); + ExpireManager.dates.put(getUUID(), System.currentTimeMillis()); + CmdConfirm.removePending(name); + UUIDHandler.getPlayers().remove(name); + PS.get().IMP.unregister(this); + } + + public int getPlayerClusterCount(final String world) { + final UUID uuid = getUUID(); + int count = 0; + for (final PlotCluster cluster : PS.get().getClusters(world)) { + if (uuid.equals(cluster.owner)) { + count += cluster.getArea(); + } + } + return count; + } + + public int getPlayerClusterCount() { + final AtomicInteger count = new AtomicInteger(); + PS.get().foreachPlotArea(new RunnableVal() { + @Override + public void run(PlotArea value) { + count.addAndGet(value.getClusters().size()); + } + }); + return count.get(); + } + + public Set getPlots(String world) { + UUID uuid = getUUID(); + HashSet plots = new HashSet<>(); + for (Plot plot : PS.get().getPlots(world)) { + if (plot.isOwner(uuid)) { + plots.add(plot); + } + } + return plots; + } + + public void populatePersistentMetaMap() { + DBFunc.dbManager.getPersistentMeta(getUUID(), new RunnableVal>() { + @Override + public void run(Map value) { + PlotPlayer.this.metaMap = value; + } + }); + } + + public byte[] getPersistentMeta(String key) { + return metaMap.get(key); + } + + public void removePersistentMeta(String key) { + if (metaMap.containsKey(key)) { + metaMap.remove(key); + } + DBFunc.dbManager.removePersistentMeta(getUUID(), key); + } + + public void setPersistentMeta(String key, byte[] value) { + boolean delete = hasPersistentMeta(key); + metaMap.put(key, value); + DBFunc.dbManager.addPersistentMeta(getUUID(), key, value, delete); + } + + public boolean hasPersistentMeta(String key) { + return metaMap.containsKey(key); + } +} diff --git a/src/main/java/com/intellectualcrafters/plot/object/PlotSettings.java b/Core/src/main/java/com/intellectualcrafters/plot/object/PlotSettings.java similarity index 96% rename from src/main/java/com/intellectualcrafters/plot/object/PlotSettings.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/PlotSettings.java index 5511927ea..eaadc3b6d 100644 --- a/src/main/java/com/intellectualcrafters/plot/object/PlotSettings.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/object/PlotSettings.java @@ -1,207 +1,207 @@ -//////////////////////////////////////////////////////////////////////////////////////////////////// -// PlotSquared - A plot manager and world generator for the Bukkit API / -// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / -// / -// This program is free software; you can redistribute it and/or modify / -// it under the terms of the GNU General Public License as published by / -// the Free Software Foundation; either version 3 of the License, or / -// (at your option) any later version. / -// / -// This program is distributed in the hope that it will be useful, / -// but WITHOUT ANY WARRANTY; without even the implied warranty of / -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / -// GNU General Public License for more details. / -// / -// You should have received a copy of the GNU General Public License / -// along with this program; if not, write to the Free Software Foundation, / -// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / -// / -// You can contact us via: support@intellectualsites.com / -//////////////////////////////////////////////////////////////////////////////////////////////////// -package com.intellectualcrafters.plot.object; - -import com.intellectualcrafters.plot.flag.Flag; -import com.intellectualcrafters.plot.flag.FlagManager; -import com.intellectualcrafters.plot.object.comment.PlotComment; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -/** - * Generic settings class - * - Does not keep a reference to a parent class - * - Direct changes here will not occur in the db (Use the parent plot object for that) - */ -public class PlotSettings { - /** - * merged plots - * @deprecated Raw access - */ - @Deprecated - public boolean[] merged = new boolean[] { false, false, false, false }; - /** - * plot alias - * @deprecated Raw access - */ - @Deprecated - public String alias = ""; - /** - * Comments - * @deprecated Raw access - */ - @Deprecated - public List comments = null; - - /** - * The ratings for a plot - * @deprecated Raw access - */ - @Deprecated - public HashMap ratings; - - /** - * Flags - * @deprecated Raw access - */ - @Deprecated - public HashMap flags; - /** - * Home Position - * @deprecated Raw access - */ - @Deprecated - private BlockLoc position; - - /** - * Constructor - * - */ - public PlotSettings() { - flags = new HashMap<>(); - } - - /** - * Check if the plot is merged in a direction
0 = North
1 = East
2 = South
3 = West
- * - * @param direction Direction to check - * - * @return boolean merged - */ - public boolean getMerged(final int direction) { - return merged[direction]; - } - - /** - * Returns true if the plot is merged (i.e. if it's a mega plot) - */ - public boolean isMerged() { - return merged[0] || merged[1] || merged[2] || merged[3]; - } - - public boolean[] getMerged() { - return merged; - } - - public void setMerged(final boolean[] merged) { - this.merged = merged; - } - - public Map getRatings() { - return ratings == null ? new HashMap() : ratings; - } - - public boolean setMerged(final int direction, final boolean merged) { - if (this.merged[direction] != merged) { - this.merged[direction] = merged; - return true; - } - return false; - } - - public BlockLoc getPosition() { - if (position == null) { - return new BlockLoc(0, 0, 0); - } - return position; - } - - public void setPosition(BlockLoc position) { - if (position != null && position.x == 0 && position.y == 0 && position.z == 0) { - position = null; - } - this.position = position; - } - - public String getAlias() { - return alias; - } - - /** - * Set the plot alias - * - * @param alias alias to be used - */ - public void setAlias(final String alias) { - this.alias = alias; - } - - public String getJoinMessage(PlotArea area) { - final Flag greeting = FlagManager.getSettingFlag(area, this, "greeting"); - if (greeting != null) { - return greeting.getValueString(); - } - return ""; - } - - /** - * Get the "farewell" flag value - * - * @return Farewell flag - */ - public String getLeaveMessage(PlotArea area) { - final Flag farewell = FlagManager.getSettingFlag(area, this, "farewell"); - if (farewell != null) { - return farewell.getValueString(); - } - return ""; - } - - public ArrayList getComments(final String inbox) { - final ArrayList c = new ArrayList<>(); - if (comments == null) { - return null; - } - for (final PlotComment comment : comments) { - if (comment.inbox.equals(inbox)) { - c.add(comment); - } - } - return c; - } - - public void setComments(final List comments) { - this.comments = comments; - } - - public void removeComment(final PlotComment comment) { - if (comments.contains(comment)) { - comments.remove(comment); - } - } - - public void removeComments(final List comments) { - for (final PlotComment comment : comments) { - removeComment(comment); - } - } - - public void addComment(final PlotComment comment) { - if (comments == null) { - comments = new ArrayList<>(); - } - comments.add(comment); - } -} +//////////////////////////////////////////////////////////////////////////////////////////////////// +// PlotSquared - A plot manager and world generator for the Bukkit API / +// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / +// / +// This program is free software; you can redistribute it and/or modify / +// it under the terms of the GNU General Public License as published by / +// the Free Software Foundation; either version 3 of the License, or / +// (at your option) any later version. / +// / +// This program is distributed in the hope that it will be useful, / +// but WITHOUT ANY WARRANTY; without even the implied warranty of / +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / +// GNU General Public License for more details. / +// / +// You should have received a copy of the GNU General Public License / +// along with this program; if not, write to the Free Software Foundation, / +// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / +// / +// You can contact us via: support@intellectualsites.com / +//////////////////////////////////////////////////////////////////////////////////////////////////// +package com.intellectualcrafters.plot.object; + +import com.intellectualcrafters.plot.flag.Flag; +import com.intellectualcrafters.plot.flag.FlagManager; +import com.intellectualcrafters.plot.object.comment.PlotComment; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** + * Generic settings class + * - Does not keep a reference to a parent class + * - Direct changes here will not occur in the db (Use the parent plot object for that) + */ +public class PlotSettings { + /** + * merged plots + * @deprecated Raw access + */ + @Deprecated + public boolean[] merged = new boolean[] { false, false, false, false }; + /** + * plot alias + * @deprecated Raw access + */ + @Deprecated + public String alias = ""; + /** + * Comments + * @deprecated Raw access + */ + @Deprecated + public List comments = null; + + /** + * The ratings for a plot + * @deprecated Raw access + */ + @Deprecated + public HashMap ratings; + + /** + * Flags + * @deprecated Raw access + */ + @Deprecated + public HashMap flags; + /** + * Home Position + * @deprecated Raw access + */ + @Deprecated + private BlockLoc position; + + /** + * Constructor + * + */ + public PlotSettings() { + flags = new HashMap<>(); + } + + /** + * Check if the plot is merged in a direction
0 = North
1 = East
2 = South
3 = West
+ * + * @param direction Direction to check + * + * @return boolean merged + */ + public boolean getMerged(final int direction) { + return merged[direction]; + } + + /** + * Returns true if the plot is merged (i.e. if it's a mega plot) + */ + public boolean isMerged() { + return merged[0] || merged[1] || merged[2] || merged[3]; + } + + public boolean[] getMerged() { + return merged; + } + + public void setMerged(final boolean[] merged) { + this.merged = merged; + } + + public Map getRatings() { + return ratings == null ? new HashMap() : ratings; + } + + public boolean setMerged(final int direction, final boolean merged) { + if (this.merged[direction] != merged) { + this.merged[direction] = merged; + return true; + } + return false; + } + + public BlockLoc getPosition() { + if (position == null) { + return new BlockLoc(0, 0, 0); + } + return position; + } + + public void setPosition(BlockLoc position) { + if (position != null && position.x == 0 && position.y == 0 && position.z == 0) { + position = null; + } + this.position = position; + } + + public String getAlias() { + return alias; + } + + /** + * Set the plot alias + * + * @param alias alias to be used + */ + public void setAlias(final String alias) { + this.alias = alias; + } + + public String getJoinMessage(PlotArea area) { + final Flag greeting = FlagManager.getSettingFlag(area, this, "greeting"); + if (greeting != null) { + return greeting.getValueString(); + } + return ""; + } + + /** + * Get the "farewell" flag value + * + * @return Farewell flag + */ + public String getLeaveMessage(PlotArea area) { + final Flag farewell = FlagManager.getSettingFlag(area, this, "farewell"); + if (farewell != null) { + return farewell.getValueString(); + } + return ""; + } + + public ArrayList getComments(final String inbox) { + final ArrayList c = new ArrayList<>(); + if (comments == null) { + return null; + } + for (final PlotComment comment : comments) { + if (comment.inbox.equals(inbox)) { + c.add(comment); + } + } + return c; + } + + public void setComments(final List comments) { + this.comments = comments; + } + + public void removeComment(final PlotComment comment) { + if (comments.contains(comment)) { + comments.remove(comment); + } + } + + public void removeComments(final List comments) { + for (final PlotComment comment : comments) { + removeComment(comment); + } + } + + public void addComment(final PlotComment comment) { + if (comments == null) { + comments = new ArrayList<>(); + } + comments.add(comment); + } +} diff --git a/src/main/java/com/intellectualcrafters/plot/object/PseudoRandom.java b/Core/src/main/java/com/intellectualcrafters/plot/object/PseudoRandom.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/PseudoRandom.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/PseudoRandom.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/Rating.java b/Core/src/main/java/com/intellectualcrafters/plot/object/Rating.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/Rating.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/Rating.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/RegionWrapper.java b/Core/src/main/java/com/intellectualcrafters/plot/object/RegionWrapper.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/RegionWrapper.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/RegionWrapper.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/RunnableVal.java b/Core/src/main/java/com/intellectualcrafters/plot/object/RunnableVal.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/RunnableVal.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/RunnableVal.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/RunnableVal2.java b/Core/src/main/java/com/intellectualcrafters/plot/object/RunnableVal2.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/RunnableVal2.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/RunnableVal2.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/RunnableVal3.java b/Core/src/main/java/com/intellectualcrafters/plot/object/RunnableVal3.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/RunnableVal3.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/RunnableVal3.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/SetupObject.java b/Core/src/main/java/com/intellectualcrafters/plot/object/SetupObject.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/SetupObject.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/SetupObject.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/StringWrapper.java b/Core/src/main/java/com/intellectualcrafters/plot/object/StringWrapper.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/StringWrapper.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/StringWrapper.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/comment/CommentInbox.java b/Core/src/main/java/com/intellectualcrafters/plot/object/comment/CommentInbox.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/comment/CommentInbox.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/comment/CommentInbox.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/comment/InboxOwner.java b/Core/src/main/java/com/intellectualcrafters/plot/object/comment/InboxOwner.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/comment/InboxOwner.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/comment/InboxOwner.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/comment/InboxPublic.java b/Core/src/main/java/com/intellectualcrafters/plot/object/comment/InboxPublic.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/comment/InboxPublic.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/comment/InboxPublic.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/comment/InboxReport.java b/Core/src/main/java/com/intellectualcrafters/plot/object/comment/InboxReport.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/comment/InboxReport.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/comment/InboxReport.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/comment/PlotComment.java b/Core/src/main/java/com/intellectualcrafters/plot/object/comment/PlotComment.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/comment/PlotComment.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/comment/PlotComment.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/schematic/ItemType.java b/Core/src/main/java/com/intellectualcrafters/plot/object/schematic/ItemType.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/schematic/ItemType.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/schematic/ItemType.java diff --git a/src/main/java/com/intellectualcrafters/plot/object/schematic/PlotItem.java b/Core/src/main/java/com/intellectualcrafters/plot/object/schematic/PlotItem.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/object/schematic/PlotItem.java rename to Core/src/main/java/com/intellectualcrafters/plot/object/schematic/PlotItem.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/AbstractTitle.java b/Core/src/main/java/com/intellectualcrafters/plot/util/AbstractTitle.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/AbstractTitle.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/AbstractTitle.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/BO3Handler.java b/Core/src/main/java/com/intellectualcrafters/plot/util/BO3Handler.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/BO3Handler.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/BO3Handler.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/ByteArrayUtilities.java b/Core/src/main/java/com/intellectualcrafters/plot/util/ByteArrayUtilities.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/ByteArrayUtilities.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/ByteArrayUtilities.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/ChatManager.java b/Core/src/main/java/com/intellectualcrafters/plot/util/ChatManager.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/ChatManager.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/ChatManager.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/ChunkManager.java b/Core/src/main/java/com/intellectualcrafters/plot/util/ChunkManager.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/ChunkManager.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/ChunkManager.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/CmdConfirm.java b/Core/src/main/java/com/intellectualcrafters/plot/util/CmdConfirm.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/CmdConfirm.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/CmdConfirm.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/CommentManager.java b/Core/src/main/java/com/intellectualcrafters/plot/util/CommentManager.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/CommentManager.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/CommentManager.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/ConsoleColors.java b/Core/src/main/java/com/intellectualcrafters/plot/util/ConsoleColors.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/ConsoleColors.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/ConsoleColors.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/EconHandler.java b/Core/src/main/java/com/intellectualcrafters/plot/util/EconHandler.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/EconHandler.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/EconHandler.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/EventUtil.java b/Core/src/main/java/com/intellectualcrafters/plot/util/EventUtil.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/EventUtil.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/EventUtil.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/ExpireManager.java b/Core/src/main/java/com/intellectualcrafters/plot/util/ExpireManager.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/ExpireManager.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/ExpireManager.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/HastebinUtility.java b/Core/src/main/java/com/intellectualcrafters/plot/util/HastebinUtility.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/HastebinUtility.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/HastebinUtility.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/InventoryUtil.java b/Core/src/main/java/com/intellectualcrafters/plot/util/InventoryUtil.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/InventoryUtil.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/InventoryUtil.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/MainUtil.java b/Core/src/main/java/com/intellectualcrafters/plot/util/MainUtil.java similarity index 97% rename from src/main/java/com/intellectualcrafters/plot/util/MainUtil.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/MainUtil.java index 7f557c730..f93d15d96 100644 --- a/src/main/java/com/intellectualcrafters/plot/util/MainUtil.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/util/MainUtil.java @@ -1,740 +1,740 @@ -//////////////////////////////////////////////////////////////////////////////////////////////////// -// PlotSquared - A plot manager and world generator for the Bukkit API / -// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / -// / -// This program is free software; you can redistribute it and/or modify / -// it under the terms of the GNU General Public License as published by / -// the Free Software Foundation; either version 3 of the License, or / -// (at your option) any later version. / -// / -// This program is distributed in the hope that it will be useful, / -// but WITHOUT ANY WARRANTY; without even the implied warranty of / -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / -// GNU General Public License for more details. / -// / -// You should have received a copy of the GNU General Public License / -// along with this program; if not, write to the Free Software Foundation, / -// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / -// / -// You can contact us via: support@intellectualsites.com / -//////////////////////////////////////////////////////////////////////////////////////////////////// -package com.intellectualcrafters.plot.util; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.UUID; -import java.util.regex.Matcher; - -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.flag.Flag; -import com.intellectualcrafters.plot.flag.FlagManager; -import com.intellectualcrafters.plot.object.ChunkLoc; -import com.intellectualcrafters.plot.object.ConsolePlayer; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotBlock; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.PseudoRandom; -import com.intellectualcrafters.plot.object.RegionWrapper; -import com.intellectualcrafters.plot.object.RunnableVal; - -/** - * plot functions - * - */ -public class MainUtil { - - /** - * - * @deprecated - * @param loc - * @return - */ - @Deprecated - public static PlotId getPlotId(Location loc) { - PlotArea area = loc.getPlotArea(); - return area == null ? null : area.getPlotManager().getPlotId(area, loc.getX(), loc.getY(), loc.getZ()); - } - - /** - * If the NMS code for sending chunk updates is functional
- * - E.g. If using an older version of Bukkit, or before the plugin is updated to 1.5
- * - Slower fallback code will be used if not.
- */ - public static boolean canSendChunk = false; - - /** - * Cache of mapping x,y,z coordinates to the chunk array
- * - Used for efficent world generation
- */ - public static short[][] x_loc; - public static short[][] y_loc; - public static short[][] z_loc; - public static short[][][] CACHE_I = null; - public static short[][][] CACHE_J = null; - - /** - * This cache is used for world generation and just saves a bit of calculation time when checking if something is in the plot area. - */ - public static void initCache() { - if (x_loc == null) { - x_loc = new short[16][4096]; - y_loc = new short[16][4096]; - z_loc = new short[16][4096]; - for (int i = 0; i < 16; i++) { - final int i4 = i << 4; - for (int j = 0; j < 4096; j++) { - final int y = i4 + (j >> 8); - final int a = j - ((y & 0xF) << 8); - final int z1 = a >> 4; - final int x1 = a - (z1 << 4); - x_loc[i][j] = (short) x1; - y_loc[i][j] = (short) y; - z_loc[i][j] = (short) z1; - } - } - } - if (CACHE_I == null) { - CACHE_I = new short[256][16][16]; - CACHE_J = new short[256][16][16]; - for (int x = 0; x < 16; x++) { - for (int z = 0; z < 16; z++) { - for (int y = 0; y < 256; y++) { - final short i = (short) (y >> 4); - final short j = (short) ((y & 0xF) << 8 | z << 4 | x); - CACHE_I[y][x][z] = i; - CACHE_J[y][x][z] = j; - } - } - } - } - } - - /** - * Hashcode of a boolean array.
- * - Used for traversing mega plots quickly. - * @param array - * @return hashcode - */ - public static int hash(boolean[] array) { - if (array.length == 4) { - if (!array[0] && !array[1] && !array[2] && !array[3]) { - return 0; - } - return ((array[0] ? 1 : 0) << 3) + ((array[1] ? 1 : 0) << 2) + ((array[2] ? 1 : 0) << 1) + (array[3] ? 1 : 0); - } - int n = 0; - for (boolean anArray : array) { - n = (n << 1) + (anArray ? 1 : 0); - } - return n; - } - - /** - * Get a list of plot ids within a selection - * @param pos1 - * @param pos2 - * @return - */ - public static ArrayList getPlotSelectionIds(final PlotId pos1, final PlotId pos2) { - final ArrayList myplots = new ArrayList<>(); - for (int x = pos1.x; x <= pos2.x; x++) { - for (int y = pos1.y; y <= pos2.y; y++) { - myplots.add(new PlotId(x, y)); - } - } - return myplots; - } - - /** - * Get the name from a UUID
- * @param owner - * @return The player's name, None, Everyone or Unknown - */ - public static String getName(final UUID owner) { - if (owner == null) { - return C.NONE.s(); - } else if (owner.equals(DBFunc.everyone)) { - return C.EVERYONE.s(); - } - final String name = UUIDHandler.getName(owner); - if (name == null) { - return C.UNKNOWN.s(); - } - return name; - } - - /** - * Get the corner locations for a list of regions
- * @see Plot#getCorners() - * @param world - * @param regions - * @return - */ - public static Location[] getCorners(String world, Collection regions) { - Location min = null; - Location max = null; - for (RegionWrapper region : regions) { - Location[] corners = region.getCorners(world); - if (min == null) { - min = corners[0]; - max = corners[1]; - continue; - } - Location pos1 = corners[0]; - Location pos2 = corners[1]; - if (pos2.getX() > max.getX()) { - max.setX(pos2.getX()); - } - if (pos1.getX() < min.getX()) { - min.setX(pos1.getX()); - } - if (pos2.getZ() > max.getZ()) { - max.setZ(pos2.getZ()); - } - if (pos1.getZ() < min.getZ()) { - min.setZ(pos1.getZ()); - } - } - return new Location[] { min, max }; - } - - /** - * Fuzzy plot search with spaces separating terms
- * - Terms: type, alias, world, owner, trusted, member - * @param search - * @return - */ - public static List getPlotsBySearch(final String search) { - final String[] split = search.split(" "); - final int size = split.length * 2; - - final List uuids = new ArrayList<>(); - PlotId id = null; - PlotArea area = null; - String alias = null; - - for (final String term : split) { - try { - UUID uuid = UUIDHandler.getUUID(term, null); - if (uuid == null) { - uuid = UUID.fromString(term); - } - uuids.add(uuid); - } catch (final Exception e) { - id = PlotId.fromString(term); - if (id != null) { - continue; - } - area = PS.get().getPlotAreaByString(term); - if (area == null) { - alias = term; - } - } - } - - final ArrayList> plotList = new ArrayList<>(size); - for (int i = 0; i < size; i++) { - plotList.add(new ArrayList()); - } - - for (final Plot plot : PS.get().getPlots()) { - int count = 0; - if (!uuids.isEmpty()) { - for (final UUID uuid : uuids) { - if (plot.isOwner(uuid)) { - count += 2; - } else if (plot.isAdded(uuid)) { - count++; - } - } - } - if (id != null) { - if (plot.getId().equals(id)) { - count++; - } - } - if (area != null && plot.getArea().equals(area)) { - count++; - } - if (alias != null && alias.equals(plot.getAlias())) { - count += 2; - } - if (count != 0) { - plotList.get(count - 1).add(plot); - } - } - - final List plots = new ArrayList<>(); - for (int i = plotList.size() - 1; i >= 0; i--) { - if (!plotList.get(i).isEmpty()) { - plots.addAll(plotList.get(i)); - } - } - return plots; - } - - /** - * Get the plot from a string
- * @param player Provides a context for what world to search in. Prefixing the term with 'world_name;' will override this context. - * @param arg The search term - * @param message If a message should be sent to the player if a plot cannot be found - * @return The plot if only 1 result is found, or null - */ - public static Plot getPlotFromString(final PlotPlayer player, final String arg, final boolean message) { - if (arg == null) { - if (player == null) { - if (message) { - MainUtil.sendMessage(player, C.NOT_VALID_PLOT_WORLD); - } - return null; - } - return player.getLocation().getPlotAbs(); - } - PlotArea area; - if (player != null) { - area = player.getApplicablePlotArea(); - } - else { - area = ConsolePlayer.getConsole().getApplicablePlotArea(); - } - final String[] split = arg.split(";|,"); - PlotId id; - if (split.length == 4) { - area = PS.get().getPlotAreaByString(split[0] + ";" + split[1]); - id = PlotId.fromString(split[2] + ";" + split[3]); - } else if (split.length == 3) { - area = PS.get().getPlotAreaByString(split[0]); - id = PlotId.fromString(split[1] + ";" + split[2]); - } else if (split.length == 2) { - id = PlotId.fromString(arg); - } else { - PlotArea tmp = PS.get().getPlotAreaByString(arg); - if (area == null) { - if (message) { - MainUtil.sendMessage(player, C.NOT_VALID_PLOT_WORLD); - } - return null; - } else { - for (final Plot p : area.getPlots()) { - final String name = p.getAlias(); - if (!name.isEmpty() && StringMan.isEqualIgnoreCase(name, arg)) { - return p; - } - } - if (message) { - MainUtil.sendMessage(player, C.NOT_VALID_PLOT_ID); - } - return null; - } - } - if (id == null) { - if (message) { - MainUtil.sendMessage(player, C.NOT_VALID_PLOT_ID); - } - return null; - } - if (area == null) { - if (message) { - MainUtil.sendMessage(player, C.NOT_VALID_PLOT_WORLD); - } - return null; - } - return area.getPlotAbs(id); - } - - /** - * Resend the chunk at a location - * @param world - * @param loc - */ - public static void update(final String world, final ChunkLoc loc) { - SetQueue.IMP.queue.sendChunk(world, Collections.singletonList(loc)); - } - - /** - * Set a cuboid in the world to a set of blocks. - * @param world - * @param pos1 - * @param pos2 - * @param blocks If multiple blocks are provided, the result will be a random mix - */ - public static void setCuboid(final String world, final Location pos1, final Location pos2, final PlotBlock[] blocks) { - if (blocks.length == 1) { - setSimpleCuboid(world, pos1, pos2, blocks[0]); - return; - } - for (int y = pos1.getY(); y <= pos2.getY(); y++) { - for (int x = pos1.getX(); x <= pos2.getX(); x++) { - for (int z = pos1.getZ(); z <= pos2.getZ(); z++) { - final int i = PseudoRandom.random.random(blocks.length); - final PlotBlock block = blocks[i]; - SetQueue.IMP.setBlock(world, x, y, z, block); - } - } - } - while (SetQueue.IMP.forceChunkSet()); - } - - /** - * Set a cubioid asynchronously to a set of blocks - * @param world - * @param pos1 - * @param pos2 - * @param blocks - */ - public static void setCuboidAsync(final String world, final Location pos1, final Location pos2, final PlotBlock[] blocks) { - if (blocks.length == 1) { - setSimpleCuboidAsync(world, pos1, pos2, blocks[0]); - return; - } - for (int y = pos1.getY(); y <= Math.min(255, pos2.getY()); y++) { - for (int x = pos1.getX(); x <= pos2.getX(); x++) { - for (int z = pos1.getZ(); z <= pos2.getZ(); z++) { - final int i = PseudoRandom.random.random(blocks.length); - final PlotBlock block = blocks[i]; - SetQueue.IMP.setBlock(world, x, y, z, block); - } - } - } - } - - /** - * Set a cuboid to a block - * @param world - * @param pos1 - * @param pos2 - * @param newblock - */ - public static void setSimpleCuboid(final String world, final Location pos1, final Location pos2, final PlotBlock newblock) { - for (int y = pos1.getY(); y <= pos2.getY(); y++) { - for (int x = pos1.getX(); x <= pos2.getX(); x++) { - for (int z = pos1.getZ(); z <= pos2.getZ(); z++) { - SetQueue.IMP.setBlock(world, x, y, z, newblock); - } - } - } - while (SetQueue.IMP.forceChunkSet()); - } - - /** - * Set a cuboic asynchronously to a block - * @param world - * @param pos1 - * @param pos2 - * @param newblock - */ - public static void setSimpleCuboidAsync(final String world, final Location pos1, final Location pos2, final PlotBlock newblock) { - for (int y = pos1.getY(); y <= Math.min(255, pos2.getY()); y++) { - for (int x = pos1.getX(); x <= pos2.getX(); x++) { - for (int z = pos1.getZ(); z <= pos2.getZ(); z++) { - SetQueue.IMP.setBlock(world, x, y, z, newblock); - } - } - } - } - - /** - * Synchronously set the biome in a selection - * @param world - * @param p1x - * @param p1z - * @param p2x - * @param p2z - * @param biome - */ - public static void setBiome(final String world, final int p1x, final int p1z, final int p2x, final int p2z, final String biome) { - RegionWrapper region = new RegionWrapper(p1x, p2x, p1z, p2z); - WorldUtil.IMP.setBiomes(world, region, biome); - } - - /** - * Get the heighest block at a location - * @param world - * @param x - * @param z - * @return - */ - public static int getHeighestBlock(final String world, final int x, final int z) { - final int result = WorldUtil.IMP.getHighestBlock(world, x, z); - if (result == 0) { - return 64; - } - return result; - } - - /** - * Send a message to the player - * - * @param plr Player to recieve message - * @param msg Message to send - * - * @return true Can be used in things such as commands (return PlayerFunctions.sendMessage(...)) - */ - public static boolean sendMessage(final PlotPlayer plr, final String msg) { - return sendMessage(plr, msg, true); - } - - /** - * Send a message to console - * @param caption - * @param args - */ - public static void sendConsoleMessage(final C caption, final String... args) { - sendMessage(null, caption, args); - } - - /** - * Send a message to a player - * @param plr Can be null to represent console, or use ConsolePlayer.getConsole() - * @param msg - * @param prefix If the message should be prefixed with the configured prefix - * @return - */ - public static boolean sendMessage(final PlotPlayer plr, final String msg, final boolean prefix) { - if (!msg.isEmpty()) { - if (plr == null) { - ConsolePlayer.getConsole().sendMessage((prefix ? C.PREFIX.s() : "") + msg); - } else { - plr.sendMessage((prefix ? C.PREFIX.s() : "") + C.color(msg)); - } - } - return true; - } - - /** - * Send a message to the player - * - * @param plr Player to receive message - * @param c Caption to send - * - * @return boolean success - */ - public static boolean sendMessage(final PlotPlayer plr, final C c, final String... args) { - return sendMessage(plr, c, (Object[]) args); - } - - /** - * Send a message to the player - * - * @param plr Player to receive message - * @param c Caption to send - * - * @return boolean success - */ - public static boolean sendMessage(final PlotPlayer plr, final C c, final Object... args) { - if (c.s().isEmpty()) { - return true; - } - TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { - String m = C.format(c, args); - if (plr == null) { - ConsolePlayer.getConsole().sendMessage(m); - } else { - plr.sendMessage(m); - } - } - }); - return true; - } - - /** - * Get the average rating for a plot - * @see Plot#getAverageRating() - * @param plot - * @return - */ - public static double getAverageRating(final Plot plot) { - HashMap rating; - if (plot.getSettings().ratings != null) { - rating = plot.getSettings().ratings; - } else if (Settings.CACHE_RATINGS) { - rating = new HashMap<>(); - } else { - rating = DBFunc.getRatings(plot); - } - if (rating == null || rating.isEmpty()) { - return 0; - } - double val = 0; - int size = 0; - for (final Entry entry : rating.entrySet()) { - int current = entry.getValue(); - if (Settings.RATING_CATEGORIES == null || Settings.RATING_CATEGORIES.isEmpty()) { - val += current; - size++; - } else { - for (int i = 0; i < Settings.RATING_CATEGORIES.size(); i++) { - val += current % 10 - 1; - current /= 10; - size++; - } - } - } - return val / size; - } - - /** - * If rating categories are enabled, get the average rating by category.
- * - The index corresponds to the index of the category in the config - * @param plot - * @return - */ - public static double[] getAverageRatings(final Plot plot) { - HashMap rating; - if (plot.getSettings().ratings != null) { - rating = plot.getSettings().ratings; - } else if (Settings.CACHE_RATINGS) { - rating = new HashMap<>(); - } else { - rating = DBFunc.getRatings(plot); - } - int size = 1; - if (Settings.RATING_CATEGORIES != null) { - size = Math.max(1, Settings.RATING_CATEGORIES.size()); - } - final double[] ratings = new double[size]; - if (rating == null || rating.isEmpty()) { - return ratings; - } - for (final Entry entry : rating.entrySet()) { - int current = entry.getValue(); - if (Settings.RATING_CATEGORIES == null || Settings.RATING_CATEGORIES.isEmpty()) { - ratings[0] += current; - } else { - for (int i = 0; i < Settings.RATING_CATEGORIES.size(); i++) { - ratings[i] += current % 10 - 1; - current /= 10; - } - } - } - for (int i = 0; i < size; i++) { - ratings[i] /= rating.size(); - } - return ratings; - } - - /** - * Format a string with plot information:
- * @param info - * @param plot - * @param player - * @param full - * @param whenDone - */ - public static void format(String info, final Plot plot, final PlotPlayer player, final boolean full, final RunnableVal whenDone) { - final int num = plot.getConnectedPlots().size(); - final String alias = !plot.getAlias().isEmpty() ? plot.getAlias() : C.NONE.s(); - final Location bot = plot.getCorners()[0]; - final String biome = WorldUtil.IMP.getBiome(plot.getArea().worldname, bot.getX(), bot.getZ()); - final String trusted = getPlayerList(plot.getTrusted()); - final String members = getPlayerList(plot.getMembers()); - final String denied = getPlayerList(plot.getDenied()); - - final Flag descriptionFlag = FlagManager.getPlotFlagRaw(plot, "description"); - final String description = descriptionFlag == null ? C.NONE.s() : descriptionFlag.getValueString(); - - final String flags; - if (!StringMan.join(FlagManager.getPlotFlags(plot.getArea(), plot.getSettings(), true).values(), "").isEmpty()) { - flags = StringMan.replaceFromMap( - "$2" + StringMan.join(FlagManager.getPlotFlags(plot.getArea(), plot.getSettings(), true).values(), "$1, $2"), C.replacements); - } else { - flags = StringMan.replaceFromMap("$2" + C.NONE.s(), C.replacements); - } - final boolean build = plot.isAdded(player.getUUID()); - - final String owner = plot.owner == null ? "unowned" : getPlayerList(plot.getOwners()); - - info = info.replaceAll("%id%", plot.getId().toString()); - info = info.replaceAll("%alias%", alias); - info = info.replaceAll("%num%", num + ""); - info = info.replaceAll("%desc%", description); - info = info.replaceAll("%biome%", biome); - info = info.replaceAll("%owner%", owner); - info = info.replaceAll("%members%", members); - info = info.replaceAll("%player%", player.getName()); - info = info.replaceAll("%trusted%", trusted); - info = info.replaceAll("%helpers%", members); - info = info.replaceAll("%denied%", denied); - info = info.replaceAll("%flags%", Matcher.quoteReplacement(flags)); - info = info.replaceAll("%build%", build + ""); - info = info.replaceAll("%desc%", "No description set."); - if (info.contains("%rating%")) { - final String newInfo = info; - TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { - int max = 10; - if (Settings.RATING_CATEGORIES != null && !Settings.RATING_CATEGORIES.isEmpty()) { - max = 8; - } - String info; - if (full && Settings.RATING_CATEGORIES != null && Settings.RATING_CATEGORIES.size() > 1) { - String rating = ""; - String prefix = ""; - final double[] ratings = MainUtil.getAverageRatings(plot); - for (int i = 0; i < ratings.length; i++) { - rating += prefix + Settings.RATING_CATEGORIES.get(i) + "=" + String.format("%.1f", ratings[i]); - prefix = ","; - } - info = newInfo.replaceAll("%rating%", rating); - } else { - info = newInfo.replaceAll("%rating%", String.format("%.1f", MainUtil.getAverageRating(plot)) + "/" + max); - } - whenDone.run(info); - } - }); - return; - } - whenDone.run(info); - } - - /** - * Get a list of names given a list of uuids.
- * - Uses the format {@link C#PLOT_USER_LIST} for the returned string - * @param uuids - * @return - */ - public static String getPlayerList(final Collection uuids) { - final ArrayList l = new ArrayList<>(uuids); - if (l.size() < 1) { - return C.NONE.s(); - } - final String c = C.PLOT_USER_LIST.s(); - final StringBuilder list = new StringBuilder(); - for (int x = 0; x < l.size(); x++) { - if (x + 1 == l.size()) { - list.append(c.replace("%user%", getName(l.get(x))).replace(",", "")); - } else { - list.append(c.replace("%user%", getName(l.get(x)))); - } - } - return list.toString(); - } - - public static void getPersistentMeta(final UUID uuid, final String key, final RunnableVal result) { - PlotPlayer pp = UUIDHandler.getPlayer(uuid); - if (pp != null) { - result.run(pp.getPersistentMeta(key)); - } else { - DBFunc.dbManager.getPersistentMeta(uuid, new RunnableVal>() { - @Override - public void run(Map value) { - result.run(value.get(key)); - } - }); - } - } -} +//////////////////////////////////////////////////////////////////////////////////////////////////// +// PlotSquared - A plot manager and world generator for the Bukkit API / +// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / +// / +// This program is free software; you can redistribute it and/or modify / +// it under the terms of the GNU General Public License as published by / +// the Free Software Foundation; either version 3 of the License, or / +// (at your option) any later version. / +// / +// This program is distributed in the hope that it will be useful, / +// but WITHOUT ANY WARRANTY; without even the implied warranty of / +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / +// GNU General Public License for more details. / +// / +// You should have received a copy of the GNU General Public License / +// along with this program; if not, write to the Free Software Foundation, / +// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / +// / +// You can contact us via: support@intellectualsites.com / +//////////////////////////////////////////////////////////////////////////////////////////////////// +package com.intellectualcrafters.plot.util; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.UUID; +import java.util.regex.Matcher; + +import com.intellectualcrafters.plot.PS; +import com.intellectualcrafters.plot.config.C; +import com.intellectualcrafters.plot.config.Settings; +import com.intellectualcrafters.plot.database.DBFunc; +import com.intellectualcrafters.plot.flag.Flag; +import com.intellectualcrafters.plot.flag.FlagManager; +import com.intellectualcrafters.plot.object.ChunkLoc; +import com.intellectualcrafters.plot.object.ConsolePlayer; +import com.intellectualcrafters.plot.object.Location; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotArea; +import com.intellectualcrafters.plot.object.PlotBlock; +import com.intellectualcrafters.plot.object.PlotId; +import com.intellectualcrafters.plot.object.PlotPlayer; +import com.intellectualcrafters.plot.object.PseudoRandom; +import com.intellectualcrafters.plot.object.RegionWrapper; +import com.intellectualcrafters.plot.object.RunnableVal; + +/** + * plot functions + * + */ +public class MainUtil { + + /** + * + * @deprecated + * @param loc + * @return + */ + @Deprecated + public static PlotId getPlotId(Location loc) { + PlotArea area = loc.getPlotArea(); + return area == null ? null : area.getPlotManager().getPlotId(area, loc.getX(), loc.getY(), loc.getZ()); + } + + /** + * If the NMS code for sending chunk updates is functional
+ * - E.g. If using an older version of Bukkit, or before the plugin is updated to 1.5
+ * - Slower fallback code will be used if not.
+ */ + public static boolean canSendChunk = false; + + /** + * Cache of mapping x,y,z coordinates to the chunk array
+ * - Used for efficent world generation
+ */ + public static short[][] x_loc; + public static short[][] y_loc; + public static short[][] z_loc; + public static short[][][] CACHE_I = null; + public static short[][][] CACHE_J = null; + + /** + * This cache is used for world generation and just saves a bit of calculation time when checking if something is in the plot area. + */ + public static void initCache() { + if (x_loc == null) { + x_loc = new short[16][4096]; + y_loc = new short[16][4096]; + z_loc = new short[16][4096]; + for (int i = 0; i < 16; i++) { + final int i4 = i << 4; + for (int j = 0; j < 4096; j++) { + final int y = i4 + (j >> 8); + final int a = j - ((y & 0xF) << 8); + final int z1 = a >> 4; + final int x1 = a - (z1 << 4); + x_loc[i][j] = (short) x1; + y_loc[i][j] = (short) y; + z_loc[i][j] = (short) z1; + } + } + } + if (CACHE_I == null) { + CACHE_I = new short[256][16][16]; + CACHE_J = new short[256][16][16]; + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + for (int y = 0; y < 256; y++) { + final short i = (short) (y >> 4); + final short j = (short) ((y & 0xF) << 8 | z << 4 | x); + CACHE_I[y][x][z] = i; + CACHE_J[y][x][z] = j; + } + } + } + } + } + + /** + * Hashcode of a boolean array.
+ * - Used for traversing mega plots quickly. + * @param array + * @return hashcode + */ + public static int hash(boolean[] array) { + if (array.length == 4) { + if (!array[0] && !array[1] && !array[2] && !array[3]) { + return 0; + } + return ((array[0] ? 1 : 0) << 3) + ((array[1] ? 1 : 0) << 2) + ((array[2] ? 1 : 0) << 1) + (array[3] ? 1 : 0); + } + int n = 0; + for (boolean anArray : array) { + n = (n << 1) + (anArray ? 1 : 0); + } + return n; + } + + /** + * Get a list of plot ids within a selection + * @param pos1 + * @param pos2 + * @return + */ + public static ArrayList getPlotSelectionIds(final PlotId pos1, final PlotId pos2) { + final ArrayList myplots = new ArrayList<>(); + for (int x = pos1.x; x <= pos2.x; x++) { + for (int y = pos1.y; y <= pos2.y; y++) { + myplots.add(new PlotId(x, y)); + } + } + return myplots; + } + + /** + * Get the name from a UUID
+ * @param owner + * @return The player's name, None, Everyone or Unknown + */ + public static String getName(final UUID owner) { + if (owner == null) { + return C.NONE.s(); + } else if (owner.equals(DBFunc.everyone)) { + return C.EVERYONE.s(); + } + final String name = UUIDHandler.getName(owner); + if (name == null) { + return C.UNKNOWN.s(); + } + return name; + } + + /** + * Get the corner locations for a list of regions
+ * @see Plot#getCorners() + * @param world + * @param regions + * @return + */ + public static Location[] getCorners(String world, Collection regions) { + Location min = null; + Location max = null; + for (RegionWrapper region : regions) { + Location[] corners = region.getCorners(world); + if (min == null) { + min = corners[0]; + max = corners[1]; + continue; + } + Location pos1 = corners[0]; + Location pos2 = corners[1]; + if (pos2.getX() > max.getX()) { + max.setX(pos2.getX()); + } + if (pos1.getX() < min.getX()) { + min.setX(pos1.getX()); + } + if (pos2.getZ() > max.getZ()) { + max.setZ(pos2.getZ()); + } + if (pos1.getZ() < min.getZ()) { + min.setZ(pos1.getZ()); + } + } + return new Location[] { min, max }; + } + + /** + * Fuzzy plot search with spaces separating terms
+ * - Terms: type, alias, world, owner, trusted, member + * @param search + * @return + */ + public static List getPlotsBySearch(final String search) { + final String[] split = search.split(" "); + final int size = split.length * 2; + + final List uuids = new ArrayList<>(); + PlotId id = null; + PlotArea area = null; + String alias = null; + + for (final String term : split) { + try { + UUID uuid = UUIDHandler.getUUID(term, null); + if (uuid == null) { + uuid = UUID.fromString(term); + } + uuids.add(uuid); + } catch (final Exception e) { + id = PlotId.fromString(term); + if (id != null) { + continue; + } + area = PS.get().getPlotAreaByString(term); + if (area == null) { + alias = term; + } + } + } + + final ArrayList> plotList = new ArrayList<>(size); + for (int i = 0; i < size; i++) { + plotList.add(new ArrayList()); + } + + for (final Plot plot : PS.get().getPlots()) { + int count = 0; + if (!uuids.isEmpty()) { + for (final UUID uuid : uuids) { + if (plot.isOwner(uuid)) { + count += 2; + } else if (plot.isAdded(uuid)) { + count++; + } + } + } + if (id != null) { + if (plot.getId().equals(id)) { + count++; + } + } + if (area != null && plot.getArea().equals(area)) { + count++; + } + if (alias != null && alias.equals(plot.getAlias())) { + count += 2; + } + if (count != 0) { + plotList.get(count - 1).add(plot); + } + } + + final List plots = new ArrayList<>(); + for (int i = plotList.size() - 1; i >= 0; i--) { + if (!plotList.get(i).isEmpty()) { + plots.addAll(plotList.get(i)); + } + } + return plots; + } + + /** + * Get the plot from a string
+ * @param player Provides a context for what world to search in. Prefixing the term with 'world_name;' will override this context. + * @param arg The search term + * @param message If a message should be sent to the player if a plot cannot be found + * @return The plot if only 1 result is found, or null + */ + public static Plot getPlotFromString(final PlotPlayer player, final String arg, final boolean message) { + if (arg == null) { + if (player == null) { + if (message) { + MainUtil.sendMessage(player, C.NOT_VALID_PLOT_WORLD); + } + return null; + } + return player.getLocation().getPlotAbs(); + } + PlotArea area; + if (player != null) { + area = player.getApplicablePlotArea(); + } + else { + area = ConsolePlayer.getConsole().getApplicablePlotArea(); + } + final String[] split = arg.split(";|,"); + PlotId id; + if (split.length == 4) { + area = PS.get().getPlotAreaByString(split[0] + ";" + split[1]); + id = PlotId.fromString(split[2] + ";" + split[3]); + } else if (split.length == 3) { + area = PS.get().getPlotAreaByString(split[0]); + id = PlotId.fromString(split[1] + ";" + split[2]); + } else if (split.length == 2) { + id = PlotId.fromString(arg); + } else { + PlotArea tmp = PS.get().getPlotAreaByString(arg); + if (area == null) { + if (message) { + MainUtil.sendMessage(player, C.NOT_VALID_PLOT_WORLD); + } + return null; + } else { + for (final Plot p : area.getPlots()) { + final String name = p.getAlias(); + if (!name.isEmpty() && StringMan.isEqualIgnoreCase(name, arg)) { + return p; + } + } + if (message) { + MainUtil.sendMessage(player, C.NOT_VALID_PLOT_ID); + } + return null; + } + } + if (id == null) { + if (message) { + MainUtil.sendMessage(player, C.NOT_VALID_PLOT_ID); + } + return null; + } + if (area == null) { + if (message) { + MainUtil.sendMessage(player, C.NOT_VALID_PLOT_WORLD); + } + return null; + } + return area.getPlotAbs(id); + } + + /** + * Resend the chunk at a location + * @param world + * @param loc + */ + public static void update(final String world, final ChunkLoc loc) { + SetQueue.IMP.queue.sendChunk(world, Collections.singletonList(loc)); + } + + /** + * Set a cuboid in the world to a set of blocks. + * @param world + * @param pos1 + * @param pos2 + * @param blocks If multiple blocks are provided, the result will be a random mix + */ + public static void setCuboid(final String world, final Location pos1, final Location pos2, final PlotBlock[] blocks) { + if (blocks.length == 1) { + setSimpleCuboid(world, pos1, pos2, blocks[0]); + return; + } + for (int y = pos1.getY(); y <= pos2.getY(); y++) { + for (int x = pos1.getX(); x <= pos2.getX(); x++) { + for (int z = pos1.getZ(); z <= pos2.getZ(); z++) { + final int i = PseudoRandom.random.random(blocks.length); + final PlotBlock block = blocks[i]; + SetQueue.IMP.setBlock(world, x, y, z, block); + } + } + } + while (SetQueue.IMP.forceChunkSet()); + } + + /** + * Set a cubioid asynchronously to a set of blocks + * @param world + * @param pos1 + * @param pos2 + * @param blocks + */ + public static void setCuboidAsync(final String world, final Location pos1, final Location pos2, final PlotBlock[] blocks) { + if (blocks.length == 1) { + setSimpleCuboidAsync(world, pos1, pos2, blocks[0]); + return; + } + for (int y = pos1.getY(); y <= Math.min(255, pos2.getY()); y++) { + for (int x = pos1.getX(); x <= pos2.getX(); x++) { + for (int z = pos1.getZ(); z <= pos2.getZ(); z++) { + final int i = PseudoRandom.random.random(blocks.length); + final PlotBlock block = blocks[i]; + SetQueue.IMP.setBlock(world, x, y, z, block); + } + } + } + } + + /** + * Set a cuboid to a block + * @param world + * @param pos1 + * @param pos2 + * @param newblock + */ + public static void setSimpleCuboid(final String world, final Location pos1, final Location pos2, final PlotBlock newblock) { + for (int y = pos1.getY(); y <= pos2.getY(); y++) { + for (int x = pos1.getX(); x <= pos2.getX(); x++) { + for (int z = pos1.getZ(); z <= pos2.getZ(); z++) { + SetQueue.IMP.setBlock(world, x, y, z, newblock); + } + } + } + while (SetQueue.IMP.forceChunkSet()); + } + + /** + * Set a cuboic asynchronously to a block + * @param world + * @param pos1 + * @param pos2 + * @param newblock + */ + public static void setSimpleCuboidAsync(final String world, final Location pos1, final Location pos2, final PlotBlock newblock) { + for (int y = pos1.getY(); y <= Math.min(255, pos2.getY()); y++) { + for (int x = pos1.getX(); x <= pos2.getX(); x++) { + for (int z = pos1.getZ(); z <= pos2.getZ(); z++) { + SetQueue.IMP.setBlock(world, x, y, z, newblock); + } + } + } + } + + /** + * Synchronously set the biome in a selection + * @param world + * @param p1x + * @param p1z + * @param p2x + * @param p2z + * @param biome + */ + public static void setBiome(final String world, final int p1x, final int p1z, final int p2x, final int p2z, final String biome) { + RegionWrapper region = new RegionWrapper(p1x, p2x, p1z, p2z); + WorldUtil.IMP.setBiomes(world, region, biome); + } + + /** + * Get the heighest block at a location + * @param world + * @param x + * @param z + * @return + */ + public static int getHeighestBlock(final String world, final int x, final int z) { + final int result = WorldUtil.IMP.getHighestBlock(world, x, z); + if (result == 0) { + return 64; + } + return result; + } + + /** + * Send a message to the player + * + * @param plr Player to recieve message + * @param msg Message to send + * + * @return true Can be used in things such as commands (return PlayerFunctions.sendMessage(...)) + */ + public static boolean sendMessage(final PlotPlayer plr, final String msg) { + return sendMessage(plr, msg, true); + } + + /** + * Send a message to console + * @param caption + * @param args + */ + public static void sendConsoleMessage(final C caption, final String... args) { + sendMessage(null, caption, args); + } + + /** + * Send a message to a player + * @param plr Can be null to represent console, or use ConsolePlayer.getConsole() + * @param msg + * @param prefix If the message should be prefixed with the configured prefix + * @return + */ + public static boolean sendMessage(final PlotPlayer plr, final String msg, final boolean prefix) { + if (!msg.isEmpty()) { + if (plr == null) { + ConsolePlayer.getConsole().sendMessage((prefix ? C.PREFIX.s() : "") + msg); + } else { + plr.sendMessage((prefix ? C.PREFIX.s() : "") + C.color(msg)); + } + } + return true; + } + + /** + * Send a message to the player + * + * @param plr Player to receive message + * @param c Caption to send + * + * @return boolean success + */ + public static boolean sendMessage(final PlotPlayer plr, final C c, final String... args) { + return sendMessage(plr, c, (Object[]) args); + } + + /** + * Send a message to the player + * + * @param plr Player to receive message + * @param c Caption to send + * + * @return boolean success + */ + public static boolean sendMessage(final PlotPlayer plr, final C c, final Object... args) { + if (c.s().isEmpty()) { + return true; + } + TaskManager.runTaskAsync(new Runnable() { + @Override + public void run() { + String m = C.format(c, args); + if (plr == null) { + ConsolePlayer.getConsole().sendMessage(m); + } else { + plr.sendMessage(m); + } + } + }); + return true; + } + + /** + * Get the average rating for a plot + * @see Plot#getAverageRating() + * @param plot + * @return + */ + public static double getAverageRating(final Plot plot) { + HashMap rating; + if (plot.getSettings().ratings != null) { + rating = plot.getSettings().ratings; + } else if (Settings.CACHE_RATINGS) { + rating = new HashMap<>(); + } else { + rating = DBFunc.getRatings(plot); + } + if (rating == null || rating.isEmpty()) { + return 0; + } + double val = 0; + int size = 0; + for (final Entry entry : rating.entrySet()) { + int current = entry.getValue(); + if (Settings.RATING_CATEGORIES == null || Settings.RATING_CATEGORIES.isEmpty()) { + val += current; + size++; + } else { + for (int i = 0; i < Settings.RATING_CATEGORIES.size(); i++) { + val += current % 10 - 1; + current /= 10; + size++; + } + } + } + return val / size; + } + + /** + * If rating categories are enabled, get the average rating by category.
+ * - The index corresponds to the index of the category in the config + * @param plot + * @return + */ + public static double[] getAverageRatings(final Plot plot) { + HashMap rating; + if (plot.getSettings().ratings != null) { + rating = plot.getSettings().ratings; + } else if (Settings.CACHE_RATINGS) { + rating = new HashMap<>(); + } else { + rating = DBFunc.getRatings(plot); + } + int size = 1; + if (Settings.RATING_CATEGORIES != null) { + size = Math.max(1, Settings.RATING_CATEGORIES.size()); + } + final double[] ratings = new double[size]; + if (rating == null || rating.isEmpty()) { + return ratings; + } + for (final Entry entry : rating.entrySet()) { + int current = entry.getValue(); + if (Settings.RATING_CATEGORIES == null || Settings.RATING_CATEGORIES.isEmpty()) { + ratings[0] += current; + } else { + for (int i = 0; i < Settings.RATING_CATEGORIES.size(); i++) { + ratings[i] += current % 10 - 1; + current /= 10; + } + } + } + for (int i = 0; i < size; i++) { + ratings[i] /= rating.size(); + } + return ratings; + } + + /** + * Format a string with plot information:
+ * @param info + * @param plot + * @param player + * @param full + * @param whenDone + */ + public static void format(String info, final Plot plot, final PlotPlayer player, final boolean full, final RunnableVal whenDone) { + final int num = plot.getConnectedPlots().size(); + final String alias = !plot.getAlias().isEmpty() ? plot.getAlias() : C.NONE.s(); + final Location bot = plot.getCorners()[0]; + final String biome = WorldUtil.IMP.getBiome(plot.getArea().worldname, bot.getX(), bot.getZ()); + final String trusted = getPlayerList(plot.getTrusted()); + final String members = getPlayerList(plot.getMembers()); + final String denied = getPlayerList(plot.getDenied()); + + final Flag descriptionFlag = FlagManager.getPlotFlagRaw(plot, "description"); + final String description = descriptionFlag == null ? C.NONE.s() : descriptionFlag.getValueString(); + + final String flags; + if (!StringMan.join(FlagManager.getPlotFlags(plot.getArea(), plot.getSettings(), true).values(), "").isEmpty()) { + flags = StringMan.replaceFromMap( + "$2" + StringMan.join(FlagManager.getPlotFlags(plot.getArea(), plot.getSettings(), true).values(), "$1, $2"), C.replacements); + } else { + flags = StringMan.replaceFromMap("$2" + C.NONE.s(), C.replacements); + } + final boolean build = plot.isAdded(player.getUUID()); + + final String owner = plot.owner == null ? "unowned" : getPlayerList(plot.getOwners()); + + info = info.replaceAll("%id%", plot.getId().toString()); + info = info.replaceAll("%alias%", alias); + info = info.replaceAll("%num%", num + ""); + info = info.replaceAll("%desc%", description); + info = info.replaceAll("%biome%", biome); + info = info.replaceAll("%owner%", owner); + info = info.replaceAll("%members%", members); + info = info.replaceAll("%player%", player.getName()); + info = info.replaceAll("%trusted%", trusted); + info = info.replaceAll("%helpers%", members); + info = info.replaceAll("%denied%", denied); + info = info.replaceAll("%flags%", Matcher.quoteReplacement(flags)); + info = info.replaceAll("%build%", build + ""); + info = info.replaceAll("%desc%", "No description set."); + if (info.contains("%rating%")) { + final String newInfo = info; + TaskManager.runTaskAsync(new Runnable() { + @Override + public void run() { + int max = 10; + if (Settings.RATING_CATEGORIES != null && !Settings.RATING_CATEGORIES.isEmpty()) { + max = 8; + } + String info; + if (full && Settings.RATING_CATEGORIES != null && Settings.RATING_CATEGORIES.size() > 1) { + String rating = ""; + String prefix = ""; + final double[] ratings = MainUtil.getAverageRatings(plot); + for (int i = 0; i < ratings.length; i++) { + rating += prefix + Settings.RATING_CATEGORIES.get(i) + "=" + String.format("%.1f", ratings[i]); + prefix = ","; + } + info = newInfo.replaceAll("%rating%", rating); + } else { + info = newInfo.replaceAll("%rating%", String.format("%.1f", MainUtil.getAverageRating(plot)) + "/" + max); + } + whenDone.run(info); + } + }); + return; + } + whenDone.run(info); + } + + /** + * Get a list of names given a list of uuids.
+ * - Uses the format {@link C#PLOT_USER_LIST} for the returned string + * @param uuids + * @return + */ + public static String getPlayerList(final Collection uuids) { + final ArrayList l = new ArrayList<>(uuids); + if (l.size() < 1) { + return C.NONE.s(); + } + final String c = C.PLOT_USER_LIST.s(); + final StringBuilder list = new StringBuilder(); + for (int x = 0; x < l.size(); x++) { + if (x + 1 == l.size()) { + list.append(c.replace("%user%", getName(l.get(x))).replace(",", "")); + } else { + list.append(c.replace("%user%", getName(l.get(x)))); + } + } + return list.toString(); + } + + public static void getPersistentMeta(final UUID uuid, final String key, final RunnableVal result) { + PlotPlayer pp = UUIDHandler.getPlayer(uuid); + if (pp != null) { + result.run(pp.getPersistentMeta(key)); + } else { + DBFunc.dbManager.getPersistentMeta(uuid, new RunnableVal>() { + @Override + public void run(Map value) { + result.run(value.get(key)); + } + }); + } + } +} diff --git a/src/main/java/com/intellectualcrafters/plot/util/MathMan.java b/Core/src/main/java/com/intellectualcrafters/plot/util/MathMan.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/MathMan.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/MathMan.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/Permissions.java b/Core/src/main/java/com/intellectualcrafters/plot/util/Permissions.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/Permissions.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/Permissions.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/PlotChunk.java b/Core/src/main/java/com/intellectualcrafters/plot/util/PlotChunk.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/PlotChunk.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/PlotChunk.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/PlotGamemode.java b/Core/src/main/java/com/intellectualcrafters/plot/util/PlotGamemode.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/PlotGamemode.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/PlotGamemode.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/PlotQueue.java b/Core/src/main/java/com/intellectualcrafters/plot/util/PlotQueue.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/PlotQueue.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/PlotQueue.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/PlotWeather.java b/Core/src/main/java/com/intellectualcrafters/plot/util/PlotWeather.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/PlotWeather.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/PlotWeather.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/ReflectionUtils.java b/Core/src/main/java/com/intellectualcrafters/plot/util/ReflectionUtils.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/ReflectionUtils.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/ReflectionUtils.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/RegExUtil.java b/Core/src/main/java/com/intellectualcrafters/plot/util/RegExUtil.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/RegExUtil.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/RegExUtil.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/SchematicHandler.java b/Core/src/main/java/com/intellectualcrafters/plot/util/SchematicHandler.java similarity index 97% rename from src/main/java/com/intellectualcrafters/plot/util/SchematicHandler.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/SchematicHandler.java index 70d4e8afc..e85b3c6c5 100644 --- a/src/main/java/com/intellectualcrafters/plot/util/SchematicHandler.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/util/SchematicHandler.java @@ -1,816 +1,816 @@ -package com.intellectualcrafters.plot.util; - -import com.google.common.collect.Lists; -import com.intellectualcrafters.jnbt.ByteArrayTag; -import com.intellectualcrafters.jnbt.CompoundTag; -import com.intellectualcrafters.jnbt.IntTag; -import com.intellectualcrafters.jnbt.ListTag; -import com.intellectualcrafters.jnbt.NBTInputStream; -import com.intellectualcrafters.jnbt.NBTOutputStream; -import com.intellectualcrafters.jnbt.ShortTag; -import com.intellectualcrafters.jnbt.StringTag; -import com.intellectualcrafters.jnbt.Tag; -import com.intellectualcrafters.json.JSONArray; -import com.intellectualcrafters.json.JSONException; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.generator.ClassicPlotWorld; -import com.intellectualcrafters.plot.object.ChunkLoc; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotBlock; -import com.intellectualcrafters.plot.object.RegionWrapper; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.object.schematic.PlotItem; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.Reader; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLConnection; -import java.nio.channels.Channels; -import java.nio.channels.ReadableByteChannel; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; - -public abstract class SchematicHandler { - public static SchematicHandler manager; - - private boolean exportAll = false; - - public boolean exportAll(final Collection collection, final File outputDir, final String namingScheme, final Runnable ifSuccess) { - if (exportAll) { - return false; - } - if (collection.isEmpty()) { - return false; - } - exportAll = true; - final ArrayList plots = new ArrayList(collection); - TaskManager.runTask(new Runnable() { - @Override - public void run() { - if (plots.isEmpty()) { - exportAll = false; - TaskManager.runTask(ifSuccess); - return; - } - final Iterator i = plots.iterator(); - final Plot plot = i.next(); - i.remove(); - String o = UUIDHandler.getName(plot.owner); - if (o == null) { - o = "unknown"; - } - final String name; - if (namingScheme == null) { - name = plot.getId().x + ";" + plot.getId().y + "," + plot.getArea() + "," + o; - } else { - name = namingScheme.replaceAll("%owner%", o).replaceAll("%id%", plot.getId().toString()).replaceAll("%idx%", plot.getId().x + "").replaceAll("%idy%", plot.getId().y + "") - .replaceAll("%world%", plot.getArea().toString()); - } - final String directory; - if (outputDir == null) { - directory = Settings.SCHEMATIC_SAVE_PATH; - } else { - directory = outputDir.getPath(); - } - final Runnable THIS = this; - SchematicHandler.manager.getCompoundTag(plot, new RunnableVal() { - @Override - public void run(final CompoundTag value) { - if (value == null) { - MainUtil.sendMessage(null, "&7 - Skipped plot &c" + plot.getId()); - } else { - TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { - MainUtil.sendMessage(null, "&6ID: " + plot.getId()); - final boolean result = SchematicHandler.manager.save(value, directory + File.separator + name + ".schematic"); - if (!result) { - MainUtil.sendMessage(null, "&7 - Failed to save &c" + plot.getId()); - } else { - MainUtil.sendMessage(null, "&7 - &a success: " + plot.getId()); - } - TaskManager.runTask(new Runnable() { - @Override - public void run() { - THIS.run(); - } - }); - } - }); - } - } - }); - } - }); - return true; - } - - /** - * Paste a schematic - * - * @param schematic the schematic object to paste - * @param plot plot to paste in - * @param x_offset offset x to paste it from plot origin - * @param z_offset offset z to paste it from plot origin - * - * @return boolean true if succeeded - */ - public void paste(final Schematic schematic, final Plot plot, final int x_offset, final int z_offset, final RunnableVal whenDone) { - TaskManager.runTask(new Runnable() { - @Override - public void run() { - if (whenDone != null) { - whenDone.value = false; - } - if (schematic == null) { - PS.debug("Schematic == null :|"); - TaskManager.runTask(whenDone); - return; - } - try { - final Dimension demensions = schematic.getSchematicDimension(); - final int WIDTH = demensions.getX(); - final int LENGTH = demensions.getZ(); - final int HEIGHT = demensions.getY(); - // Validate dimensions - RegionWrapper region = plot.getLargestRegion(); - if ((((region.maxX - region.minX + x_offset) + 1) < WIDTH) || (((region.maxZ - region.minZ + z_offset) + 1) < LENGTH) || (HEIGHT > 256)) { - PS.debug("Schematic is too large"); - PS.debug("(" + WIDTH + "," + LENGTH + "," + HEIGHT + ") is bigger than (" + (region.maxX - region.minX) + "," + (region.maxZ - region.minZ) + ",256)"); - TaskManager.runTask(whenDone); - return; - } - // block type and data arrays - final short[] ids = schematic.ids; - final byte[] datas = schematic.datas; - // Calculate the optimal height to paste the schematic at - final int y_offset; - if (HEIGHT >= 256) { - y_offset = 0; - } else { - PlotArea pw = plot.getArea(); - if (pw instanceof ClassicPlotWorld) { - y_offset = ((ClassicPlotWorld) pw).PLOT_HEIGHT; - } else { - y_offset = MainUtil.getHeighestBlock(plot.getArea().worldname, region.minX + 1, region.minZ + 1); - } - } - final Location pos1 = new Location(plot.getArea().worldname, region.minX + x_offset, y_offset, region.minZ + z_offset); - final Location pos2 = pos1.clone().add(WIDTH - 1, HEIGHT - 1, LENGTH - 1); - // TODO switch to ChunkManager.chunkTask(pos1, pos2, task, whenDone, allocate); - final int p1x = pos1.getX(); - final int p1z = pos1.getZ(); - final int p2x = pos2.getX(); - final int p2z = pos2.getZ(); - final int bcx = p1x >> 4; - final int bcz = p1z >> 4; - final int tcx = p2x >> 4; - final int tcz = p2z >> 4; - final ArrayList chunks = new ArrayList(); - for (int x = bcx; x <= tcx; x++) { - for (int z = bcz; z <= tcz; z++) { - chunks.add(new ChunkLoc(x, z)); - } - } - TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { - int count = 0; - while (!chunks.isEmpty() && count < 256) { - count++; - final ChunkLoc chunk = chunks.remove(0); - final int x = chunk.x; - final int z = chunk.z; - int xxb = x << 4; - int zzb = z << 4; - int xxt = xxb + 15; - int zzt = zzb + 15; - if (x == bcx) { - xxb = p1x; - } - if (x == tcx) { - xxt = p2x; - } - if (z == bcz) { - zzb = p1z; - } - if (z == tcz) { - zzt = p2z; - } - // Paste schematic here - - for (int ry = 0; ry < Math.min(256, HEIGHT); ry++) { - final int yy = y_offset + ry; - if (yy > 255) { - continue; - } - final int i1 = ry * WIDTH * LENGTH; - for (int rz = zzb - p1z; rz <= (zzt - p1z); rz++) { - final int i2 = (rz * WIDTH) + i1; - for (int rx = xxb - p1x; rx <= (xxt - p1x); rx++) { - final int i = i2 + rx; - - final int xx = p1x + rx; - final int zz = p1z + rz; - - int id = ids[i]; - - switch (id) { - case 0: - case 2: - case 4: - case 13: - case 14: - case 15: - case 20: - case 21: - case 22: - case 30: - case 32: - case 37: - case 39: - case 40: - case 41: - case 42: - case 45: - case 46: - case 47: - case 48: - case 49: - case 51: - case 55: - case 56: - case 57: - case 58: - case 60: - case 7: - case 8: - case 9: - case 10: - case 11: - case 73: - case 74: - case 78: - case 79: - case 80: - case 81: - case 82: - case 83: - case 85: - case 87: - case 88: - case 101: - case 102: - case 103: - case 110: - case 112: - case 113: - case 121: - case 122: - case 129: - case 133: - case 165: - case 166: - case 169: - case 170: - case 172: - case 173: - case 174: - case 181: - case 182: - case 188: - case 189: - case 190: - case 191: - case 192: - SetQueue.IMP.setBlock(plot.getArea().worldname, xx, yy, zz, id); - break; - default: - SetQueue.IMP.setBlock(plot.getArea().worldname, xx, yy, zz, new PlotBlock((short) id, datas[i])); - break; - } - } - } - } - } - if (!chunks.isEmpty()) { - final Runnable task = this; - // Run when the queue is free - SetQueue.IMP.addTask(new Runnable() { - @Override - public void run() { - System.gc(); - TaskManager.runTaskLaterAsync(task, 80); - } - }); - } else { - System.gc(); - // Finished - SetQueue.IMP.addTask(new Runnable() { - @Override - public void run() { - pasteStates(schematic, plot, x_offset, z_offset); - if (whenDone != null) { - whenDone.value = true; - whenDone.run(); - } - } - }); - } - } - }); - } catch (final Exception e) { - e.printStackTrace(); - TaskManager.runTask(whenDone); - } - } - }); - } - - public boolean pasteStates(final Schematic schematic, final Plot plot, final int x_offset, final int z_offset) { - if (schematic == null) { - PS.debug("Schematic == null :|"); - return false; - } - final HashSet items = schematic.getItems(); - if (items == null) { - return false; - } - RegionWrapper region = plot.getLargestRegion(); - Location l1 = new Location(plot.getArea().worldname, region.minX + x_offset, 1, region.minZ + z_offset); -// Location l1 = MainUtil.getPlotBottomLoc(plot.world, plot.getId()); - final int sy = MainUtil.getHeighestBlock(plot.getArea().worldname, l1.getX() + 1, l1.getZ() + 1); - final Dimension demensions = schematic.getSchematicDimension(); - final int HEIGHT = demensions.getY(); - if (HEIGHT < 255) { - l1 = l1.add(0, sy - 1, 0); - } - final int X = l1.getX() + x_offset; - final int Y = l1.getY(); - final int Z = l1.getZ() + z_offset; - for (final PlotItem item : items) { - item.x += X; - item.y += Y; - item.z += Z; - WorldUtil.IMP.addItems(plot.getArea().worldname, item); - } - return true; - } - - public Schematic getSchematic(final CompoundTag tag) { - final Map tagMap = tag.getValue(); - // Slow - // byte[] addId = new byte[0]; - // if (tagMap.containsKey("AddBlocks")) { - // addId = ByteArrayTag.class.cast(tagMap.get("AddBlocks")).getValue(); - // } - // end slow - - final short width = ShortTag.class.cast(tagMap.get("Width")).getValue(); - final short length = ShortTag.class.cast(tagMap.get("Length")).getValue(); - final short height = ShortTag.class.cast(tagMap.get("Height")).getValue(); - final byte[] block_sml = ByteArrayTag.class.cast(tagMap.get("Blocks")).getValue(); - final byte[] data = ByteArrayTag.class.cast(tagMap.get("Data")).getValue(); - - final short[] block = new short[block_sml.length]; - for (int i = 0; i < block.length; i++) { - short id = block_sml[i]; - if (id < 0) { - id = (short) (id & 0xFF); - } - block[i] = id; - } - - // Slow + has code for exceptions (addId) inside the loop rather than outside - // for (int index = 0; index < b.length; index++) { - // if ((index >> 1) >= addId.length) { - // blocks[index] = (short) (b[index] & 0xFF); - // } else { - // if ((index & 1) == 0) { - // blocks[index] = (short) (((addId[index >> 1] & 0x0F) << 8) + (b[index] & 0xFF)); - // } else { - // blocks[index] = (short) (((addId[index >> 1] & 0xF0) << 4) + (b[index] & 0xFF)); - // } - // } - // } - // Slow as wrapper for each block - // final DataCollection[] collection = new DataCollection[b.length]; - // for (int x = 0; x < b.length; x++) { - // collection[x] = new DataCollection(blocks[x], d[x]); - // } - // Schematic schem = new Schematic(collection, dimension, file); - - final Dimension dimensions = new Dimension(width, height, length); - final Schematic schem = new Schematic(block, data, dimensions); - - // Slow - try { - final List blockStates = ListTag.class.cast(tagMap.get("TileEntities")).getValue(); - for (final Tag stateTag : blockStates) { - try { - final CompoundTag ct = ((CompoundTag) stateTag); - final Map state = ct.getValue(); - final short x = IntTag.class.cast(state.get("x")).getValue().shortValue(); - final short y = IntTag.class.cast(state.get("y")).getValue().shortValue(); - final short z = IntTag.class.cast(state.get("z")).getValue().shortValue(); - manager.restoreTag(ct, x, y, z, schem); - } catch (final Exception e) { - e.printStackTrace(); - } - } - } catch (final Exception e) { - e.printStackTrace(); - } - return schem; - } - - public abstract void restoreTag(CompoundTag ct, short x, short y, short z, Schematic schem); - - /** - * Get a schematic - * - * @param name to check - * - * @return schematic if found, else null - */ - public Schematic getSchematic(final String name) { - final File parent = new File(PS.get().IMP.getDirectory() + File.separator + "schematics"); - if (!parent.exists()) { - if (!parent.mkdir()) { - throw new RuntimeException("Could not create schematic parent directory"); - } - } - final File file = new File(PS.get().IMP.getDirectory() + File.separator + "schematics" + File.separator + name + (name.endsWith(".schematic") ? "" : ".schematic")); - return getSchematic(file); - } - - /** - * Get a schematic - * - * @param file to check - * - * @return schematic if found, else null - */ - public Schematic getSchematic(final File file) { - if (!file.exists()) { - return null; - } - try { - return getSchematic(new FileInputStream(file)); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - return null; - } - - public Schematic getSchematic(final URL url) { - try { - final ReadableByteChannel rbc = Channels.newChannel(url.openStream()); - final InputStream is = Channels.newInputStream(rbc); - return getSchematic(is); - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } - - public Schematic getSchematic(final InputStream is) { - if (is == null) { - return null; - } - try { - final NBTInputStream stream = new NBTInputStream(new GZIPInputStream(is)); - final CompoundTag tag = (CompoundTag) stream.readTag(1073741824); - is.close(); - stream.close(); - return getSchematic(tag); - } catch (IOException e) { - e.printStackTrace(); - PS.debug(is.toString() + " | " + is.getClass().getCanonicalName() + " is not in GZIP format : " + e.getMessage()); - } - return null; - } - - public List getSaves(final UUID uuid) { - final StringBuilder rawJSON = new StringBuilder(); - try { - final String website = Settings.WEB_URL + "list.php?" + uuid.toString(); - final URL url = new URL(website); - final URLConnection connection = new URL(url.toString()).openConnection(); - connection.setRequestProperty("User-Agent", "Mozilla/5.0"); - final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); - String line; - while ((line = reader.readLine()) != null) { - rawJSON.append(line); - } - reader.close(); - final JSONArray array = new JSONArray(rawJSON.toString()); - final List schematics = new ArrayList<>(); - for (int i = 0; i < array.length(); i++) { - final String schematic = array.getString(i); - schematics.add(schematic); - } - return Lists.reverse(schematics); - } catch (JSONException | IOException e) { - e.printStackTrace(); - PS.debug("ERROR PARSING: " + rawJSON); - } - return null; - } - - public URL upload(final CompoundTag tag, UUID uuid, String file) { - if (tag == null) { - PS.debug("&cCannot save empty tag"); - return null; - } - try { - String website; - if (uuid == null) { - uuid = UUID.randomUUID(); - website = Settings.WEB_URL + "upload.php?" + uuid; - file = "plot"; - } else { - website = Settings.WEB_URL + "save.php?" + uuid; - } - final String boundary = Long.toHexString(System.currentTimeMillis()); - final URLConnection con = new URL(website).openConnection(); - con.setDoOutput(true); - con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); - try (OutputStream output = con.getOutputStream(); - PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8), true)) { - final String CRLF = "\r\n"; - writer.append("--" + boundary).append(CRLF); - writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF); - writer.append("Content-Type: text/plain; charset=" + StandardCharsets.UTF_8.displayName()).append(CRLF); - final String param = "value"; - writer.append(CRLF).append(param).append(CRLF).flush(); - writer.append("--" + boundary).append(CRLF); - writer.append("Content-Disposition: form-data; name=\"schematicFile\"; filename=\"" + file + ".schematic" + "\"").append(CRLF); - writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(file + ".schematic")).append(CRLF); - writer.append("Content-Transfer-Encoding: binary").append(CRLF); - writer.append(CRLF).flush(); - final GZIPOutputStream gzip = new GZIPOutputStream(output); - final NBTOutputStream nos = new NBTOutputStream(gzip); - nos.writeTag(tag); - gzip.finish(); - nos.flush(); - output.flush(); - writer.append(CRLF).flush(); - writer.append("--" + boundary + "--").append(CRLF).flush(); - nos.close(); - } - try (Reader response = new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)) { - final char[] buffer = new char[256]; - final StringBuilder result = new StringBuilder(); - while (true) { - final int r = response.read(buffer); - if (r < 0) { - break; - } - result.append(buffer, 0, r); - } - if (!result.toString().equals("The file plot.schematic has been uploaded.")) { - PS.debug(result); - } - } catch (IOException e) { - e.printStackTrace(); - } - final int responseCode = ((HttpURLConnection) con).getResponseCode(); - if (responseCode != 200) { - return null; - } - return new URL(Settings.WEB_URL + "?key=" + uuid + "&ip=" + Settings.WEB_IP); - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } - - /** - * Saves a schematic to a file path - * - * @param tag to save - * @param path to save in - * - * @return true if succeeded - */ - public boolean save(final CompoundTag tag, final String path) { - if (tag == null) { - PS.debug("&cCannot save empty tag"); - return false; - } - try { - final File tmp = new File(path); - tmp.getParentFile().mkdirs(); - try (OutputStream stream = new FileOutputStream(path); NBTOutputStream output = new NBTOutputStream(new GZIPOutputStream(stream))) { - output.writeTag(tag); - } - } catch (final IOException e) { - e.printStackTrace(); - return false; - } - return true; - } - - /** - * Create a compound tag from blocks - * - Untested - * @param blocks - * @param blockdata - * @param d - * @return - */ - public CompoundTag createTag(final byte[] blocks, final byte[] blockdata, final Dimension d) { - final HashMap schematic = new HashMap<>(); - schematic.put("Width", new ShortTag("Width", (short) d.getX())); - schematic.put("Length", new ShortTag("Length", (short) d.getZ())); - schematic.put("Height", new ShortTag("Height", (short) d.getY())); - schematic.put("Materials", new StringTag("Materials", "Alpha")); - schematic.put("WEOriginX", new IntTag("WEOriginX", 0)); - schematic.put("WEOriginY", new IntTag("WEOriginY", 0)); - schematic.put("WEOriginZ", new IntTag("WEOriginZ", 0)); - schematic.put("WEOffsetX", new IntTag("WEOffsetX", 0)); - schematic.put("WEOffsetY", new IntTag("WEOffsetY", 0)); - schematic.put("WEOffsetZ", new IntTag("WEOffsetZ", 0)); - schematic.put("Blocks", new ByteArrayTag("Blocks", blocks)); - schematic.put("Data", new ByteArrayTag("Data", blockdata)); - schematic.put("Entities", new ListTag("Entities", CompoundTag.class, new ArrayList())); - schematic.put("TileEntities", new ListTag("TileEntities", CompoundTag.class, new ArrayList())); - return new CompoundTag("Schematic", schematic); - } - - public abstract void getCompoundTag(final String world, Set regions, final RunnableVal whenDone); - - public void getCompoundTag(Plot plot, final RunnableVal whenDone) { - getCompoundTag(plot.getArea().worldname, plot.getRegions(), whenDone); - } - - /** - * Schematic Dimensions - * - - */ - public static class Dimension { - - private final int x; - private final int y; - private final int z; - - public Dimension(final int x, final int y, final int z) { - this.x = x; - this.y = y; - this.z = z; - } - - public int getX() { - return x; - } - - public int getY() { - return y; - } - - public int getZ() { - return z; - } - } - - /** - * Schematic Class - * - - */ - public class Schematic { - // Lossy but fast - private final short[] ids; - private final byte[] datas; - - private final Dimension schematicDimension; - private HashSet items; - - public Schematic(final short[] i, final byte[] b, final Dimension d) { - ids = i; - datas = b; - schematicDimension = d; - } - - /** - * Add an item to the schematic - * @param item - */ - public void addItem(final PlotItem item) { - if (items == null) { - items = new HashSet<>(); - } - items.add(item); - } - - /** - * Get any items associated with this schematic - * @return - */ - public HashSet getItems() { - return items; - } - - /** - * Get the schematic dimensions - * @return - */ - public Dimension getSchematicDimension() { - return schematicDimension; - } - - /** - * Get the block type array - * @return - */ - public short[] getIds() { - return ids; - } - - /** - * Get the block data array - * @return - */ - public byte[] getDatas() { - return datas; - } - - public Schematic copySection(RegionWrapper region) { - - int x1 = region.minX; - int x2 = region.maxX; - - int z1 = region.minZ; - int z2 = region.maxZ; - - int y1 = region.minY; - int y2 = Math.min(region.maxY, 255); - - int width = x2 - x1 + 1; - int length = z2 - z1 + 1; - int height = y2 - y1 + 1; - - short[] ids2 = new short[width * length * height]; - byte[] datas2 = new byte[width * length * height]; - - int dx = schematicDimension.getX(); - int dy = schematicDimension.getY(); - int dz = schematicDimension.getZ(); - - for (int y = y1; y <= y2; y++) { - int yy = y >= 0 ? (y < dy ? y : y - dy) : y + dy; - int i1 = yy * dx * dz; - int j1 = (y - y1) * width * length; - for (int z = z1; z <= z2; z++) { - int zz = z >= 0 ? (z < dz ? z : z - dz) : z + dz; - int i2 = i1 + zz * dx; - int j2 = j1 + (z - z1) * width; - for (int x = x1; x <= x2; x++) { - int xx = x >= 0 ? (x < dx ? x : x - dx) : x + dx; - int i3 = i2 + xx; - int j3 = j2 + (x - x1); - ids2[j3] = ids[i3]; - datas2[j3] = datas[i3]; - } - } - } - return new Schematic(ids2, datas2, new Dimension(width, height, length)); - } - - public void save(final File file) { - byte[] ids2 = new byte[ids.length]; - for (int i = 0; i < ids.length; i++) { - ids2[i] = (byte) ids[i]; - } - CompoundTag tag = createTag(ids2, datas, schematicDimension); - SchematicHandler.this.save(tag, file.toString()); - } - } - -} +package com.intellectualcrafters.plot.util; + +import com.google.common.collect.Lists; +import com.intellectualcrafters.jnbt.ByteArrayTag; +import com.intellectualcrafters.jnbt.CompoundTag; +import com.intellectualcrafters.jnbt.IntTag; +import com.intellectualcrafters.jnbt.ListTag; +import com.intellectualcrafters.jnbt.NBTInputStream; +import com.intellectualcrafters.jnbt.NBTOutputStream; +import com.intellectualcrafters.jnbt.ShortTag; +import com.intellectualcrafters.jnbt.StringTag; +import com.intellectualcrafters.jnbt.Tag; +import com.intellectualcrafters.json.JSONArray; +import com.intellectualcrafters.json.JSONException; +import com.intellectualcrafters.plot.PS; +import com.intellectualcrafters.plot.config.Settings; +import com.intellectualcrafters.plot.generator.ClassicPlotWorld; +import com.intellectualcrafters.plot.object.ChunkLoc; +import com.intellectualcrafters.plot.object.Location; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotArea; +import com.intellectualcrafters.plot.object.PlotBlock; +import com.intellectualcrafters.plot.object.RegionWrapper; +import com.intellectualcrafters.plot.object.RunnableVal; +import com.intellectualcrafters.plot.object.schematic.PlotItem; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.io.Reader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLConnection; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; + +public abstract class SchematicHandler { + public static SchematicHandler manager; + + private boolean exportAll = false; + + public boolean exportAll(final Collection collection, final File outputDir, final String namingScheme, final Runnable ifSuccess) { + if (exportAll) { + return false; + } + if (collection.isEmpty()) { + return false; + } + exportAll = true; + final ArrayList plots = new ArrayList(collection); + TaskManager.runTask(new Runnable() { + @Override + public void run() { + if (plots.isEmpty()) { + exportAll = false; + TaskManager.runTask(ifSuccess); + return; + } + final Iterator i = plots.iterator(); + final Plot plot = i.next(); + i.remove(); + String o = UUIDHandler.getName(plot.owner); + if (o == null) { + o = "unknown"; + } + final String name; + if (namingScheme == null) { + name = plot.getId().x + ";" + plot.getId().y + "," + plot.getArea() + "," + o; + } else { + name = namingScheme.replaceAll("%owner%", o).replaceAll("%id%", plot.getId().toString()).replaceAll("%idx%", plot.getId().x + "").replaceAll("%idy%", plot.getId().y + "") + .replaceAll("%world%", plot.getArea().toString()); + } + final String directory; + if (outputDir == null) { + directory = Settings.SCHEMATIC_SAVE_PATH; + } else { + directory = outputDir.getPath(); + } + final Runnable THIS = this; + SchematicHandler.manager.getCompoundTag(plot, new RunnableVal() { + @Override + public void run(final CompoundTag value) { + if (value == null) { + MainUtil.sendMessage(null, "&7 - Skipped plot &c" + plot.getId()); + } else { + TaskManager.runTaskAsync(new Runnable() { + @Override + public void run() { + MainUtil.sendMessage(null, "&6ID: " + plot.getId()); + final boolean result = SchematicHandler.manager.save(value, directory + File.separator + name + ".schematic"); + if (!result) { + MainUtil.sendMessage(null, "&7 - Failed to save &c" + plot.getId()); + } else { + MainUtil.sendMessage(null, "&7 - &a success: " + plot.getId()); + } + TaskManager.runTask(new Runnable() { + @Override + public void run() { + THIS.run(); + } + }); + } + }); + } + } + }); + } + }); + return true; + } + + /** + * Paste a schematic + * + * @param schematic the schematic object to paste + * @param plot plot to paste in + * @param x_offset offset x to paste it from plot origin + * @param z_offset offset z to paste it from plot origin + * + * @return boolean true if succeeded + */ + public void paste(final Schematic schematic, final Plot plot, final int x_offset, final int z_offset, final RunnableVal whenDone) { + TaskManager.runTask(new Runnable() { + @Override + public void run() { + if (whenDone != null) { + whenDone.value = false; + } + if (schematic == null) { + PS.debug("Schematic == null :|"); + TaskManager.runTask(whenDone); + return; + } + try { + final Dimension demensions = schematic.getSchematicDimension(); + final int WIDTH = demensions.getX(); + final int LENGTH = demensions.getZ(); + final int HEIGHT = demensions.getY(); + // Validate dimensions + RegionWrapper region = plot.getLargestRegion(); + if ((((region.maxX - region.minX + x_offset) + 1) < WIDTH) || (((region.maxZ - region.minZ + z_offset) + 1) < LENGTH) || (HEIGHT > 256)) { + PS.debug("Schematic is too large"); + PS.debug("(" + WIDTH + "," + LENGTH + "," + HEIGHT + ") is bigger than (" + (region.maxX - region.minX) + "," + (region.maxZ - region.minZ) + ",256)"); + TaskManager.runTask(whenDone); + return; + } + // block type and data arrays + final short[] ids = schematic.ids; + final byte[] datas = schematic.datas; + // Calculate the optimal height to paste the schematic at + final int y_offset; + if (HEIGHT >= 256) { + y_offset = 0; + } else { + PlotArea pw = plot.getArea(); + if (pw instanceof ClassicPlotWorld) { + y_offset = ((ClassicPlotWorld) pw).PLOT_HEIGHT; + } else { + y_offset = MainUtil.getHeighestBlock(plot.getArea().worldname, region.minX + 1, region.minZ + 1); + } + } + final Location pos1 = new Location(plot.getArea().worldname, region.minX + x_offset, y_offset, region.minZ + z_offset); + final Location pos2 = pos1.clone().add(WIDTH - 1, HEIGHT - 1, LENGTH - 1); + // TODO switch to ChunkManager.chunkTask(pos1, pos2, task, whenDone, allocate); + final int p1x = pos1.getX(); + final int p1z = pos1.getZ(); + final int p2x = pos2.getX(); + final int p2z = pos2.getZ(); + final int bcx = p1x >> 4; + final int bcz = p1z >> 4; + final int tcx = p2x >> 4; + final int tcz = p2z >> 4; + final ArrayList chunks = new ArrayList(); + for (int x = bcx; x <= tcx; x++) { + for (int z = bcz; z <= tcz; z++) { + chunks.add(new ChunkLoc(x, z)); + } + } + TaskManager.runTaskAsync(new Runnable() { + @Override + public void run() { + int count = 0; + while (!chunks.isEmpty() && count < 256) { + count++; + final ChunkLoc chunk = chunks.remove(0); + final int x = chunk.x; + final int z = chunk.z; + int xxb = x << 4; + int zzb = z << 4; + int xxt = xxb + 15; + int zzt = zzb + 15; + if (x == bcx) { + xxb = p1x; + } + if (x == tcx) { + xxt = p2x; + } + if (z == bcz) { + zzb = p1z; + } + if (z == tcz) { + zzt = p2z; + } + // Paste schematic here + + for (int ry = 0; ry < Math.min(256, HEIGHT); ry++) { + final int yy = y_offset + ry; + if (yy > 255) { + continue; + } + final int i1 = ry * WIDTH * LENGTH; + for (int rz = zzb - p1z; rz <= (zzt - p1z); rz++) { + final int i2 = (rz * WIDTH) + i1; + for (int rx = xxb - p1x; rx <= (xxt - p1x); rx++) { + final int i = i2 + rx; + + final int xx = p1x + rx; + final int zz = p1z + rz; + + int id = ids[i]; + + switch (id) { + case 0: + case 2: + case 4: + case 13: + case 14: + case 15: + case 20: + case 21: + case 22: + case 30: + case 32: + case 37: + case 39: + case 40: + case 41: + case 42: + case 45: + case 46: + case 47: + case 48: + case 49: + case 51: + case 55: + case 56: + case 57: + case 58: + case 60: + case 7: + case 8: + case 9: + case 10: + case 11: + case 73: + case 74: + case 78: + case 79: + case 80: + case 81: + case 82: + case 83: + case 85: + case 87: + case 88: + case 101: + case 102: + case 103: + case 110: + case 112: + case 113: + case 121: + case 122: + case 129: + case 133: + case 165: + case 166: + case 169: + case 170: + case 172: + case 173: + case 174: + case 181: + case 182: + case 188: + case 189: + case 190: + case 191: + case 192: + SetQueue.IMP.setBlock(plot.getArea().worldname, xx, yy, zz, id); + break; + default: + SetQueue.IMP.setBlock(plot.getArea().worldname, xx, yy, zz, new PlotBlock((short) id, datas[i])); + break; + } + } + } + } + } + if (!chunks.isEmpty()) { + final Runnable task = this; + // Run when the queue is free + SetQueue.IMP.addTask(new Runnable() { + @Override + public void run() { + System.gc(); + TaskManager.runTaskLaterAsync(task, 80); + } + }); + } else { + System.gc(); + // Finished + SetQueue.IMP.addTask(new Runnable() { + @Override + public void run() { + pasteStates(schematic, plot, x_offset, z_offset); + if (whenDone != null) { + whenDone.value = true; + whenDone.run(); + } + } + }); + } + } + }); + } catch (final Exception e) { + e.printStackTrace(); + TaskManager.runTask(whenDone); + } + } + }); + } + + public boolean pasteStates(final Schematic schematic, final Plot plot, final int x_offset, final int z_offset) { + if (schematic == null) { + PS.debug("Schematic == null :|"); + return false; + } + final HashSet items = schematic.getItems(); + if (items == null) { + return false; + } + RegionWrapper region = plot.getLargestRegion(); + Location l1 = new Location(plot.getArea().worldname, region.minX + x_offset, 1, region.minZ + z_offset); +// Location l1 = MainUtil.getPlotBottomLoc(plot.world, plot.getId()); + final int sy = MainUtil.getHeighestBlock(plot.getArea().worldname, l1.getX() + 1, l1.getZ() + 1); + final Dimension demensions = schematic.getSchematicDimension(); + final int HEIGHT = demensions.getY(); + if (HEIGHT < 255) { + l1 = l1.add(0, sy - 1, 0); + } + final int X = l1.getX() + x_offset; + final int Y = l1.getY(); + final int Z = l1.getZ() + z_offset; + for (final PlotItem item : items) { + item.x += X; + item.y += Y; + item.z += Z; + WorldUtil.IMP.addItems(plot.getArea().worldname, item); + } + return true; + } + + public Schematic getSchematic(final CompoundTag tag) { + final Map tagMap = tag.getValue(); + // Slow + // byte[] addId = new byte[0]; + // if (tagMap.containsKey("AddBlocks")) { + // addId = ByteArrayTag.class.cast(tagMap.get("AddBlocks")).getValue(); + // } + // end slow + + final short width = ShortTag.class.cast(tagMap.get("Width")).getValue(); + final short length = ShortTag.class.cast(tagMap.get("Length")).getValue(); + final short height = ShortTag.class.cast(tagMap.get("Height")).getValue(); + final byte[] block_sml = ByteArrayTag.class.cast(tagMap.get("Blocks")).getValue(); + final byte[] data = ByteArrayTag.class.cast(tagMap.get("Data")).getValue(); + + final short[] block = new short[block_sml.length]; + for (int i = 0; i < block.length; i++) { + short id = block_sml[i]; + if (id < 0) { + id = (short) (id & 0xFF); + } + block[i] = id; + } + + // Slow + has code for exceptions (addId) inside the loop rather than outside + // for (int index = 0; index < b.length; index++) { + // if ((index >> 1) >= addId.length) { + // blocks[index] = (short) (b[index] & 0xFF); + // } else { + // if ((index & 1) == 0) { + // blocks[index] = (short) (((addId[index >> 1] & 0x0F) << 8) + (b[index] & 0xFF)); + // } else { + // blocks[index] = (short) (((addId[index >> 1] & 0xF0) << 4) + (b[index] & 0xFF)); + // } + // } + // } + // Slow as wrapper for each block + // final DataCollection[] collection = new DataCollection[b.length]; + // for (int x = 0; x < b.length; x++) { + // collection[x] = new DataCollection(blocks[x], d[x]); + // } + // Schematic schem = new Schematic(collection, dimension, file); + + final Dimension dimensions = new Dimension(width, height, length); + final Schematic schem = new Schematic(block, data, dimensions); + + // Slow + try { + final List blockStates = ListTag.class.cast(tagMap.get("TileEntities")).getValue(); + for (final Tag stateTag : blockStates) { + try { + final CompoundTag ct = ((CompoundTag) stateTag); + final Map state = ct.getValue(); + final short x = IntTag.class.cast(state.get("x")).getValue().shortValue(); + final short y = IntTag.class.cast(state.get("y")).getValue().shortValue(); + final short z = IntTag.class.cast(state.get("z")).getValue().shortValue(); + manager.restoreTag(ct, x, y, z, schem); + } catch (final Exception e) { + e.printStackTrace(); + } + } + } catch (final Exception e) { + e.printStackTrace(); + } + return schem; + } + + public abstract void restoreTag(CompoundTag ct, short x, short y, short z, Schematic schem); + + /** + * Get a schematic + * + * @param name to check + * + * @return schematic if found, else null + */ + public Schematic getSchematic(final String name) { + final File parent = new File(PS.get().IMP.getDirectory() + File.separator + "schematics"); + if (!parent.exists()) { + if (!parent.mkdir()) { + throw new RuntimeException("Could not create schematic parent directory"); + } + } + final File file = new File(PS.get().IMP.getDirectory() + File.separator + "schematics" + File.separator + name + (name.endsWith(".schematic") ? "" : ".schematic")); + return getSchematic(file); + } + + /** + * Get a schematic + * + * @param file to check + * + * @return schematic if found, else null + */ + public Schematic getSchematic(final File file) { + if (!file.exists()) { + return null; + } + try { + return getSchematic(new FileInputStream(file)); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + return null; + } + + public Schematic getSchematic(final URL url) { + try { + final ReadableByteChannel rbc = Channels.newChannel(url.openStream()); + final InputStream is = Channels.newInputStream(rbc); + return getSchematic(is); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + + public Schematic getSchematic(final InputStream is) { + if (is == null) { + return null; + } + try { + final NBTInputStream stream = new NBTInputStream(new GZIPInputStream(is)); + final CompoundTag tag = (CompoundTag) stream.readTag(1073741824); + is.close(); + stream.close(); + return getSchematic(tag); + } catch (IOException e) { + e.printStackTrace(); + PS.debug(is.toString() + " | " + is.getClass().getCanonicalName() + " is not in GZIP format : " + e.getMessage()); + } + return null; + } + + public List getSaves(final UUID uuid) { + final StringBuilder rawJSON = new StringBuilder(); + try { + final String website = Settings.WEB_URL + "list.php?" + uuid.toString(); + final URL url = new URL(website); + final URLConnection connection = new URL(url.toString()).openConnection(); + connection.setRequestProperty("User-Agent", "Mozilla/5.0"); + final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); + String line; + while ((line = reader.readLine()) != null) { + rawJSON.append(line); + } + reader.close(); + final JSONArray array = new JSONArray(rawJSON.toString()); + final List schematics = new ArrayList<>(); + for (int i = 0; i < array.length(); i++) { + final String schematic = array.getString(i); + schematics.add(schematic); + } + return Lists.reverse(schematics); + } catch (JSONException | IOException e) { + e.printStackTrace(); + PS.debug("ERROR PARSING: " + rawJSON); + } + return null; + } + + public URL upload(final CompoundTag tag, UUID uuid, String file) { + if (tag == null) { + PS.debug("&cCannot save empty tag"); + return null; + } + try { + String website; + if (uuid == null) { + uuid = UUID.randomUUID(); + website = Settings.WEB_URL + "upload.php?" + uuid; + file = "plot"; + } else { + website = Settings.WEB_URL + "save.php?" + uuid; + } + final String boundary = Long.toHexString(System.currentTimeMillis()); + final URLConnection con = new URL(website).openConnection(); + con.setDoOutput(true); + con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); + try (OutputStream output = con.getOutputStream(); + PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8), true)) { + final String CRLF = "\r\n"; + writer.append("--" + boundary).append(CRLF); + writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF); + writer.append("Content-Type: text/plain; charset=" + StandardCharsets.UTF_8.displayName()).append(CRLF); + final String param = "value"; + writer.append(CRLF).append(param).append(CRLF).flush(); + writer.append("--" + boundary).append(CRLF); + writer.append("Content-Disposition: form-data; name=\"schematicFile\"; filename=\"" + file + ".schematic" + "\"").append(CRLF); + writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(file + ".schematic")).append(CRLF); + writer.append("Content-Transfer-Encoding: binary").append(CRLF); + writer.append(CRLF).flush(); + final GZIPOutputStream gzip = new GZIPOutputStream(output); + final NBTOutputStream nos = new NBTOutputStream(gzip); + nos.writeTag(tag); + gzip.finish(); + nos.flush(); + output.flush(); + writer.append(CRLF).flush(); + writer.append("--" + boundary + "--").append(CRLF).flush(); + nos.close(); + } + try (Reader response = new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)) { + final char[] buffer = new char[256]; + final StringBuilder result = new StringBuilder(); + while (true) { + final int r = response.read(buffer); + if (r < 0) { + break; + } + result.append(buffer, 0, r); + } + if (!result.toString().equals("The file plot.schematic has been uploaded.")) { + PS.debug(result); + } + } catch (IOException e) { + e.printStackTrace(); + } + final int responseCode = ((HttpURLConnection) con).getResponseCode(); + if (responseCode != 200) { + return null; + } + return new URL(Settings.WEB_URL + "?key=" + uuid + "&ip=" + Settings.WEB_IP); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + + /** + * Saves a schematic to a file path + * + * @param tag to save + * @param path to save in + * + * @return true if succeeded + */ + public boolean save(final CompoundTag tag, final String path) { + if (tag == null) { + PS.debug("&cCannot save empty tag"); + return false; + } + try { + final File tmp = new File(path); + tmp.getParentFile().mkdirs(); + try (OutputStream stream = new FileOutputStream(path); NBTOutputStream output = new NBTOutputStream(new GZIPOutputStream(stream))) { + output.writeTag(tag); + } + } catch (final IOException e) { + e.printStackTrace(); + return false; + } + return true; + } + + /** + * Create a compound tag from blocks + * - Untested + * @param blocks + * @param blockdata + * @param d + * @return + */ + public CompoundTag createTag(final byte[] blocks, final byte[] blockdata, final Dimension d) { + final HashMap schematic = new HashMap<>(); + schematic.put("Width", new ShortTag("Width", (short) d.getX())); + schematic.put("Length", new ShortTag("Length", (short) d.getZ())); + schematic.put("Height", new ShortTag("Height", (short) d.getY())); + schematic.put("Materials", new StringTag("Materials", "Alpha")); + schematic.put("WEOriginX", new IntTag("WEOriginX", 0)); + schematic.put("WEOriginY", new IntTag("WEOriginY", 0)); + schematic.put("WEOriginZ", new IntTag("WEOriginZ", 0)); + schematic.put("WEOffsetX", new IntTag("WEOffsetX", 0)); + schematic.put("WEOffsetY", new IntTag("WEOffsetY", 0)); + schematic.put("WEOffsetZ", new IntTag("WEOffsetZ", 0)); + schematic.put("Blocks", new ByteArrayTag("Blocks", blocks)); + schematic.put("Data", new ByteArrayTag("Data", blockdata)); + schematic.put("Entities", new ListTag("Entities", CompoundTag.class, new ArrayList())); + schematic.put("TileEntities", new ListTag("TileEntities", CompoundTag.class, new ArrayList())); + return new CompoundTag("Schematic", schematic); + } + + public abstract void getCompoundTag(final String world, Set regions, final RunnableVal whenDone); + + public void getCompoundTag(Plot plot, final RunnableVal whenDone) { + getCompoundTag(plot.getArea().worldname, plot.getRegions(), whenDone); + } + + /** + * Schematic Dimensions + * + + */ + public static class Dimension { + + private final int x; + private final int y; + private final int z; + + public Dimension(final int x, final int y, final int z) { + this.x = x; + this.y = y; + this.z = z; + } + + public int getX() { + return x; + } + + public int getY() { + return y; + } + + public int getZ() { + return z; + } + } + + /** + * Schematic Class + * + + */ + public class Schematic { + // Lossy but fast + private final short[] ids; + private final byte[] datas; + + private final Dimension schematicDimension; + private HashSet items; + + public Schematic(final short[] i, final byte[] b, final Dimension d) { + ids = i; + datas = b; + schematicDimension = d; + } + + /** + * Add an item to the schematic + * @param item + */ + public void addItem(final PlotItem item) { + if (items == null) { + items = new HashSet<>(); + } + items.add(item); + } + + /** + * Get any items associated with this schematic + * @return + */ + public HashSet getItems() { + return items; + } + + /** + * Get the schematic dimensions + * @return + */ + public Dimension getSchematicDimension() { + return schematicDimension; + } + + /** + * Get the block type array + * @return + */ + public short[] getIds() { + return ids; + } + + /** + * Get the block data array + * @return + */ + public byte[] getDatas() { + return datas; + } + + public Schematic copySection(RegionWrapper region) { + + int x1 = region.minX; + int x2 = region.maxX; + + int z1 = region.minZ; + int z2 = region.maxZ; + + int y1 = region.minY; + int y2 = Math.min(region.maxY, 255); + + int width = x2 - x1 + 1; + int length = z2 - z1 + 1; + int height = y2 - y1 + 1; + + short[] ids2 = new short[width * length * height]; + byte[] datas2 = new byte[width * length * height]; + + int dx = schematicDimension.getX(); + int dy = schematicDimension.getY(); + int dz = schematicDimension.getZ(); + + for (int y = y1; y <= y2; y++) { + int yy = y >= 0 ? (y < dy ? y : y - dy) : y + dy; + int i1 = yy * dx * dz; + int j1 = (y - y1) * width * length; + for (int z = z1; z <= z2; z++) { + int zz = z >= 0 ? (z < dz ? z : z - dz) : z + dz; + int i2 = i1 + zz * dx; + int j2 = j1 + (z - z1) * width; + for (int x = x1; x <= x2; x++) { + int xx = x >= 0 ? (x < dx ? x : x - dx) : x + dx; + int i3 = i2 + xx; + int j3 = j2 + (x - x1); + ids2[j3] = ids[i3]; + datas2[j3] = datas[i3]; + } + } + } + return new Schematic(ids2, datas2, new Dimension(width, height, length)); + } + + public void save(final File file) { + byte[] ids2 = new byte[ids.length]; + for (int i = 0; i < ids.length; i++) { + ids2[i] = (byte) ids[i]; + } + CompoundTag tag = createTag(ids2, datas, schematicDimension); + SchematicHandler.this.save(tag, file.toString()); + } + } + +} diff --git a/src/main/java/com/intellectualcrafters/plot/util/SetQueue.java b/Core/src/main/java/com/intellectualcrafters/plot/util/SetQueue.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/SetQueue.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/SetQueue.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/SetupUtils.java b/Core/src/main/java/com/intellectualcrafters/plot/util/SetupUtils.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/SetupUtils.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/SetupUtils.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/StringComparison.java b/Core/src/main/java/com/intellectualcrafters/plot/util/StringComparison.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/StringComparison.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/StringComparison.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/StringMan.java b/Core/src/main/java/com/intellectualcrafters/plot/util/StringMan.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/StringMan.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/StringMan.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/TaskManager.java b/Core/src/main/java/com/intellectualcrafters/plot/util/TaskManager.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/TaskManager.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/TaskManager.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/UUIDHandler.java b/Core/src/main/java/com/intellectualcrafters/plot/util/UUIDHandler.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/UUIDHandler.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/UUIDHandler.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/UUIDHandlerImplementation.java b/Core/src/main/java/com/intellectualcrafters/plot/util/UUIDHandlerImplementation.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/UUIDHandlerImplementation.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/UUIDHandlerImplementation.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/WorldUtil.java b/Core/src/main/java/com/intellectualcrafters/plot/util/WorldUtil.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/WorldUtil.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/WorldUtil.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/area/QuadMap.java b/Core/src/main/java/com/intellectualcrafters/plot/util/area/QuadMap.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/area/QuadMap.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/area/QuadMap.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/helpmenu/HelpMenu.java b/Core/src/main/java/com/intellectualcrafters/plot/util/helpmenu/HelpMenu.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/helpmenu/HelpMenu.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/helpmenu/HelpMenu.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/helpmenu/HelpObject.java b/Core/src/main/java/com/intellectualcrafters/plot/util/helpmenu/HelpObject.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/helpmenu/HelpObject.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/helpmenu/HelpObject.java diff --git a/src/main/java/com/intellectualcrafters/plot/util/helpmenu/HelpPage.java b/Core/src/main/java/com/intellectualcrafters/plot/util/helpmenu/HelpPage.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/util/helpmenu/HelpPage.java rename to Core/src/main/java/com/intellectualcrafters/plot/util/helpmenu/HelpPage.java diff --git a/src/main/java/com/intellectualcrafters/plot/uuid/UUIDWrapper.java b/Core/src/main/java/com/intellectualcrafters/plot/uuid/UUIDWrapper.java similarity index 100% rename from src/main/java/com/intellectualcrafters/plot/uuid/UUIDWrapper.java rename to Core/src/main/java/com/intellectualcrafters/plot/uuid/UUIDWrapper.java diff --git a/src/main/java/com/plotsquared/general/commands/Argument.java b/Core/src/main/java/com/plotsquared/general/commands/Argument.java similarity index 100% rename from src/main/java/com/plotsquared/general/commands/Argument.java rename to Core/src/main/java/com/plotsquared/general/commands/Argument.java diff --git a/src/main/java/com/plotsquared/general/commands/Command.java b/Core/src/main/java/com/plotsquared/general/commands/Command.java similarity index 100% rename from src/main/java/com/plotsquared/general/commands/Command.java rename to Core/src/main/java/com/plotsquared/general/commands/Command.java diff --git a/src/main/java/com/plotsquared/general/commands/CommandCaller.java b/Core/src/main/java/com/plotsquared/general/commands/CommandCaller.java similarity index 100% rename from src/main/java/com/plotsquared/general/commands/CommandCaller.java rename to Core/src/main/java/com/plotsquared/general/commands/CommandCaller.java diff --git a/src/main/java/com/plotsquared/general/commands/CommandDeclaration.java b/Core/src/main/java/com/plotsquared/general/commands/CommandDeclaration.java similarity index 100% rename from src/main/java/com/plotsquared/general/commands/CommandDeclaration.java rename to Core/src/main/java/com/plotsquared/general/commands/CommandDeclaration.java diff --git a/src/main/java/com/plotsquared/general/commands/CommandHandlingOutput.java b/Core/src/main/java/com/plotsquared/general/commands/CommandHandlingOutput.java similarity index 100% rename from src/main/java/com/plotsquared/general/commands/CommandHandlingOutput.java rename to Core/src/main/java/com/plotsquared/general/commands/CommandHandlingOutput.java diff --git a/src/main/java/com/plotsquared/general/commands/CommandManager.java b/Core/src/main/java/com/plotsquared/general/commands/CommandManager.java similarity index 100% rename from src/main/java/com/plotsquared/general/commands/CommandManager.java rename to Core/src/main/java/com/plotsquared/general/commands/CommandManager.java diff --git a/src/main/java/com/plotsquared/listener/ExtentWrapper.java b/Core/src/main/java/com/plotsquared/listener/ExtentWrapper.java similarity index 100% rename from src/main/java/com/plotsquared/listener/ExtentWrapper.java rename to Core/src/main/java/com/plotsquared/listener/ExtentWrapper.java diff --git a/src/main/java/com/plotsquared/listener/HeightLimitExtent.java b/Core/src/main/java/com/plotsquared/listener/HeightLimitExtent.java similarity index 100% rename from src/main/java/com/plotsquared/listener/HeightLimitExtent.java rename to Core/src/main/java/com/plotsquared/listener/HeightLimitExtent.java diff --git a/src/main/java/com/plotsquared/listener/PlayerBlockEventType.java b/Core/src/main/java/com/plotsquared/listener/PlayerBlockEventType.java similarity index 100% rename from src/main/java/com/plotsquared/listener/PlayerBlockEventType.java rename to Core/src/main/java/com/plotsquared/listener/PlayerBlockEventType.java diff --git a/src/main/java/com/plotsquared/listener/PlotListener.java b/Core/src/main/java/com/plotsquared/listener/PlotListener.java similarity index 98% rename from src/main/java/com/plotsquared/listener/PlotListener.java rename to Core/src/main/java/com/plotsquared/listener/PlotListener.java index e2654efa0..017609179 100644 --- a/src/main/java/com/plotsquared/listener/PlotListener.java +++ b/Core/src/main/java/com/plotsquared/listener/PlotListener.java @@ -1,241 +1,241 @@ -//////////////////////////////////////////////////////////////////////////////////////////////////// -// PlotSquared - A plot manager and world generator for the Bukkit API / -// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / -// / -// This program is free software; you can redistribute it and/or modify / -// it under the terms of the GNU General Public License as published by / -// the Free Software Foundation; either version 3 of the License, or / -// (at your option) any later version. / -// / -// This program is distributed in the hope that it will be useful, / -// but WITHOUT ANY WARRANTY; without even the implied warranty of / -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / -// GNU General Public License for more details. / -// / -// You should have received a copy of the GNU General Public License / -// along with this program; if not, write to the Free Software Foundation, / -// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / -// / -// You can contact us via: support@intellectualsites.com / -//////////////////////////////////////////////////////////////////////////////////////////////////// -package com.plotsquared.listener; - -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.flag.Flag; -import com.intellectualcrafters.plot.flag.FlagManager; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.util.AbstractTitle; -import com.intellectualcrafters.plot.util.CommentManager; -import com.intellectualcrafters.plot.util.EventUtil; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.PlotGamemode; -import com.intellectualcrafters.plot.util.PlotWeather; -import com.intellectualcrafters.plot.util.StringMan; -import com.intellectualcrafters.plot.util.TaskManager; -import com.intellectualcrafters.plot.util.UUIDHandler; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -/** - - - */ -public class PlotListener { - - public static boolean plotEntry(final PlotPlayer pp, final Plot plot) { - if (plot.isDenied(pp.getUUID()) && !Permissions.hasPermission(pp, "plots.admin.entry.denied")) { - return false; - } - final Plot last = pp.getMeta("lastplot"); - if ((last != null) && !last.getId().equals(plot.getId())) { - plotExit(pp, last); - } - pp.setMeta("lastplot", plot.getBasePlot(false)); - EventUtil.manager.callEntry(pp, plot); - if (plot.hasOwner()) { - final HashMap flags = FlagManager.getPlotFlags(plot); - final int size = flags.size(); - boolean titles = Settings.TITLES; - final String greeting; - - if (size != 0) { - final Flag titleFlag = flags.get("titles"); - if (titleFlag != null) { - titles = (Boolean) titleFlag.getValue(); - } - final Flag greetingFlag = flags.get("greeting"); - if (greetingFlag != null) { - greeting = (String) greetingFlag.getValue(); - MainUtil.format(C.PREFIX_GREETING.s() + greeting, plot, pp, false, new RunnableVal() { - @Override - public void run(String value) { - MainUtil.sendMessage(pp, value); - } - }); - } else { - greeting = ""; - } - final Flag enter = flags.get("notify-enter"); - if (enter != null && (Boolean) enter.getValue()) { - if (!Permissions.hasPermission(pp, "plots.flag.notify-enter.bypass")) { - for (final UUID uuid : plot.getOwners()) { - final PlotPlayer owner = UUIDHandler.getPlayer(uuid); - if ((owner != null) && !owner.getUUID().equals(pp.getUUID())) { - MainUtil.sendMessage(owner, C.NOTIFY_ENTER.s().replace("%player", pp.getName()).replace("%plot", plot.getId().toString())); - } - } - } - } - final Flag gamemodeFlag = flags.get("gamemode"); - if (gamemodeFlag != null) { - if (pp.getGamemode() != gamemodeFlag.getValue()) { - if (!Permissions.hasPermission(pp, "plots.gamemode.bypass")) { - pp.setGamemode((PlotGamemode) gamemodeFlag.getValue()); - } else { - MainUtil.sendMessage(pp, StringMan.replaceAll(C.GAMEMODE_WAS_BYPASSED.s(), "{plot}", plot.getId(), "{gamemode}", gamemodeFlag.getValue())); - } - } - } - final Flag flyFlag = flags.get("fly"); - if (flyFlag != null) { - pp.setFlight((boolean) flyFlag.getValue()); - } - final Flag timeFlag = flags.get("time"); - if (timeFlag != null) { - try { - final long time = (long) timeFlag.getValue(); - pp.setTime(time); - } catch (final Exception e) { - FlagManager.removePlotFlag(plot, "time"); - } - } - final Flag weatherFlag = flags.get("weather"); - if (weatherFlag != null) { - pp.setWeather((PlotWeather) weatherFlag.getValue()); - } - - final Flag musicFlag = flags.get("music"); - if (musicFlag != null) { - final Integer id = (Integer) musicFlag.getValue(); - if ((id >= 2256 && id <= 2267) || (id == 0)) { - final Location loc = pp.getLocation(); - final Location lastLoc = pp.getMeta("music"); - if (lastLoc != null) { - pp.playMusic(lastLoc, 0); - if (id == 0) { - pp.deleteMeta("music"); - } - } - if (id != 0) { - try { - pp.setMeta("music", loc); - pp.playMusic(loc, id); - } catch (final Exception e) {} - } - } - } else { - final Location lastLoc = pp.getMeta("music"); - if (lastLoc != null) { - pp.deleteMeta("music"); - pp.playMusic(lastLoc, 0); - } - } - CommentManager.sendTitle(pp, plot); - } else if (titles) { - greeting = ""; - } else { - return true; - } - if (titles) { - if ((!C.TITLE_ENTERED_PLOT.s().isEmpty()) || (!C.TITLE_ENTERED_PLOT_SUB.s().isEmpty())) { - TaskManager.runTaskLaterAsync(new Runnable() { - @Override - public void run() { - final Plot lastPlot = pp.getMeta("lastplot"); - if ((lastPlot != null) && plot.getId().equals(lastPlot.getId())) { - final Map replacements = new HashMap<>(); - replacements.put("%x%", lastPlot.getId().x + ""); - replacements.put("%z%", lastPlot.getId().y + ""); - replacements.put("%world%", plot.getArea().toString()); - replacements.put("%greeting%", greeting); - replacements.put("%alias", plot.toString()); - replacements.put("%s", MainUtil.getName(plot.owner)); - final String main = StringMan.replaceFromMap(C.TITLE_ENTERED_PLOT.s(), replacements); - final String sub = StringMan.replaceFromMap(C.TITLE_ENTERED_PLOT_SUB.s(), replacements); - AbstractTitle.sendTitle(pp, main, sub); - } - } - }, 20); - } - } - return true; - } - return true; - } - - public static boolean plotExit(final PlotPlayer pp, final Plot plot) { - pp.deleteMeta("lastplot"); - EventUtil.manager.callLeave(pp, plot); - if (plot.hasOwner()) { - final PlotArea pw = plot.getArea(); - if (pw == null) { - return true; - } - if (FlagManager.getPlotFlagRaw(plot, "gamemode") != null) { - if (pp.getGamemode() != pw.GAMEMODE) { - if (!Permissions.hasPermission(pp, "plots.gamemode.bypass")) { - pp.setGamemode(pw.GAMEMODE); - } else { - MainUtil.sendMessage(pp, StringMan.replaceAll(C.GAMEMODE_WAS_BYPASSED.s(), "{plot}", plot.toString(), "{gamemode}", pw.GAMEMODE.name().toLowerCase())); - } - } - } - final Flag farewell = FlagManager.getPlotFlagRaw(plot, "farewell"); - if (farewell != null) { - MainUtil.format(C.PREFIX_FAREWELL.s() + farewell.getValueString(), plot, pp, false, new RunnableVal() { - @Override - public void run(String value) { - MainUtil.sendMessage(pp, value); - } - }); - } - final Flag leave = FlagManager.getPlotFlagRaw(plot, "notify-leave"); - if ((leave != null) && ((Boolean) leave.getValue())) { - if (!Permissions.hasPermission(pp, "plots.flag.notify-enter.bypass")) { - for (final UUID uuid : plot.getOwners()) { - final PlotPlayer owner = UUIDHandler.getPlayer(uuid); - if ((owner != null) && !owner.getUUID().equals(pp.getUUID())) { - MainUtil.sendMessage(pp, C.NOTIFY_LEAVE.s().replace("%player", pp.getName()).replace("%plot", plot.getId().toString())); - } - } - } - } - if (FlagManager.getPlotFlagRaw(plot, "fly") != null) { - final PlotGamemode gamemode = pp.getGamemode(); - if (gamemode == PlotGamemode.SURVIVAL || (gamemode == PlotGamemode.ADVENTURE)) { - pp.setFlight(false); - } - } - if (FlagManager.getPlotFlagRaw(plot, "time") != null) { - pp.setTime(Long.MAX_VALUE); - } - if (FlagManager.getPlotFlagRaw(plot, "weather") != null) { - pp.setWeather(PlotWeather.RESET); - } - final Location lastLoc = pp.getMeta("music"); - if (lastLoc != null) { - pp.deleteMeta("music"); - pp.playMusic(lastLoc, 0); - } - } - return true; - } -} +//////////////////////////////////////////////////////////////////////////////////////////////////// +// PlotSquared - A plot manager and world generator for the Bukkit API / +// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / +// / +// This program is free software; you can redistribute it and/or modify / +// it under the terms of the GNU General Public License as published by / +// the Free Software Foundation; either version 3 of the License, or / +// (at your option) any later version. / +// / +// This program is distributed in the hope that it will be useful, / +// but WITHOUT ANY WARRANTY; without even the implied warranty of / +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / +// GNU General Public License for more details. / +// / +// You should have received a copy of the GNU General Public License / +// along with this program; if not, write to the Free Software Foundation, / +// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / +// / +// You can contact us via: support@intellectualsites.com / +//////////////////////////////////////////////////////////////////////////////////////////////////// +package com.plotsquared.listener; + +import com.intellectualcrafters.plot.config.C; +import com.intellectualcrafters.plot.config.Settings; +import com.intellectualcrafters.plot.flag.Flag; +import com.intellectualcrafters.plot.flag.FlagManager; +import com.intellectualcrafters.plot.object.Location; +import com.intellectualcrafters.plot.object.Plot; +import com.intellectualcrafters.plot.object.PlotArea; +import com.intellectualcrafters.plot.object.PlotPlayer; +import com.intellectualcrafters.plot.object.RunnableVal; +import com.intellectualcrafters.plot.util.AbstractTitle; +import com.intellectualcrafters.plot.util.CommentManager; +import com.intellectualcrafters.plot.util.EventUtil; +import com.intellectualcrafters.plot.util.MainUtil; +import com.intellectualcrafters.plot.util.Permissions; +import com.intellectualcrafters.plot.util.PlotGamemode; +import com.intellectualcrafters.plot.util.PlotWeather; +import com.intellectualcrafters.plot.util.StringMan; +import com.intellectualcrafters.plot.util.TaskManager; +import com.intellectualcrafters.plot.util.UUIDHandler; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +/** + + + */ +public class PlotListener { + + public static boolean plotEntry(final PlotPlayer pp, final Plot plot) { + if (plot.isDenied(pp.getUUID()) && !Permissions.hasPermission(pp, "plots.admin.entry.denied")) { + return false; + } + final Plot last = pp.getMeta("lastplot"); + if ((last != null) && !last.getId().equals(plot.getId())) { + plotExit(pp, last); + } + pp.setMeta("lastplot", plot.getBasePlot(false)); + EventUtil.manager.callEntry(pp, plot); + if (plot.hasOwner()) { + final HashMap flags = FlagManager.getPlotFlags(plot); + final int size = flags.size(); + boolean titles = Settings.TITLES; + final String greeting; + + if (size != 0) { + final Flag titleFlag = flags.get("titles"); + if (titleFlag != null) { + titles = (Boolean) titleFlag.getValue(); + } + final Flag greetingFlag = flags.get("greeting"); + if (greetingFlag != null) { + greeting = (String) greetingFlag.getValue(); + MainUtil.format(C.PREFIX_GREETING.s() + greeting, plot, pp, false, new RunnableVal() { + @Override + public void run(String value) { + MainUtil.sendMessage(pp, value); + } + }); + } else { + greeting = ""; + } + final Flag enter = flags.get("notify-enter"); + if (enter != null && (Boolean) enter.getValue()) { + if (!Permissions.hasPermission(pp, "plots.flag.notify-enter.bypass")) { + for (final UUID uuid : plot.getOwners()) { + final PlotPlayer owner = UUIDHandler.getPlayer(uuid); + if ((owner != null) && !owner.getUUID().equals(pp.getUUID())) { + MainUtil.sendMessage(owner, C.NOTIFY_ENTER.s().replace("%player", pp.getName()).replace("%plot", plot.getId().toString())); + } + } + } + } + final Flag gamemodeFlag = flags.get("gamemode"); + if (gamemodeFlag != null) { + if (pp.getGamemode() != gamemodeFlag.getValue()) { + if (!Permissions.hasPermission(pp, "plots.gamemode.bypass")) { + pp.setGamemode((PlotGamemode) gamemodeFlag.getValue()); + } else { + MainUtil.sendMessage(pp, StringMan.replaceAll(C.GAMEMODE_WAS_BYPASSED.s(), "{plot}", plot.getId(), "{gamemode}", gamemodeFlag.getValue())); + } + } + } + final Flag flyFlag = flags.get("fly"); + if (flyFlag != null) { + pp.setFlight((boolean) flyFlag.getValue()); + } + final Flag timeFlag = flags.get("time"); + if (timeFlag != null) { + try { + final long time = (long) timeFlag.getValue(); + pp.setTime(time); + } catch (final Exception e) { + FlagManager.removePlotFlag(plot, "time"); + } + } + final Flag weatherFlag = flags.get("weather"); + if (weatherFlag != null) { + pp.setWeather((PlotWeather) weatherFlag.getValue()); + } + + final Flag musicFlag = flags.get("music"); + if (musicFlag != null) { + final Integer id = (Integer) musicFlag.getValue(); + if ((id >= 2256 && id <= 2267) || (id == 0)) { + final Location loc = pp.getLocation(); + final Location lastLoc = pp.getMeta("music"); + if (lastLoc != null) { + pp.playMusic(lastLoc, 0); + if (id == 0) { + pp.deleteMeta("music"); + } + } + if (id != 0) { + try { + pp.setMeta("music", loc); + pp.playMusic(loc, id); + } catch (final Exception e) {} + } + } + } else { + final Location lastLoc = pp.getMeta("music"); + if (lastLoc != null) { + pp.deleteMeta("music"); + pp.playMusic(lastLoc, 0); + } + } + CommentManager.sendTitle(pp, plot); + } else if (titles) { + greeting = ""; + } else { + return true; + } + if (titles) { + if ((!C.TITLE_ENTERED_PLOT.s().isEmpty()) || (!C.TITLE_ENTERED_PLOT_SUB.s().isEmpty())) { + TaskManager.runTaskLaterAsync(new Runnable() { + @Override + public void run() { + final Plot lastPlot = pp.getMeta("lastplot"); + if ((lastPlot != null) && plot.getId().equals(lastPlot.getId())) { + final Map replacements = new HashMap<>(); + replacements.put("%x%", lastPlot.getId().x + ""); + replacements.put("%z%", lastPlot.getId().y + ""); + replacements.put("%world%", plot.getArea().toString()); + replacements.put("%greeting%", greeting); + replacements.put("%alias", plot.toString()); + replacements.put("%s", MainUtil.getName(plot.owner)); + final String main = StringMan.replaceFromMap(C.TITLE_ENTERED_PLOT.s(), replacements); + final String sub = StringMan.replaceFromMap(C.TITLE_ENTERED_PLOT_SUB.s(), replacements); + AbstractTitle.sendTitle(pp, main, sub); + } + } + }, 20); + } + } + return true; + } + return true; + } + + public static boolean plotExit(final PlotPlayer pp, final Plot plot) { + pp.deleteMeta("lastplot"); + EventUtil.manager.callLeave(pp, plot); + if (plot.hasOwner()) { + final PlotArea pw = plot.getArea(); + if (pw == null) { + return true; + } + if (FlagManager.getPlotFlagRaw(plot, "gamemode") != null) { + if (pp.getGamemode() != pw.GAMEMODE) { + if (!Permissions.hasPermission(pp, "plots.gamemode.bypass")) { + pp.setGamemode(pw.GAMEMODE); + } else { + MainUtil.sendMessage(pp, StringMan.replaceAll(C.GAMEMODE_WAS_BYPASSED.s(), "{plot}", plot.toString(), "{gamemode}", pw.GAMEMODE.name().toLowerCase())); + } + } + } + final Flag farewell = FlagManager.getPlotFlagRaw(plot, "farewell"); + if (farewell != null) { + MainUtil.format(C.PREFIX_FAREWELL.s() + farewell.getValueString(), plot, pp, false, new RunnableVal() { + @Override + public void run(String value) { + MainUtil.sendMessage(pp, value); + } + }); + } + final Flag leave = FlagManager.getPlotFlagRaw(plot, "notify-leave"); + if ((leave != null) && ((Boolean) leave.getValue())) { + if (!Permissions.hasPermission(pp, "plots.flag.notify-enter.bypass")) { + for (final UUID uuid : plot.getOwners()) { + final PlotPlayer owner = UUIDHandler.getPlayer(uuid); + if ((owner != null) && !owner.getUUID().equals(pp.getUUID())) { + MainUtil.sendMessage(pp, C.NOTIFY_LEAVE.s().replace("%player", pp.getName()).replace("%plot", plot.getId().toString())); + } + } + } + } + if (FlagManager.getPlotFlagRaw(plot, "fly") != null) { + final PlotGamemode gamemode = pp.getGamemode(); + if (gamemode == PlotGamemode.SURVIVAL || (gamemode == PlotGamemode.ADVENTURE)) { + pp.setFlight(false); + } + } + if (FlagManager.getPlotFlagRaw(plot, "time") != null) { + pp.setTime(Long.MAX_VALUE); + } + if (FlagManager.getPlotFlagRaw(plot, "weather") != null) { + pp.setWeather(PlotWeather.RESET); + } + final Location lastLoc = pp.getMeta("music"); + if (lastLoc != null) { + pp.deleteMeta("music"); + pp.playMusic(lastLoc, 0); + } + } + return true; + } +} diff --git a/src/main/java/com/plotsquared/listener/ProcessedWEExtent.java b/Core/src/main/java/com/plotsquared/listener/ProcessedWEExtent.java similarity index 100% rename from src/main/java/com/plotsquared/listener/ProcessedWEExtent.java rename to Core/src/main/java/com/plotsquared/listener/ProcessedWEExtent.java diff --git a/src/main/java/com/plotsquared/listener/WEExtent.java b/Core/src/main/java/com/plotsquared/listener/WEExtent.java similarity index 100% rename from src/main/java/com/plotsquared/listener/WEExtent.java rename to Core/src/main/java/com/plotsquared/listener/WEExtent.java diff --git a/src/main/java/com/plotsquared/listener/WEManager.java b/Core/src/main/java/com/plotsquared/listener/WEManager.java similarity index 100% rename from src/main/java/com/plotsquared/listener/WEManager.java rename to Core/src/main/java/com/plotsquared/listener/WEManager.java diff --git a/src/main/java/com/plotsquared/listener/WESubscriber.java b/Core/src/main/java/com/plotsquared/listener/WESubscriber.java similarity index 100% rename from src/main/java/com/plotsquared/listener/WESubscriber.java rename to Core/src/main/java/com/plotsquared/listener/WESubscriber.java diff --git a/src/main/resources/Ko-kr.yml b/Core/src/main/resources/Ko-kr.yml similarity index 100% rename from src/main/resources/Ko-kr.yml rename to Core/src/main/resources/Ko-kr.yml diff --git a/src/main/resources/LICENSE b/Core/src/main/resources/LICENSE similarity index 100% rename from src/main/resources/LICENSE rename to Core/src/main/resources/LICENSE diff --git a/src/main/resources/automerge.js b/Core/src/main/resources/automerge.js similarity index 100% rename from src/main/resources/automerge.js rename to Core/src/main/resources/automerge.js diff --git a/src/main/resources/base.yml b/Core/src/main/resources/base.yml similarity index 100% rename from src/main/resources/base.yml rename to Core/src/main/resources/base.yml diff --git a/src/main/resources/german.yml b/Core/src/main/resources/german.yml similarity index 100% rename from src/main/resources/german.yml rename to Core/src/main/resources/german.yml diff --git a/src/main/resources/italian.yml b/Core/src/main/resources/italian.yml similarity index 100% rename from src/main/resources/italian.yml rename to Core/src/main/resources/italian.yml diff --git a/src/main/resources/s_chinese.yml b/Core/src/main/resources/s_chinese.yml similarity index 100% rename from src/main/resources/s_chinese.yml rename to Core/src/main/resources/s_chinese.yml diff --git a/src/main/resources/s_chinese_unescaped.yml b/Core/src/main/resources/s_chinese_unescaped.yml similarity index 100% rename from src/main/resources/s_chinese_unescaped.yml rename to Core/src/main/resources/s_chinese_unescaped.yml diff --git a/src/main/resources/skyblock.template b/Core/src/main/resources/skyblock.template similarity index 100% rename from src/main/resources/skyblock.template rename to Core/src/main/resources/skyblock.template diff --git a/src/main/resources/spanish.yml b/Core/src/main/resources/spanish.yml similarity index 100% rename from src/main/resources/spanish.yml rename to Core/src/main/resources/spanish.yml diff --git a/src/main/resources/town.template b/Core/src/main/resources/town.template similarity index 100% rename from src/main/resources/town.template rename to Core/src/main/resources/town.template diff --git a/Sponge/build.gradle b/Sponge/build.gradle new file mode 100644 index 000000000..cec7245b7 --- /dev/null +++ b/Sponge/build.gradle @@ -0,0 +1,70 @@ +apply plugin: 'eclipse' +apply plugin: 'idea' + +buildscript { + repositories { + jcenter() + maven { + name = "forge" + url = "http://files.minecraftforge.net/maven" + } + } + dependencies { + classpath 'net.minecraftforge.gradle:ForgeGradle:2.1-SNAPSHOT' + } +} +apply plugin: 'net.minecraftforge.gradle.forge' + +dependencies { + compile project(':Core') + compile 'org.spongepowered:spongeapi:3.1.0-SNAPSHOT' +} + +sourceCompatibility = 1.8 +targetCompatibility = 1.8 + +repositories { + maven { + name = 'forge' + url = 'http://files.minecraftforge.net/maven' + } + maven { + name = "Sponge" + url = "https://repo.spongepowered.org/maven" + } +} + +version = "3.2.27" + +minecraft { + version = "1.8.9-11.15.1.1742" + mappings = "snapshot_20160204" + runDir = 'run' +} + +project.archivesBaseName = "${project.archivesBaseName}-mc${minecraft.version}" + +processResources { + from(sourceSets.main.resources.srcDirs) { + expand 'version': project.version, + 'mcVersion': project.minecraft.version + } +} +shadowJar { + dependencies { + include(dependency(':Core')) + } +} + +reobf { + shadowJar { + mappingType = 'SEARGE' + } +} + +task deobfJar(type: Jar) { + from sourceSets.main.output + classifier = 'dev' +} + +build.dependsOn(shadowJar) \ No newline at end of file diff --git a/src/main/java/com/plotsquared/sponge/SpongeMain.java b/Sponge/src/main/java/com/plotsquared/sponge/SpongeMain.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/SpongeMain.java rename to Sponge/src/main/java/com/plotsquared/sponge/SpongeMain.java diff --git a/src/main/java/com/plotsquared/sponge/SpongeSetupUtils.java b/Sponge/src/main/java/com/plotsquared/sponge/SpongeSetupUtils.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/SpongeSetupUtils.java rename to Sponge/src/main/java/com/plotsquared/sponge/SpongeSetupUtils.java diff --git a/src/main/java/com/plotsquared/sponge/events/ClusterFlagRemoveEvent.java b/Sponge/src/main/java/com/plotsquared/sponge/events/ClusterFlagRemoveEvent.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/events/ClusterFlagRemoveEvent.java rename to Sponge/src/main/java/com/plotsquared/sponge/events/ClusterFlagRemoveEvent.java diff --git a/src/main/java/com/plotsquared/sponge/events/PlayerClaimPlotEvent.java b/Sponge/src/main/java/com/plotsquared/sponge/events/PlayerClaimPlotEvent.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/events/PlayerClaimPlotEvent.java rename to Sponge/src/main/java/com/plotsquared/sponge/events/PlayerClaimPlotEvent.java diff --git a/src/main/java/com/plotsquared/sponge/events/PlayerEnterPlotEvent.java b/Sponge/src/main/java/com/plotsquared/sponge/events/PlayerEnterPlotEvent.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/events/PlayerEnterPlotEvent.java rename to Sponge/src/main/java/com/plotsquared/sponge/events/PlayerEnterPlotEvent.java diff --git a/src/main/java/com/plotsquared/sponge/events/PlayerEvent.java b/Sponge/src/main/java/com/plotsquared/sponge/events/PlayerEvent.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/events/PlayerEvent.java rename to Sponge/src/main/java/com/plotsquared/sponge/events/PlayerEvent.java diff --git a/src/main/java/com/plotsquared/sponge/events/PlayerLeavePlotEvent.java b/Sponge/src/main/java/com/plotsquared/sponge/events/PlayerLeavePlotEvent.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/events/PlayerLeavePlotEvent.java rename to Sponge/src/main/java/com/plotsquared/sponge/events/PlayerLeavePlotEvent.java diff --git a/src/main/java/com/plotsquared/sponge/events/PlayerPlotDeniedEvent.java b/Sponge/src/main/java/com/plotsquared/sponge/events/PlayerPlotDeniedEvent.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/events/PlayerPlotDeniedEvent.java rename to Sponge/src/main/java/com/plotsquared/sponge/events/PlayerPlotDeniedEvent.java diff --git a/src/main/java/com/plotsquared/sponge/events/PlayerPlotHelperEvent.java b/Sponge/src/main/java/com/plotsquared/sponge/events/PlayerPlotHelperEvent.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/events/PlayerPlotHelperEvent.java rename to Sponge/src/main/java/com/plotsquared/sponge/events/PlayerPlotHelperEvent.java diff --git a/src/main/java/com/plotsquared/sponge/events/PlayerPlotTrustedEvent.java b/Sponge/src/main/java/com/plotsquared/sponge/events/PlayerPlotTrustedEvent.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/events/PlayerPlotTrustedEvent.java rename to Sponge/src/main/java/com/plotsquared/sponge/events/PlayerPlotTrustedEvent.java diff --git a/src/main/java/com/plotsquared/sponge/events/PlayerTeleportToPlotEvent.java b/Sponge/src/main/java/com/plotsquared/sponge/events/PlayerTeleportToPlotEvent.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/events/PlayerTeleportToPlotEvent.java rename to Sponge/src/main/java/com/plotsquared/sponge/events/PlayerTeleportToPlotEvent.java diff --git a/src/main/java/com/plotsquared/sponge/events/PlotClearEvent.java b/Sponge/src/main/java/com/plotsquared/sponge/events/PlotClearEvent.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/events/PlotClearEvent.java rename to Sponge/src/main/java/com/plotsquared/sponge/events/PlotClearEvent.java diff --git a/src/main/java/com/plotsquared/sponge/events/PlotDeleteEvent.java b/Sponge/src/main/java/com/plotsquared/sponge/events/PlotDeleteEvent.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/events/PlotDeleteEvent.java rename to Sponge/src/main/java/com/plotsquared/sponge/events/PlotDeleteEvent.java diff --git a/src/main/java/com/plotsquared/sponge/events/PlotEvent.java b/Sponge/src/main/java/com/plotsquared/sponge/events/PlotEvent.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/events/PlotEvent.java rename to Sponge/src/main/java/com/plotsquared/sponge/events/PlotEvent.java diff --git a/src/main/java/com/plotsquared/sponge/events/PlotFlagAddEvent.java b/Sponge/src/main/java/com/plotsquared/sponge/events/PlotFlagAddEvent.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/events/PlotFlagAddEvent.java rename to Sponge/src/main/java/com/plotsquared/sponge/events/PlotFlagAddEvent.java diff --git a/src/main/java/com/plotsquared/sponge/events/PlotFlagRemoveEvent.java b/Sponge/src/main/java/com/plotsquared/sponge/events/PlotFlagRemoveEvent.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/events/PlotFlagRemoveEvent.java rename to Sponge/src/main/java/com/plotsquared/sponge/events/PlotFlagRemoveEvent.java diff --git a/src/main/java/com/plotsquared/sponge/events/PlotMergeEvent.java b/Sponge/src/main/java/com/plotsquared/sponge/events/PlotMergeEvent.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/events/PlotMergeEvent.java rename to Sponge/src/main/java/com/plotsquared/sponge/events/PlotMergeEvent.java diff --git a/src/main/java/com/plotsquared/sponge/events/PlotRateEvent.java b/Sponge/src/main/java/com/plotsquared/sponge/events/PlotRateEvent.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/events/PlotRateEvent.java rename to Sponge/src/main/java/com/plotsquared/sponge/events/PlotRateEvent.java diff --git a/src/main/java/com/plotsquared/sponge/events/PlotUnlinkEvent.java b/Sponge/src/main/java/com/plotsquared/sponge/events/PlotUnlinkEvent.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/events/PlotUnlinkEvent.java rename to Sponge/src/main/java/com/plotsquared/sponge/events/PlotUnlinkEvent.java diff --git a/src/main/java/com/plotsquared/sponge/generator/SpongeAugmentedGenerator.java b/Sponge/src/main/java/com/plotsquared/sponge/generator/SpongeAugmentedGenerator.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/generator/SpongeAugmentedGenerator.java rename to Sponge/src/main/java/com/plotsquared/sponge/generator/SpongeAugmentedGenerator.java diff --git a/src/main/java/com/plotsquared/sponge/generator/SpongePlotGenerator.java b/Sponge/src/main/java/com/plotsquared/sponge/generator/SpongePlotGenerator.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/generator/SpongePlotGenerator.java rename to Sponge/src/main/java/com/plotsquared/sponge/generator/SpongePlotGenerator.java diff --git a/src/main/java/com/plotsquared/sponge/generator/SpongeTerrainGen.java b/Sponge/src/main/java/com/plotsquared/sponge/generator/SpongeTerrainGen.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/generator/SpongeTerrainGen.java rename to Sponge/src/main/java/com/plotsquared/sponge/generator/SpongeTerrainGen.java diff --git a/src/main/java/com/plotsquared/sponge/listener/ChunkProcessor.java b/Sponge/src/main/java/com/plotsquared/sponge/listener/ChunkProcessor.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/listener/ChunkProcessor.java rename to Sponge/src/main/java/com/plotsquared/sponge/listener/ChunkProcessor.java diff --git a/src/main/java/com/plotsquared/sponge/listener/MainListener.java b/Sponge/src/main/java/com/plotsquared/sponge/listener/MainListener.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/listener/MainListener.java rename to Sponge/src/main/java/com/plotsquared/sponge/listener/MainListener.java diff --git a/src/main/java/com/plotsquared/sponge/listener/WorldEvents.java b/Sponge/src/main/java/com/plotsquared/sponge/listener/WorldEvents.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/listener/WorldEvents.java rename to Sponge/src/main/java/com/plotsquared/sponge/listener/WorldEvents.java diff --git a/src/main/java/com/plotsquared/sponge/object/SpongeOfflinePlayer.java b/Sponge/src/main/java/com/plotsquared/sponge/object/SpongeOfflinePlayer.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/object/SpongeOfflinePlayer.java rename to Sponge/src/main/java/com/plotsquared/sponge/object/SpongeOfflinePlayer.java diff --git a/src/main/java/com/plotsquared/sponge/object/SpongePlayer.java b/Sponge/src/main/java/com/plotsquared/sponge/object/SpongePlayer.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/object/SpongePlayer.java rename to Sponge/src/main/java/com/plotsquared/sponge/object/SpongePlayer.java diff --git a/src/main/java/com/plotsquared/sponge/util/KillRoadMobs.java b/Sponge/src/main/java/com/plotsquared/sponge/util/KillRoadMobs.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/util/KillRoadMobs.java rename to Sponge/src/main/java/com/plotsquared/sponge/util/KillRoadMobs.java diff --git a/src/main/java/com/plotsquared/sponge/util/SpongeChatManager.java b/Sponge/src/main/java/com/plotsquared/sponge/util/SpongeChatManager.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/util/SpongeChatManager.java rename to Sponge/src/main/java/com/plotsquared/sponge/util/SpongeChatManager.java diff --git a/src/main/java/com/plotsquared/sponge/util/SpongeChunkManager.java b/Sponge/src/main/java/com/plotsquared/sponge/util/SpongeChunkManager.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/util/SpongeChunkManager.java rename to Sponge/src/main/java/com/plotsquared/sponge/util/SpongeChunkManager.java diff --git a/src/main/java/com/plotsquared/sponge/util/SpongeCommand.java b/Sponge/src/main/java/com/plotsquared/sponge/util/SpongeCommand.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/util/SpongeCommand.java rename to Sponge/src/main/java/com/plotsquared/sponge/util/SpongeCommand.java diff --git a/src/main/java/com/plotsquared/sponge/util/SpongeEconHandler.java b/Sponge/src/main/java/com/plotsquared/sponge/util/SpongeEconHandler.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/util/SpongeEconHandler.java rename to Sponge/src/main/java/com/plotsquared/sponge/util/SpongeEconHandler.java diff --git a/src/main/java/com/plotsquared/sponge/util/SpongeEventUtil.java b/Sponge/src/main/java/com/plotsquared/sponge/util/SpongeEventUtil.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/util/SpongeEventUtil.java rename to Sponge/src/main/java/com/plotsquared/sponge/util/SpongeEventUtil.java diff --git a/src/main/java/com/plotsquared/sponge/util/SpongeHybridUtils.java b/Sponge/src/main/java/com/plotsquared/sponge/util/SpongeHybridUtils.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/util/SpongeHybridUtils.java rename to Sponge/src/main/java/com/plotsquared/sponge/util/SpongeHybridUtils.java diff --git a/src/main/java/com/plotsquared/sponge/util/SpongeInventoryUtil.java b/Sponge/src/main/java/com/plotsquared/sponge/util/SpongeInventoryUtil.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/util/SpongeInventoryUtil.java rename to Sponge/src/main/java/com/plotsquared/sponge/util/SpongeInventoryUtil.java diff --git a/src/main/java/com/plotsquared/sponge/util/SpongeMetrics.java b/Sponge/src/main/java/com/plotsquared/sponge/util/SpongeMetrics.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/util/SpongeMetrics.java rename to Sponge/src/main/java/com/plotsquared/sponge/util/SpongeMetrics.java diff --git a/src/main/java/com/plotsquared/sponge/util/SpongeSchematicHandler.java b/Sponge/src/main/java/com/plotsquared/sponge/util/SpongeSchematicHandler.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/util/SpongeSchematicHandler.java rename to Sponge/src/main/java/com/plotsquared/sponge/util/SpongeSchematicHandler.java diff --git a/src/main/java/com/plotsquared/sponge/util/SpongeSetupUtils.java b/Sponge/src/main/java/com/plotsquared/sponge/util/SpongeSetupUtils.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/util/SpongeSetupUtils.java rename to Sponge/src/main/java/com/plotsquared/sponge/util/SpongeSetupUtils.java diff --git a/src/main/java/com/plotsquared/sponge/util/SpongeTaskManager.java b/Sponge/src/main/java/com/plotsquared/sponge/util/SpongeTaskManager.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/util/SpongeTaskManager.java rename to Sponge/src/main/java/com/plotsquared/sponge/util/SpongeTaskManager.java diff --git a/src/main/java/com/plotsquared/sponge/util/SpongeTitleManager.java b/Sponge/src/main/java/com/plotsquared/sponge/util/SpongeTitleManager.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/util/SpongeTitleManager.java rename to Sponge/src/main/java/com/plotsquared/sponge/util/SpongeTitleManager.java diff --git a/src/main/java/com/plotsquared/sponge/util/SpongeUtil.java b/Sponge/src/main/java/com/plotsquared/sponge/util/SpongeUtil.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/util/SpongeUtil.java rename to Sponge/src/main/java/com/plotsquared/sponge/util/SpongeUtil.java diff --git a/src/main/java/com/plotsquared/sponge/util/block/FastChunk.java b/Sponge/src/main/java/com/plotsquared/sponge/util/block/FastChunk.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/util/block/FastChunk.java rename to Sponge/src/main/java/com/plotsquared/sponge/util/block/FastChunk.java diff --git a/src/main/java/com/plotsquared/sponge/util/block/FastQueue.java b/Sponge/src/main/java/com/plotsquared/sponge/util/block/FastQueue.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/util/block/FastQueue.java rename to Sponge/src/main/java/com/plotsquared/sponge/util/block/FastQueue.java diff --git a/src/main/java/com/plotsquared/sponge/util/block/GenChunk.java b/Sponge/src/main/java/com/plotsquared/sponge/util/block/GenChunk.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/util/block/GenChunk.java rename to Sponge/src/main/java/com/plotsquared/sponge/util/block/GenChunk.java diff --git a/src/main/java/com/plotsquared/sponge/util/block/SlowChunk.java b/Sponge/src/main/java/com/plotsquared/sponge/util/block/SlowChunk.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/util/block/SlowChunk.java rename to Sponge/src/main/java/com/plotsquared/sponge/util/block/SlowChunk.java diff --git a/src/main/java/com/plotsquared/sponge/util/block/SlowQueue.java b/Sponge/src/main/java/com/plotsquared/sponge/util/block/SlowQueue.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/util/block/SlowQueue.java rename to Sponge/src/main/java/com/plotsquared/sponge/util/block/SlowQueue.java diff --git a/src/main/java/com/plotsquared/sponge/uuid/SpongeLowerOfflineUUIDWrapper.java b/Sponge/src/main/java/com/plotsquared/sponge/uuid/SpongeLowerOfflineUUIDWrapper.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/uuid/SpongeLowerOfflineUUIDWrapper.java rename to Sponge/src/main/java/com/plotsquared/sponge/uuid/SpongeLowerOfflineUUIDWrapper.java diff --git a/src/main/java/com/plotsquared/sponge/uuid/SpongeOnlineUUIDWrapper.java b/Sponge/src/main/java/com/plotsquared/sponge/uuid/SpongeOnlineUUIDWrapper.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/uuid/SpongeOnlineUUIDWrapper.java rename to Sponge/src/main/java/com/plotsquared/sponge/uuid/SpongeOnlineUUIDWrapper.java diff --git a/src/main/java/com/plotsquared/sponge/uuid/SpongeUUIDHandler.java b/Sponge/src/main/java/com/plotsquared/sponge/uuid/SpongeUUIDHandler.java similarity index 100% rename from src/main/java/com/plotsquared/sponge/uuid/SpongeUUIDHandler.java rename to Sponge/src/main/java/com/plotsquared/sponge/uuid/SpongeUUIDHandler.java diff --git a/build.gradle b/build.gradle new file mode 100644 index 000000000..3a10bb028 --- /dev/null +++ b/build.gradle @@ -0,0 +1,35 @@ +buildscript { + repositories { + mavenCentral() + maven { url = "https://oss.sonatype.org/content/repositories/snapshots/" } + jcenter() + } + dependencies { + classpath 'com.github.jengelman.gradle.plugins:shadow:1.2.3' + } +} +group = 'com.intellectualcrafters' +version = '3.2.27' + +description = """PlotSquared""" + +subprojects { + apply plugin: 'java' + apply plugin: 'maven' + apply plugin: 'com.github.johnrengelman.shadow' + dependencies { + compile(group: 'com.sk89q', name: 'worldedit', version:'6.0.0-SNAPSHOT') { + exclude(module: 'bukkit-classloader-check') + } + compile 'org.yaml:snakeyaml:1.16' + } + repositories { + mavenCentral() + maven {url "http://empcraft.com/maven2"} + maven {url "https://hub.spigotmc.org/nexus/content/groups/public/"} + maven {url "http://maven.sk89q.com/repo/"} + maven {url "http://nexus.theyeticave.net/content/repositories/pub_releases"} + maven {url "http://repo.maven.apache.org/maven2"} + } + +} diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..028492f28 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Mon Feb 22 21:55:23 EST 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.11-all.zip diff --git a/gradlew b/gradlew new file mode 100644 index 000000000..9d82f7891 --- /dev/null +++ b/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/pom.xml b/pom.xml deleted file mode 100644 index 92a26264f..000000000 --- a/pom.xml +++ /dev/null @@ -1,330 +0,0 @@ - - - 4.0.0 - - com.intellectualcrafters - plotsquared - 3.2.26 - jar - - PlotSquared - Reinventing the plotworld! - http://www.spigotmc.org/resources/plotsquared.1177/ - - - IntellectualSites - https://github.com/IntellectualSites - - - - scm:git:https://github.com/IntellectualSites/PlotSquared.git - scm:git:git@github.com:IntellectualSites/PlotSquared.git - https://github.com/IntellectualSites/PlotSquared - - - - - jenkins - http://ci.xephi.fr/job/PlotSquared/ - - - - - The GNU General Public Licence version 3 (GPLv3) - http://www.gnu.org/licenses/gpl-3.0.html - - - - - 3.3.3 - - - - UTF-8 - - - 1.7 - - - 1.8.8-R0.1-SNAPSHOT - 3.1.0-SNAPSHOT - - - - ${project.name}-Uber-${project.version} - src/main/java - - - - true - - plugin.yml - - ${basedir}/src/main/resources/ - - - false - - plugin.yml - - ${basedir}/src/main/resources/ - - - - - - - - - maven-jar-plugin - 2.6 - - - bukkit - - jar - - package - - ${project.name}-Bukkit-${project.version} - - **/com/plotsquared/sponge/** - - - - - - sponge - - jar - - package - - ${project.name}-Sponge-${project.version} - - **/com/plotsquared/bukkit/** - **/com/intellectualcrafters/plot/api/* - - - - - - api - - jar - - package - - ${project.name}-API-${project.version} - - **/com/plotsquared/bukkit/** - **/com/plotsquared/sponge/** - **/com/intellectualcrafters/plot/api/* - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.3 - - 1.7 - ${javaVersion} - - - - - - - - - - - - - empcraft-repo - http://empcraft.com/maven2 - - - spigot-repo - https://hub.spigotmc.org/nexus/content/groups/public/ - - - sponge-maven-repo - http://repo.spongepowered.org/maven - - true - - - true - - - - sk89q - http://maven.sk89q.com/repo/ - - - vault-repo - http://nexus.theyeticave.net/content/repositories/pub_releases - - - - - - - - org.bukkit - bukkit - ${bukkitVersion} - provided - true - - - junit - junit - - - - persistence-api - javax.persistence - - - - - - org.spongepowered - spongeapi - ${spongeVersion} - provided - true - - - jsr305 - com.google.code.findbugs - - - - - org.bukkit - bukkit - 1.8.8-R0.1-SNAPSHOT - - - com.sk89q - worldedit - 6.0.0-SNAPSHOT - provided - true - - - truezip - de.schlichtherle - - - js - rhino - - - jsr305 - com.google.code.findbugs - - - guava - com.google.guava - - - - - - - - - - net.milkbowl.vault - VaultAPI - 1.5 - provided - true - - - org.bukkit - bukkit - - - - - - - - - - diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 000000000..78debc8c5 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,4 @@ +rootProject.name = 'PlotSquared' + +include 'Core', 'Bukkit', 'Sponge' +