Reformat code

This commit is contained in:
sauilitired 2018-08-10 17:01:10 +02:00
parent 02ee1e8fa1
commit 1646cd0f5a
437 changed files with 12795 additions and 14203 deletions

View File

@ -1,7 +1,7 @@
repositories {
maven {url "https://hub.spigotmc.org/nexus/content/groups/public/"}
maven { url = "https://oss.sonatype.org/content/repositories/snapshots/"}
maven {url "http://nexus.hc.to/content/repositories/pub_releases"}
maven { url "https://hub.spigotmc.org/nexus/content/groups/public/" }
maven { url = "https://oss.sonatype.org/content/repositories/snapshots/" }
maven { url "http://nexus.hc.to/content/repositories/pub_releases" }
mavenLocal()
}

View File

@ -7,16 +7,8 @@ import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.flag.Flags;
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.Permissions;
import com.intellectualcrafters.plot.util.SchematicHandler;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.object.*;
import com.intellectualcrafters.plot.util.*;
import com.intellectualcrafters.plot.util.block.GlobalBlockQueue;
import com.intellectualcrafters.plot.uuid.UUIDWrapper;
import com.plotsquared.bukkit.util.BukkitUtil;
@ -26,16 +18,11 @@ 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.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.*;
/**
* PlotSquared API.
*
* <p>
* <p>Useful classes:
* <ul>
* <li>{@link BukkitUtil}</li>
@ -45,25 +32,27 @@ import java.util.UUID;
* <li>{@link PlotArea}</li>
* <li>{@link PS}</li>
* </ul>
*
* @version 3.3.3
*/
public class PlotAPI {
/**
* Deprecated, does nothing.
*
* @param plugin not needed
* @deprecated Not needed
*/
@Deprecated
public PlotAPI(JavaPlugin plugin) {}
@Deprecated public PlotAPI(JavaPlugin plugin) {
}
public PlotAPI(){}
public PlotAPI() {
}
/**
* Get all plots.
*
* @return all plots
*
* @see PS#getPlots()
*/
public Set<Plot> getAllPlots() {
@ -74,7 +63,6 @@ public class PlotAPI {
* Return all plots for a player.
*
* @param player Player, whose plots to search for
*
* @return all plots that a player owns
*/
public Set<Plot> getPlayerPlots(Player player) {
@ -93,8 +81,8 @@ public class PlotAPI {
/**
* Returns the PlotSquared configurations file.
* @return main configuration
*
* @return main configuration
* @see PS#config
*/
public YamlConfiguration getConfig() {
@ -103,8 +91,8 @@ public class PlotAPI {
/**
* Get the PlotSquared storage file.
* @return storage configuration
*
* @return storage configuration
* @see PS#storage
*/
public YamlConfiguration getStorage() {
@ -115,7 +103,6 @@ public class PlotAPI {
* Get the main class for this plugin. Only use this if you really need it.
*
* @return PlotSquared PlotSquared Main Class
*
* @see PS
*/
public PS getMain() {
@ -133,7 +120,6 @@ public class PlotAPI {
* </ul>
*
* @return ChunkManager
*
* @see ChunkManager
*/
public ChunkManager getChunkManager() {
@ -142,6 +128,7 @@ public class PlotAPI {
/**
* Get the block/biome set queue
*
* @return GlobalBlockQueue.IMP
*/
public GlobalBlockQueue getBlockQueue() {
@ -153,7 +140,6 @@ public class PlotAPI {
* to use the UUIDHandler class instead.
*
* @return UUIDWrapper
*
* @see UUIDWrapper
*/
public UUIDWrapper getUUIDWrapper() {
@ -165,11 +151,9 @@ public class PlotAPI {
* - Flag related stuff
*
* @return FlagManager
*
* @deprecated Use {@link FlagManager} directly
*/
@Deprecated
public FlagManager getFlagManager() {
@Deprecated public FlagManager getFlagManager() {
return new FlagManager();
}
@ -179,8 +163,7 @@ public class PlotAPI {
* @return MainUtil
* @deprecated Use {@link MainUtil} directly
*/
@Deprecated
public MainUtil getMainUtil() {
@Deprecated public MainUtil getMainUtil() {
return new MainUtil();
}
@ -188,12 +171,10 @@ public class PlotAPI {
* Do not use this. Instead use C.PERMISSION_[method] in your code.
*
* @return Array of strings
*
* @see Permissions
* @deprecated Use {@link C} to list all the permissions
*/
@Deprecated
public String[] getPermissions() {
@Deprecated public String[] getPermissions() {
ArrayList<String> perms = new ArrayList<>();
for (C caption : C.values()) {
if ("static.permissions".equals(caption.getCategory())) {
@ -208,7 +189,6 @@ public class PlotAPI {
* and writing schematics.
*
* @return SchematicHandler
*
* @see SchematicHandler
*/
public SchematicHandler getSchematicHandler() {
@ -221,8 +201,7 @@ public class PlotAPI {
* @return C
* @deprecated Use {@link C}
*/
@Deprecated
public C[] getCaptions() {
@Deprecated public C[] getCaptions() {
return C.values();
}
@ -231,15 +210,11 @@ public class PlotAPI {
* through the MainUtil.
*
* @param world the world to retrieve the manager from
*
* @return PlotManager
*
* @see PlotManager
* @see PS#getPlotManager(Plot)
*/
@SuppressWarnings("deprecation")
@Deprecated
public PlotManager getPlotManager(World world) {
@SuppressWarnings("deprecation") @Deprecated public PlotManager getPlotManager(World world) {
if (world == null) {
return null;
}
@ -248,6 +223,7 @@ public class PlotAPI {
/**
* Get a list of PlotAreas in the world.
*
* @param world The world to check for plot areas
* @return A set of PlotAreas
*/
@ -263,14 +239,11 @@ public class PlotAPI {
* plot merging, clearing, and tessellation.
*
* @param world The world
*
* @return PlotManager
*
* @see PS#getPlotManager(Plot)
* @see PlotManager
*/
@Deprecated
public PlotManager getPlotManager(String world) {
@Deprecated public PlotManager getPlotManager(String world) {
Set<PlotArea> areas = PS.get().getPlotAreas(world);
switch (areas.size()) {
case 0:
@ -278,7 +251,8 @@ public class PlotAPI {
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.");
PS.debug(
"PlotAPI#getPlotManager(org.bukkit.World) is deprecated and doesn't support multi plot area worlds.");
return null;
}
}
@ -289,15 +263,11 @@ public class PlotAPI {
* DefaultPlotWorld class implements PlotArea
*
* @param world The World
*
* @return The {@link PlotArea} for the world or null if not in plotworld
*
* @see #getPlotAreas(World)
* @see PlotArea
*/
@SuppressWarnings("deprecation")
@Deprecated
public PlotArea getWorldSettings(World world) {
@SuppressWarnings("deprecation") @Deprecated public PlotArea getWorldSettings(World world) {
if (world == null) {
return null;
}
@ -308,14 +278,11 @@ public class PlotAPI {
* Get the settings for a world.
*
* @param world the world to retrieve settings from
*
* @return The {@link PlotArea} for the world or null if not in plotworld
*
* @see PS#getPlotArea(String, String)
* @see PlotArea
*/
@Deprecated
public PlotArea getWorldSettings(String world) {
@Deprecated public PlotArea getWorldSettings(String world) {
if (world == null) {
return null;
}
@ -326,7 +293,8 @@ public class PlotAPI {
case 1:
return areas.iterator().next();
default:
PS.debug("PlotAPI#getWorldSettings(org.bukkit.World) is deprecated and doesn't support multi plot area worlds.");
PS.debug(
"PlotAPI#getWorldSettings(org.bukkit.World) is deprecated and doesn't support multi plot area worlds.");
return null;
}
}
@ -336,7 +304,6 @@ public class PlotAPI {
*
* @param player the recipient of the message
* @param caption the message
*
* @see MainUtil#sendMessage(PlotPlayer, C, String...)
*/
public void sendMessage(Player player, C caption) {
@ -348,7 +315,6 @@ public class PlotAPI {
*
* @param player the recipient of the message
* @param string the message
*
* @see MainUtil#sendMessage(PlotPlayer, String)
*/
public void sendMessage(Player player, String string) {
@ -359,7 +325,6 @@ public class PlotAPI {
* Send a message to the console. The message supports color codes.
*
* @param message the message
*
* @see MainUtil#sendConsoleMessage(C, String...)
*/
public void sendConsoleMessage(String message) {
@ -370,7 +335,6 @@ public class PlotAPI {
* Send a message to the console.
*
* @param caption the message
*
* @see #sendConsoleMessage(String)
* @see C
*/
@ -382,7 +346,6 @@ public class PlotAPI {
* Registers a flag for use in plots.
*
* @param flag the flag to register
*
*/
public void addFlag(Flag<?> flag) {
Flags.registerFlag(flag);
@ -394,14 +357,10 @@ public class PlotAPI {
* @param world the world the plot is located in
* @param x The PlotID x coordinate
* @param z The PlotID y coordinate
*
* @return plot, null if ID is wrong
*
* @see PlotArea#getPlot(PlotId)
*/
@SuppressWarnings("deprecation")
@Deprecated
public Plot getPlot(World world, int x, int z) {
@SuppressWarnings("deprecation") @Deprecated public Plot getPlot(World world, int x, int z) {
if (world == null) {
return null;
}
@ -416,9 +375,7 @@ public class PlotAPI {
* Get a plot based on the location.
*
* @param location the location to check
*
* @return plot if found, otherwise it creates a temporary plot
*
* @see Plot
*/
public Plot getPlot(Location location) {
@ -432,9 +389,7 @@ public class PlotAPI {
* Get a plot based on the player location.
*
* @param player the player to check
*
* @return plot if found, otherwise it creates a temporary plot
*
* @see #getPlot(Location)
* @see Plot
*/
@ -448,12 +403,10 @@ public class PlotAPI {
* @param player Player that you want to check for
* @param world The world to check
* @return true if player has a plot, false if not.
*
* @see #getPlots(World, Player, boolean)
*/
@SuppressWarnings("deprecation")
@Deprecated
public boolean hasPlot(World world, Player player) {
@SuppressWarnings("deprecation") @Deprecated public boolean hasPlot(World world,
Player player) {
return getPlots(world, player, true).length > 0;
}
@ -465,8 +418,7 @@ public class PlotAPI {
* @param justOwner should we just search for owner? Or with rights?
* @return An array of plots for the player
*/
@Deprecated
public Plot[] getPlots(World world, Player player, boolean justOwner) {
@Deprecated public Plot[] getPlots(World world, Player player, boolean justOwner) {
ArrayList<Plot> pPlots = new ArrayList<>();
UUID uuid = BukkitUtil.getPlayer(player).getUUID();
for (Plot plot : PS.get().getPlots(world.getName())) {
@ -485,14 +437,11 @@ public class PlotAPI {
* 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(World world) {
@Deprecated public Plot[] getPlots(World world) {
if (world == null) {
return new Plot[0];
}
@ -504,11 +453,8 @@ public class PlotAPI {
* Get all plot worlds.
*
* @return World[] - array of plot worlds
*
*/
@SuppressWarnings("deprecation")
@Deprecated
public String[] getPlotWorlds() {
@SuppressWarnings("deprecation") @Deprecated public String[] getPlotWorlds() {
Set<String> plotWorldStrings = PS.get().getPlotWorldStrings();
return plotWorldStrings.toArray(new String[plotWorldStrings.size()]);
}
@ -517,13 +463,10 @@ public class PlotAPI {
* Get if plotworld.
*
* @param world The world to check
*
* @return boolean (if plot world or not)
*
* @see PS#hasPlotArea(String)
*/
@Deprecated
public boolean isPlotWorld(World world) {
@Deprecated public boolean isPlotWorld(World world) {
return PS.get().hasPlotArea(world.getName());
}
@ -531,29 +474,22 @@ public class PlotAPI {
* Get plot locations.
*
* @param plot Plot 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 As merged plots may not have a rectangular shape
*/
@SuppressWarnings("deprecation")
@Deprecated
public Location[] getLocations(Plot plot) {
@SuppressWarnings("deprecation") @Deprecated public Location[] getLocations(Plot plot) {
Location bukkitBottom = BukkitUtil.getLocation(plot.getCorners()[0]);
Location bukkitTop = BukkitUtil.getLocation(plot.getCorners()[1]);
Location bukkitHome = BukkitUtil.getLocation(plot.getHome());
return new Location[]{bukkitBottom, bukkitTop, bukkitHome};
return new Location[] {bukkitBottom, bukkitTop, bukkitHome};
}
/**
* Get home location.
*
* @param plot Plot that you want to get the location for
*
* @return plot bottom location
*
* @see Plot
*/
public Location getHomeLocation(Plot plot) {
@ -564,16 +500,11 @@ public class PlotAPI {
* Get Bottom Location (min, min, min).
*
* @param plot 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 As merged plots may not have a rectangular shape
*/
@SuppressWarnings("deprecation")
@Deprecated
public Location getBottomLocation(Plot plot) {
@SuppressWarnings("deprecation") @Deprecated public Location getBottomLocation(Plot plot) {
return BukkitUtil.getLocation(plot.getCorners()[0]);
}
@ -581,16 +512,11 @@ public class PlotAPI {
* Get Top Location (max, max, max).
*
* @param plot 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 As merged plots may not have a rectangular shape
*/
@SuppressWarnings("deprecation")
@Deprecated
public Location getTopLocation(Plot plot) {
@SuppressWarnings("deprecation") @Deprecated public Location getTopLocation(Plot plot) {
return BukkitUtil.getLocation(plot.getCorners()[1]);
}
@ -598,9 +524,7 @@ public class PlotAPI {
* 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(Player player) {
return getPlot(player) != null;
@ -608,12 +532,12 @@ public class PlotAPI {
/**
* Register a subcommand.
* @deprecated Command registration is done on object creation
*
* @param c SubCommand, that we want to register
* @see SubCommand
* @deprecated Command registration is done on object creation
*/
@Deprecated
public void registerCommand(SubCommand c) {
@Deprecated public void registerCommand(SubCommand c) {
PS.debug("SubCommands are now registered on creation");
}
@ -621,7 +545,6 @@ public class PlotAPI {
* Gets the PlotSquared class.
*
* @return PlotSquared Class
*
* @see PS
*/
public PS getPlotSquared() {
@ -633,9 +556,7 @@ public class PlotAPI {
*
* @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(World world, Player player) {
if (world == null) {
@ -649,11 +570,8 @@ public class PlotAPI {
*
* @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<Plot> getPlayerPlots(World world, Player player) {
@ -667,9 +585,7 @@ public class PlotAPI {
* Gets the number of plots, which the player is able to build in.
*
* @param player player, for whom we're getting the plots
*
* @return the number of allowed plots
*
*/
public int getAllowedPlots(Player player) {
PlotPlayer plotPlayer = PlotPlayer.wrap(player);
@ -680,10 +596,9 @@ public class PlotAPI {
* Gets the PlotPlayer for a player. The PlotPlayer is usually cached and
* will provide useful functions relating to players.
*
* @see PlotPlayer#wrap(Object)
*
* @param player the player to wrap
* @return a {@code PlotPlayer}
* @see PlotPlayer#wrap(Object)
*/
public PlotPlayer wrapPlayer(Player player) {
return PlotPlayer.wrap(player);
@ -691,14 +606,13 @@ public class PlotAPI {
/**
* Get the PlotPlayer for a UUID.
*
* <p>
* <p><i>Please note that PlotSquared can be configured to provide
* different UUIDs than bukkit</i>
*
* @see PlotPlayer#wrap(Object)
*
* @param uuid the uuid of the player to wrap
* @return a {@code PlotPlayer}
* @see PlotPlayer#wrap(Object)
*/
public PlotPlayer wrapPlayer(UUID uuid) {
return PlotPlayer.wrap(uuid);
@ -707,10 +621,9 @@ public class PlotAPI {
/**
* Get the PlotPlayer for a username.
*
* @see PlotPlayer#wrap(Object)
*
* @param player the player to wrap
* @return a {@code PlotPlayer}
* @see PlotPlayer#wrap(Object)
*/
public PlotPlayer wrapPlayer(String player) {
return PlotPlayer.wrap(player);
@ -718,14 +631,13 @@ public class PlotAPI {
/**
* Get the PlotPlayer for an offline player.
*
* <p>
* <p>Note that this will work if the player is offline, however not all
* functionality will work.
*
* @see PlotPlayer#wrap(Object)
*
* @param player the player to wrap
* @return a {@code PlotPlayer}
* @see PlotPlayer#wrap(Object)
*/
public PlotPlayer wrapPlayer(OfflinePlayer player) {
return PlotPlayer.wrap(player);

View File

@ -1,7 +1,5 @@
package com.plotsquared.bukkit;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
import com.intellectualcrafters.configuration.ConfigurationSection;
import com.intellectualcrafters.plot.IPlotMain;
import com.intellectualcrafters.plot.PS;
@ -12,89 +10,27 @@ import com.intellectualcrafters.plot.generator.GeneratorWrapper;
import com.intellectualcrafters.plot.generator.HybridGen;
import com.intellectualcrafters.plot.generator.HybridUtils;
import com.intellectualcrafters.plot.generator.IndependentPlotGenerator;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.object.SetupObject;
import com.intellectualcrafters.plot.object.*;
import com.intellectualcrafters.plot.object.chat.PlainChatManager;
import com.intellectualcrafters.plot.object.worlds.PlotAreaManager;
import com.intellectualcrafters.plot.object.worlds.SinglePlotArea;
import com.intellectualcrafters.plot.object.worlds.SinglePlotAreaManager;
import com.intellectualcrafters.plot.object.worlds.SingleWorldGenerator;
import com.intellectualcrafters.plot.util.AbstractTitle;
import com.intellectualcrafters.plot.util.ChatManager;
import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.ConsoleColors;
import com.intellectualcrafters.plot.util.EconHandler;
import com.intellectualcrafters.plot.util.EventUtil;
import com.intellectualcrafters.plot.util.InventoryUtil;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.ReflectionUtils;
import com.intellectualcrafters.plot.util.SchematicHandler;
import com.intellectualcrafters.plot.util.SetupUtils;
import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.util.UUIDHandlerImplementation;
import com.intellectualcrafters.plot.util.WorldUtil;
import com.intellectualcrafters.plot.util.*;
import com.intellectualcrafters.plot.util.block.QueueProvider;
import com.intellectualcrafters.plot.uuid.UUIDWrapper;
import com.plotsquared.bukkit.database.plotme.ClassicPlotMeConnector;
import com.plotsquared.bukkit.database.plotme.LikePlotMeConverter;
import com.plotsquared.bukkit.database.plotme.PlotMeConnector_017;
import com.plotsquared.bukkit.generator.BukkitPlotGenerator;
import com.plotsquared.bukkit.listeners.ChunkListener;
import com.plotsquared.bukkit.listeners.EntityPortal_1_7_9;
import com.plotsquared.bukkit.listeners.EntitySpawnListener;
import com.plotsquared.bukkit.listeners.PlayerEvents;
import com.plotsquared.bukkit.listeners.PlayerEvents183;
import com.plotsquared.bukkit.listeners.PlayerEvents_1_8;
import com.plotsquared.bukkit.listeners.PlayerEvents_1_9;
import com.plotsquared.bukkit.listeners.PlotPlusListener;
import com.plotsquared.bukkit.listeners.PlotPlusListener_1_12;
import com.plotsquared.bukkit.listeners.PlotPlusListener_Legacy;
import com.plotsquared.bukkit.listeners.SingleWorldListener;
import com.plotsquared.bukkit.listeners.WorldEvents;
import com.plotsquared.bukkit.listeners.*;
import com.plotsquared.bukkit.titles.DefaultTitle_111;
import com.plotsquared.bukkit.util.BukkitChatManager;
import com.plotsquared.bukkit.util.BukkitChunkManager;
import com.plotsquared.bukkit.util.BukkitCommand;
import com.plotsquared.bukkit.util.BukkitEconHandler;
import com.plotsquared.bukkit.util.BukkitEventUtil;
import com.plotsquared.bukkit.util.BukkitHybridUtils;
import com.plotsquared.bukkit.util.BukkitInventoryUtil;
import com.plotsquared.bukkit.util.BukkitSchematicHandler;
import com.plotsquared.bukkit.util.BukkitSetupUtils;
import com.plotsquared.bukkit.util.BukkitTaskManager;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.bukkit.util.BukkitVersion;
import com.plotsquared.bukkit.util.Metrics;
import com.plotsquared.bukkit.util.SendChunk;
import com.plotsquared.bukkit.util.SetGenCB;
import com.plotsquared.bukkit.util.block.BukkitLocalQueue;
import com.plotsquared.bukkit.util.block.BukkitLocalQueue_1_7;
import com.plotsquared.bukkit.util.block.BukkitLocalQueue_1_8;
import com.plotsquared.bukkit.util.block.BukkitLocalQueue_1_8_3;
import com.plotsquared.bukkit.util.block.BukkitLocalQueue_1_9;
import com.plotsquared.bukkit.uuid.DefaultUUIDWrapper;
import com.plotsquared.bukkit.uuid.FileUUIDHandler;
import com.plotsquared.bukkit.uuid.LowerOfflineUUIDWrapper;
import com.plotsquared.bukkit.uuid.OfflineUUIDWrapper;
import com.plotsquared.bukkit.uuid.SQLUUIDHandler;
import com.plotsquared.bukkit.util.*;
import com.plotsquared.bukkit.util.block.*;
import com.plotsquared.bukkit.uuid.*;
import com.sk89q.worldedit.WorldEdit;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Chunk;
import org.bukkit.*;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.command.PluginCommand;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
@ -107,8 +43,17 @@ import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
public static WorldEdit worldEdit;
private static ConcurrentHashMap<String, Plugin> pluginMap;
static {
@ -128,14 +73,15 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
iter.remove();
}
}
Map<String, Plugin> lookupNames = (Map<String, Plugin>) lookupNamesField.get(manager);
Map<String, Plugin> lookupNames =
(Map<String, Plugin>) lookupNamesField.get(manager);
lookupNames.remove("PlotMe");
lookupNames.remove("PlotMe-DefaultGenerator");
pluginsField.set(manager, new ArrayList<Plugin>(plugins) {
@Override
public boolean add(Plugin plugin) {
@Override public boolean add(Plugin plugin) {
if (plugin.getName().startsWith("PlotMe")) {
System.out.print("Disabling `" + plugin.getName() + "` for PlotMe conversion (configure in PlotSquared settings.yml)");
System.out.print("Disabling `" + plugin.getName()
+ "` for PlotMe conversion (configure in PlotSquared settings.yml)");
} else {
return super.add(plugin);
}
@ -143,8 +89,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
}
});
pluginMap = new ConcurrentHashMap<String, Plugin>(lookupNames) {
@Override
public Plugin put(String key, Plugin plugin) {
@Override public Plugin put(String key, Plugin plugin) {
if (!plugin.getName().startsWith("PlotMe")) {
return super.put(key, plugin);
}
@ -153,17 +98,17 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
};
lookupNamesField.set(manager, pluginMap);
}
} catch (Throwable ignore) {}
} catch (Throwable ignore) {
}
}
public static WorldEdit worldEdit;
private int[] version;
private String name;
private SingleWorldListener singleWorldListener;
private Method methodUnloadChunk0;
private boolean methodUnloadSetup = false;
@Override
public int[] getServerVersion() {
@Override public int[] getServerVersion() {
if (this.version == null) {
try {
this.version = new int[3];
@ -177,14 +122,13 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
e.printStackTrace();
PS.debug(StringMan.getString(Bukkit.getBukkitVersion()));
PS.debug(StringMan.getString(Bukkit.getBukkitVersion().split("-")[0].split("\\.")));
return new int[]{1, 13, 0};
return new int[] {1, 13, 0};
}
}
return this.version;
}
@Override
public void onEnable() {
@Override public void onEnable() {
if (pluginMap != null) {
pluginMap.put("PlotMe-DefaultGenerator", this);
}
@ -199,8 +143,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
}
if (Settings.Enabled_Components.WORLDS) {
TaskManager.IMP.taskRepeat(new Runnable() {
@Override
public void run() {
@Override public void run() {
unload();
}
}, 20);
@ -216,15 +159,13 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
return singleWorldListener;
}
private Method methodUnloadChunk0;
private boolean methodUnloadSetup = false;
public void unload() {
if (!methodUnloadSetup) {
methodUnloadSetup = true;
try {
ReflectionUtils.RefClass classCraftWorld = getRefClass("{cb}.CraftWorld");
methodUnloadChunk0 = classCraftWorld.getRealClass().getDeclaredMethod("unloadChunk0", int.class, int.class, boolean.class);
methodUnloadChunk0 = classCraftWorld.getRealClass()
.getDeclaredMethod("unloadChunk0", int.class, int.class, boolean.class);
methodUnloadChunk0.setAccessible(true);
} catch (Throwable ignore) {
ignore.printStackTrace();
@ -238,7 +179,8 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
for (World world : Bukkit.getWorlds()) {
String name = world.getName();
char char0 = name.charAt(0);
if (!Character.isDigit(char0) && char0 != '-') continue;
if (!Character.isDigit(char0) && char0 != '-')
continue;
if (!world.getPlayers().isEmpty()) {
continue;
}
@ -265,19 +207,22 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
boolean result;
if (methodUnloadChunk0 != null) {
try {
result = (boolean) methodUnloadChunk0.invoke(world, chunkI.getX(), chunkI.getZ(), true);
result = (boolean) methodUnloadChunk0
.invoke(world, chunkI.getX(), chunkI.getZ(), true);
} catch (Throwable e) {
methodUnloadChunk0 = null;
e.printStackTrace();
continue outer;
}
} else {
result = world.unloadChunk(chunkI.getX(), chunkI.getZ(), true, false);
result = world
.unloadChunk(chunkI.getX(), chunkI.getZ(), true, false);
}
if (!result) {
continue outer;
}
} while (index < chunks.length && System.currentTimeMillis() - start < 5);
} while (index < chunks.length
&& System.currentTimeMillis() - start < 5);
return;
}
}
@ -287,14 +232,12 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
}
}
@Override
public void onDisable() {
@Override public void onDisable() {
PS.get().disable();
Bukkit.getScheduler().cancelTasks(this);
}
@Override
public void log(String message) {
@Override public void log(String message) {
try {
message = C.color(message);
if (!Settings.Chat.CONSOLE_COLOR) {
@ -306,32 +249,29 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
}
}
@Override
public void disable() {
@Override public void disable() {
onDisable();
}
@Override
public int[] getPluginVersion() {
@Override public int[] getPluginVersion() {
String ver = getDescription().getVersion();
if (ver.contains("-")) {
ver = ver.split("-")[0];
}
String[] split = ver.split("\\.");
return new int[]{Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2])};
return new int[] {Integer.parseInt(split[0]), Integer.parseInt(split[1]),
Integer.parseInt(split[2])};
}
@Override public String getPluginVersionString() {
return getDescription().getVersion();
}
@Override
public String getPluginName() {
@Override public String getPluginName() {
return name;
}
@Override
public void registerCommands() {
@Override public void registerCommands() {
BukkitCommand bukkitCommand = new BukkitCommand();
PluginCommand plotCommand = getCommand("plots");
plotCommand.setExecutor(bukkitCommand);
@ -339,30 +279,24 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
plotCommand.setTabCompleter(bukkitCommand);
}
@Override
public File getDirectory() {
@Override public File getDirectory() {
return getDataFolder();
}
@Override
public File getWorldContainer() {
@Override public File getWorldContainer() {
return Bukkit.getWorldContainer();
}
@Override
public TaskManager getTaskManager() {
@Override public TaskManager getTaskManager() {
return new BukkitTaskManager(this);
}
@Override
public void runEntityTask() {
@Override public void runEntityTask() {
PS.log(C.PREFIX + "KillAllEntities started.");
TaskManager.runTaskRepeat(new Runnable() {
@Override
public void run() {
@Override public void run() {
PS.get().foreachPlotArea(new RunnableVal<PlotArea>() {
@Override
public void run(PlotArea plotArea) {
@Override public void run(PlotArea plotArea) {
World world = Bukkit.getWorld(plotArea.worldname);
try {
if (world == null) {
@ -416,7 +350,8 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
case MINECART_TNT:
case BOAT:
if (Settings.Enabled_Components.KILL_ROAD_VEHICLES) {
com.intellectualcrafters.plot.object.Location location = BukkitUtil.getLocation(entity.getLocation());
com.intellectualcrafters.plot.object.Location location =
BukkitUtil.getLocation(entity.getLocation());
Plot plot = location.getPlot();
if (plot == null) {
if (location.isPlotArea()) {
@ -503,10 +438,13 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
Location location = entity.getLocation();
if (BukkitUtil.getLocation(location).isPlotRoad()) {
if (entity instanceof LivingEntity) {
LivingEntity livingEntity = (LivingEntity) entity;
if (!livingEntity.isLeashed() || !entity.hasMetadata("keep")) {
LivingEntity livingEntity =
(LivingEntity) entity;
if (!livingEntity.isLeashed() || !entity
.hasMetadata("keep")) {
Entity passenger = entity.getPassenger();
if (!(passenger instanceof Player) && entity.getMetadata("keep").isEmpty()) {
if (!(passenger instanceof Player) && entity
.getMetadata("keep").isEmpty()) {
iterator.remove();
entity.remove();
continue;
@ -514,7 +452,8 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
}
} else {
Entity passenger = entity.getPassenger();
if (!(passenger instanceof Player) && entity.getMetadata("keep").isEmpty()) {
if (!(passenger instanceof Player) && entity
.getMetadata("keep").isEmpty()) {
iterator.remove();
entity.remove();
continue;
@ -529,18 +468,28 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
LivingEntity livingEntity = (LivingEntity) entity;
List<MetadataValue> meta = entity.getMetadata("plot");
if (meta != null && !meta.isEmpty()) {
if (livingEntity.isLeashed()) continue;
if (livingEntity.isLeashed())
continue;
List<MetadataValue> keep = entity.getMetadata("keep");
if (keep != null && !keep.isEmpty()) continue;
List<MetadataValue> keep =
entity.getMetadata("keep");
if (keep != null && !keep.isEmpty())
continue;
PlotId originalPlotId = (PlotId) meta.get(0).value();
PlotId originalPlotId =
(PlotId) meta.get(0).value();
if (originalPlotId != null) {
com.intellectualcrafters.plot.object.Location pLoc = BukkitUtil.getLocation(entity.getLocation());
com.intellectualcrafters.plot.object.Location
pLoc = BukkitUtil
.getLocation(entity.getLocation());
PlotArea area = pLoc.getPlotArea();
if (area != null) {
PlotId currentPlotId = PlotId.of(area.getPlotAbs(pLoc));
if (!originalPlotId.equals(currentPlotId) && (currentPlotId == null || !area.getPlot(originalPlotId).equals(area.getPlot(currentPlotId)))) {
PlotId currentPlotId =
PlotId.of(area.getPlotAbs(pLoc));
if (!originalPlotId.equals(currentPlotId)
&& (currentPlotId == null || !area
.getPlot(originalPlotId)
.equals(area.getPlot(currentPlotId)))) {
iterator.remove();
entity.remove();
}
@ -548,12 +497,17 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
}
} else {
//This is to apply the metadata to already spawned shulkers (see EntitySpawnListener.java)
com.intellectualcrafters.plot.object.Location pLoc = BukkitUtil.getLocation(entity.getLocation());
com.intellectualcrafters.plot.object.Location pLoc =
BukkitUtil.getLocation(entity.getLocation());
PlotArea area = pLoc.getPlotArea();
if (area != null) {
PlotId currentPlotId = PlotId.of(area.getPlotAbs(pLoc));
PlotId currentPlotId =
PlotId.of(area.getPlotAbs(pLoc));
if (currentPlotId != null) {
entity.setMetadata("plot", new FixedMetadataValue((Plugin) PS.get().IMP, currentPlotId));
entity.setMetadata("plot",
new FixedMetadataValue(
(Plugin) PS.get().IMP,
currentPlotId));
}
}
}
@ -571,8 +525,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
}, 20);
}
@Override
public final ChunkGenerator getDefaultWorldGenerator(String world, String id) {
@Override public final ChunkGenerator getDefaultWorldGenerator(String world, String id) {
if (Settings.Enabled_Components.PLOTME_CONVERTER) {
initPlotMeConverter();
Settings.Enabled_Components.PLOTME_CONVERTER = false;
@ -589,8 +542,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
return (ChunkGenerator) result.specify(world);
}
@Override
public void registerPlayerEvents() {
@Override public void registerPlayerEvents() {
PlayerEvents main = new PlayerEvents();
getServer().getPluginManager().registerEvents(main, this);
try {
@ -630,13 +582,11 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
}
}
@Override
public void registerInventoryEvents() {
@Override public void registerInventoryEvents() {
// Part of PlayerEvents - can be moved if necessary
}
@Override
public void registerPlotPlusEvents() {
@Override public void registerPlotPlusEvents() {
PlotPlusListener.startRunnable(this);
getServer().getPluginManager().registerEvents(new PlotPlusListener(), this);
if (PS.get().checkVersion(getServerVersion(), BukkitVersion.v1_12_0)) {
@ -646,12 +596,10 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
}
}
@Override
public void registerForceFieldEvents() {
@Override public void registerForceFieldEvents() {
}
@Override
public boolean initWorldEdit() {
@Override public boolean initWorldEdit() {
if (getServer().getPluginManager().getPlugin("WorldEdit") != null) {
worldEdit = WorldEdit.getInstance();
return true;
@ -659,8 +607,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
return false;
}
@Override
public EconHandler getEconomyHandler() {
@Override public EconHandler getEconomyHandler() {
try {
BukkitEconHandler econ = new BukkitEconHandler();
if (econ.init()) {
@ -672,13 +619,13 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
return null;
}
@Override
public QueueProvider initBlockQueue() {
@Override public QueueProvider initBlockQueue() {
try {
new SendChunk();
MainUtil.canSendChunk = true;
} catch (ClassNotFoundException | NoSuchFieldException | NoSuchMethodException e) {
PS.debug(SendChunk.class + " does not support " + StringMan.getString(getServerVersion()));
PS.debug(
SendChunk.class + " does not support " + StringMan.getString(getServerVersion()));
MainUtil.canSendChunk = false;
}
if (PS.get().checkVersion(getServerVersion(), BukkitVersion.v1_13_0)) {
@ -696,13 +643,11 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
return QueueProvider.of(BukkitLocalQueue_1_7.class, BukkitLocalQueue.class);
}
@Override
public WorldUtil initWorldUtil() {
@Override public WorldUtil initWorldUtil() {
return new BukkitUtil();
}
@Override
public boolean initPlotMeConverter() {
@Override public boolean initPlotMeConverter() {
if (new LikePlotMeConverter("PlotMe").run(new ClassicPlotMeConnector())) {
return true;
} else if (new LikePlotMeConverter("PlotMe").run(new PlotMeConnector_017())) {
@ -711,8 +656,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
return false;
}
@Override
public GeneratorWrapper<?> getGenerator(String world, String name) {
@Override public GeneratorWrapper<?> getGenerator(String world, String name) {
if (name == null) {
return null;
}
@ -728,23 +672,21 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
}
}
@Override
public HybridUtils initHybridUtils() {
@Override public HybridUtils initHybridUtils() {
return new BukkitHybridUtils();
}
@Override
public SetupUtils initSetupUtils() {
@Override public SetupUtils initSetupUtils() {
return new BukkitSetupUtils();
}
@Override
public UUIDHandlerImplementation initUUIDHandler() {
@Override public UUIDHandlerImplementation initUUIDHandler() {
boolean checkVersion = false;
try {
OfflinePlayer.class.getDeclaredMethod("getUniqueId");
checkVersion = true;
} catch (Throwable ignore) {}
} catch (Throwable ignore) {
}
UUIDWrapper wrapper;
if (Settings.UUID.OFFLINE) {
if (Settings.UUID.FORCE_LOWERCASE) {
@ -765,17 +707,19 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
Settings.UUID.OFFLINE = true;
}
if (!checkVersion) {
PS.log(C.PREFIX + " &c[WARN] Titles are disabled - please update your version of Bukkit to support this feature.");
PS.log(C.PREFIX
+ " &c[WARN] Titles are disabled - please update your version of Bukkit to support this feature.");
Settings.TITLES = false;
} else {
AbstractTitle.TITLE_CLASS = new DefaultTitle_111();
if (wrapper instanceof DefaultUUIDWrapper || wrapper.getClass() == OfflineUUIDWrapper.class && !Bukkit.getOnlineMode()) {
if (wrapper instanceof DefaultUUIDWrapper
|| wrapper.getClass() == OfflineUUIDWrapper.class && !Bukkit.getOnlineMode()) {
Settings.UUID.NATIVE_UUID_PROVIDER = true;
}
}
if (Settings.UUID.OFFLINE) {
PS.log(C.PREFIX
+ " &6" + getPluginName() + " is using Offline Mode UUIDs either because of user preference, or because you are using an old version of "
PS.log(C.PREFIX + " &6" + getPluginName()
+ " is using Offline Mode UUIDs either because of user preference, or because you are using an old version of "
+ "Bukkit");
} else {
PS.log(C.PREFIX + " &6" + getPluginName() + " is using online UUIDs");
@ -787,53 +731,45 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
}
}
@Override
public ChunkManager initChunkManager() {
@Override public ChunkManager initChunkManager() {
return new BukkitChunkManager();
}
@Override
public EventUtil initEventUtil() {
@Override public EventUtil initEventUtil() {
return new BukkitEventUtil();
}
@Override
public void unregister(PlotPlayer player) {
@Override public void unregister(PlotPlayer player) {
BukkitUtil.removePlayer(player.getName());
}
@Override
public void registerChunkProcessor() {
@Override public void registerChunkProcessor() {
getServer().getPluginManager().registerEvents(new ChunkListener(), this);
}
@Override
public void registerWorldEvents() {
@Override public void registerWorldEvents() {
getServer().getPluginManager().registerEvents(new WorldEvents(), this);
}
@Override
public IndependentPlotGenerator getDefaultGenerator() {
@Override public IndependentPlotGenerator getDefaultGenerator() {
return new HybridGen();
}
@Override
public InventoryUtil initInventoryUtil() {
@Override public InventoryUtil initInventoryUtil() {
return new BukkitInventoryUtil();
}
@Override
public void startMetrics() {
@Override public void startMetrics() {
new Metrics(this).start();
PS.log(C.PREFIX + "&6Metrics enabled.");
}
@Override
public void setGenerator(String worldName) {
@Override public void setGenerator(String worldName) {
World world = BukkitUtil.getWorld(worldName);
if (world == null) {
// create world
ConfigurationSection worldConfig = PS.get().worlds.getConfigurationSection("worlds." + worldName);
ConfigurationSection worldConfig =
PS.get().worlds.getConfigurationSection("worlds." + worldName);
String manager = worldConfig.getString("generator.plugin", getPluginName());
SetupObject setup = new SetupObject();
setup.plotManager = manager;
@ -865,19 +801,16 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
}
}
@Override
public SchematicHandler initSchematicHandler() {
@Override public SchematicHandler initSchematicHandler() {
return new BukkitSchematicHandler();
}
@Override
public AbstractTitle initTitleManager() {
@Override public AbstractTitle initTitleManager() {
// Already initialized in UUID handler
return AbstractTitle.TITLE_CLASS;
}
@Override
public PlotPlayer wrapPlayer(Object player) {
@Override public PlotPlayer wrapPlayer(Object player) {
if (player instanceof Player) {
return BukkitUtil.getPlayer((Player) player);
}
@ -893,14 +826,12 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
return null;
}
@Override
public String getNMSPackage() {
@Override public String getNMSPackage() {
String name = Bukkit.getServer().getClass().getPackage().getName();
return name.substring(name.lastIndexOf('.') + 1);
}
@Override
public ChatManager<?> initChatManager() {
@Override public ChatManager<?> initChatManager() {
if (Settings.Chat.INTERACTIVE) {
return new BukkitChatManager();
} else {
@ -913,11 +844,11 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
return new BukkitPlotGenerator(generator);
}
@Override
public List<String> getPluginIds() {
@Override public List<String> getPluginIds() {
ArrayList<String> names = new ArrayList<>();
for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
names.add(plugin.getName() + ';' + plugin.getDescription().getVersion() + ':' + plugin.isEnabled());
names.add(plugin.getName() + ';' + plugin.getDescription().getVersion() + ':' + plugin
.isEnabled());
}
return names;
}

View File

@ -19,6 +19,8 @@ import java.util.Collection;
*/
public final class ArrayWrapper<E> {
private E[] _array;
/**
* Creates an array wrapper with some elements.
*
@ -28,7 +30,38 @@ public final class ArrayWrapper<E> {
setArray(elements);
}
private E[] _array;
/**
* Converts an iterable element collection to an array of elements.
* The iteration order of the specified object will be used as the array element order.
*
* @param list The iterable of objects which will be converted to an array.
* @param c The type of the elements of the array.
* @return An array of elements in the specified iterable.
*/
@SuppressWarnings("unchecked") public static <T> T[] toArray(Iterable<? extends T> list,
Class<T> c) {
int size = -1;
if (list instanceof Collection<?>) {
@SuppressWarnings("rawtypes") Collection coll = (Collection) list;
size = coll.size();
}
if (size < 0) {
size = 0;
// Ugly hack: Count it ourselves
for (@SuppressWarnings("unused") T element : list) {
size++;
}
}
T[] result = (T[]) Array.newInstance(c, size);
int i = 0;
for (T element : list) { // Assumes iteration order is consistent
result[i++] = element; // Assign array element at index THEN increment counter
}
return result;
}
/**
* Retrieves a reference to the wrapped array instance.
@ -54,9 +87,7 @@ public final class ArrayWrapper<E> {
*
* @see Arrays#equals(Object[], Object[])
*/
@SuppressWarnings("rawtypes")
@Override
public boolean equals(Object other) {
@SuppressWarnings("rawtypes") @Override public boolean equals(Object other) {
if (!(other instanceof ArrayWrapper)) {
return false;
}
@ -69,43 +100,8 @@ public final class ArrayWrapper<E> {
* @return This object's hash code.
* @see Arrays#hashCode(Object[])
*/
@Override
public int hashCode() {
@Override public int hashCode() {
return Arrays.hashCode(_array);
}
/**
* Converts an iterable element collection to an array of elements.
* The iteration order of the specified object will be used as the array element order.
*
* @param list The iterable of objects which will be converted to an array.
* @param c The type of the elements of the array.
* @return An array of elements in the specified iterable.
*/
@SuppressWarnings("unchecked")
public static <T> T[] toArray(Iterable<? extends T> list, Class<T> c) {
int size = -1;
if (list instanceof Collection<?>) {
@SuppressWarnings("rawtypes")
Collection coll = (Collection) list;
size = coll.size();
}
if (size < 0) {
size = 0;
// Ugly hack: Count it ourselves
for (@SuppressWarnings("unused") T element : list) {
size++;
}
}
T[] result = (T[]) Array.newInstance(c, size);
int i = 0;
for (T element : list) { // Assumes iteration order is consistent
result[i++] = element; // Assign array element at index THEN increment counter
}
return result;
}
}

View File

@ -1,17 +1,11 @@
package com.plotsquared.bukkit.chat;
import static com.plotsquared.bukkit.chat.TextualComponent.rawText;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonWriter;
import org.bukkit.Achievement;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.Statistic;
import org.bukkit.*;
import org.bukkit.Statistic.Type;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
@ -22,19 +16,12 @@ import org.bukkit.inventory.ItemStack;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.lang.reflect.*;
import java.util.*;
import java.util.logging.Level;
import static com.plotsquared.bukkit.chat.TextualComponent.rawText;
/**
* Represents a formattable message. Such messages can use elements such as colors, formatting codes, hover and click data, and other features provided by the vanilla Minecraft <a href="http://minecraft.gamepedia.com/Tellraw#Raw_JSON_Text">JSON message formatter</a>.
* This class allows plugins to emulate the functionality of the vanilla Minecraft <a href="http://minecraft.gamepedia.com/Commands#tellraw">tellraw command</a>.
@ -45,7 +32,14 @@ import java.util.logging.Level;
* optionally initializing it with text. Further property-setting method calls will affect that editing component.
* </p>
*/
public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<MessagePart>, ConfigurationSerializable {
public class FancyMessage
implements JsonRepresentedObject, Cloneable, Iterable<MessagePart>, ConfigurationSerializable {
private static Constructor<?> nmsPacketPlayOutChatConstructor;
// The ChatSerializer's instance of Gson
private static Object nmsChatSerializerGsonInstance;
private static Method fromJsonMethod;
private static JsonParser _stringParser = new JsonParser();
static {
ConfigurationSerialization.registerClass(FancyMessage.class);
@ -55,20 +49,6 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
private String jsonString;
private boolean dirty;
private static Constructor<?> nmsPacketPlayOutChatConstructor;
@Override
public FancyMessage clone() throws CloneNotSupportedException {
FancyMessage instance = (FancyMessage) super.clone();
instance.messageParts = new ArrayList<>(messageParts.size());
for (int i = 0; i < messageParts.size(); i++) {
instance.messageParts.add(i, messageParts.get(i).clone());
}
instance.dirty = false;
instance.jsonString = null;
return instance;
}
/**
* Creates a JSON message with text.
*
@ -85,10 +65,12 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
dirty = false;
if (nmsPacketPlayOutChatConstructor == null) {
try {
nmsPacketPlayOutChatConstructor = Reflection.getNMSClass("PacketPlayOutChat").getDeclaredConstructor(Reflection.getNMSClass("IChatBaseComponent"));
nmsPacketPlayOutChatConstructor = Reflection.getNMSClass("PacketPlayOutChat")
.getDeclaredConstructor(Reflection.getNMSClass("IChatBaseComponent"));
nmsPacketPlayOutChatConstructor.setAccessible(true);
} catch (NoSuchMethodException e) {
Bukkit.getLogger().log(Level.SEVERE, "Could not find Minecraft method or constructor.", e);
Bukkit.getLogger()
.log(Level.SEVERE, "Could not find Minecraft method or constructor.", e);
} catch (SecurityException e) {
Bukkit.getLogger().log(Level.WARNING, "Could not access constructor.", e);
}
@ -102,6 +84,112 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
this((TextualComponent) null);
}
/**
* Deserializes a JSON-represented message from a mapping of key-value pairs.
* This is called by the Bukkit serialization API.
* It is not intended for direct public API consumption.
*
* @param serialized The key-value mapping which represents a fancy message.
*/
@SuppressWarnings("unchecked") public static FancyMessage deserialize(
Map<String, Object> serialized) {
FancyMessage msg = new FancyMessage();
msg.messageParts = (List<MessagePart>) serialized.get("messageParts");
msg.jsonString = serialized.containsKey("JSON") ? serialized.get("JSON").toString() : null;
msg.dirty = !serialized.containsKey("JSON");
return msg;
}
/**
* Deserializes a fancy message from its JSON representation. This JSON representation is of the format of
* that returned by {@link #toJSONString()}, and is compatible with vanilla inputs.
*
* @param json The JSON string which represents a fancy message.
* @return A {@code FancyMessage} representing the parameterized JSON message.
*/
public static FancyMessage deserialize(String json) {
JsonObject serialized = _stringParser.parse(json).getAsJsonObject();
JsonArray extra = serialized.getAsJsonArray("extra"); // Get the extra component
FancyMessage returnVal = new FancyMessage();
returnVal.messageParts.clear();
for (JsonElement mPrt : extra) {
MessagePart component = new MessagePart();
JsonObject messagePart = mPrt.getAsJsonObject();
for (Map.Entry<String, JsonElement> entry : messagePart.entrySet()) {
// Deserialize text
if (TextualComponent.isTextKey(entry.getKey())) {
// The map mimics the YAML serialization, which has a "key" field and one or more "value" fields
Map<String, Object> serializedMapForm =
new HashMap<>(); // Must be object due to Bukkit serializer API compliance
serializedMapForm.put("key", entry.getKey());
if (entry.getValue().isJsonPrimitive()) {
// Assume string
serializedMapForm.put("value", entry.getValue().getAsString());
} else {
// Composite object, but we assume each element is a string
for (Map.Entry<String, JsonElement> compositeNestedElement : entry
.getValue().getAsJsonObject().entrySet()) {
serializedMapForm.put("value." + compositeNestedElement.getKey(),
compositeNestedElement.getValue().getAsString());
}
}
component.text = TextualComponent.deserialize(serializedMapForm);
} else if (MessagePart.stylesToNames.inverse().containsKey(entry.getKey())) {
if (entry.getValue().getAsBoolean()) {
component.styles
.add(MessagePart.stylesToNames.inverse().get(entry.getKey()));
}
} else if (entry.getKey().equals("color")) {
component.color =
ChatColor.valueOf(entry.getValue().getAsString().toUpperCase());
} else if (entry.getKey().equals("clickEvent")) {
JsonObject object = entry.getValue().getAsJsonObject();
component.clickActionName = object.get("action").getAsString();
component.clickActionData = object.get("value").getAsString();
} else if (entry.getKey().equals("hoverEvent")) {
JsonObject object = entry.getValue().getAsJsonObject();
component.hoverActionName = object.get("action").getAsString();
if (object.get("value").isJsonPrimitive()) {
// Assume string
component.hoverActionData =
new JsonString(object.get("value").getAsString());
} else {
// Assume composite type
// The only composite type we currently store is another FancyMessage
// Therefore, recursion time!
component.hoverActionData = deserialize(object.get("value").toString() /* This should properly serialize the JSON object as a JSON string */);
}
} else if (entry.getKey().equals("insertion")) {
component.insertionData = entry.getValue().getAsString();
} else if (entry.getKey().equals("with")) {
for (JsonElement object : entry.getValue().getAsJsonArray()) {
if (object.isJsonPrimitive()) {
component.translationReplacements
.add(new JsonString(object.getAsString()));
} else {
// Only composite type stored in this array is - again - FancyMessages
// Recurse within this function to parse this as a translation replacement
component.translationReplacements.add(deserialize(object.toString()));
}
}
}
}
returnVal.messageParts.add(component);
}
return returnVal;
}
@Override public FancyMessage clone() throws CloneNotSupportedException {
FancyMessage instance = (FancyMessage) super.clone();
instance.messageParts = new ArrayList<>(messageParts.size());
for (int i = 0; i < messageParts.size(); i++) {
instance.messageParts.add(i, messageParts.get(i).clone());
}
instance.dirty = false;
instance.jsonString = null;
return instance;
}
/**
* Sets the text of the current editing component to a value.
*
@ -242,8 +330,12 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
*/
public FancyMessage achievementTooltip(final Achievement which) {
try {
Object achievement = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getNMSAchievement", Achievement.class).invoke(null, which);
return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Achievement"), "name").get(achievement));
Object achievement = Reflection
.getMethod(Reflection.getOBCClass("CraftStatistic"), "getNMSAchievement",
Achievement.class).invoke(null, which);
return achievementTooltip(
(String) Reflection.getField(Reflection.getNMSClass("Achievement"), "name")
.get(achievement));
} catch (IllegalAccessException e) {
Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e);
return this;
@ -251,7 +343,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e);
return this;
} catch (InvocationTargetException e) {
Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e);
Bukkit.getLogger()
.log(Level.WARNING, "A error has occurred during invoking of method.", e);
return this;
}
}
@ -267,11 +360,16 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
public FancyMessage statisticTooltip(final Statistic which) {
Type type = which.getType();
if (type != Type.UNTYPED) {
throw new IllegalArgumentException("That statistic requires an additional " + type + " parameter!");
throw new IllegalArgumentException(
"That statistic requires an additional " + type + " parameter!");
}
try {
Object statistic = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getNMSStatistic", Statistic.class).invoke(null, which);
return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name").get(statistic));
Object statistic = Reflection
.getMethod(Reflection.getOBCClass("CraftStatistic"), "getNMSStatistic",
Statistic.class).invoke(null, which);
return achievementTooltip(
(String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name")
.get(statistic));
} catch (IllegalAccessException e) {
Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e);
return this;
@ -279,7 +377,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e);
return this;
} catch (InvocationTargetException e) {
Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e);
Bukkit.getLogger()
.log(Level.WARNING, "A error has occurred during invoking of method.", e);
return this;
}
}
@ -299,11 +398,16 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
throw new IllegalArgumentException("That statistic needs no additional parameter!");
}
if ((type == Type.BLOCK && item.isBlock()) || type == Type.ENTITY) {
throw new IllegalArgumentException("Wrong parameter type for that statistic - needs " + type + "!");
throw new IllegalArgumentException(
"Wrong parameter type for that statistic - needs " + type + "!");
}
try {
Object statistic = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getMaterialStatistic", Statistic.class, Material.class).invoke(null, which, item);
return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name").get(statistic));
Object statistic = Reflection
.getMethod(Reflection.getOBCClass("CraftStatistic"), "getMaterialStatistic",
Statistic.class, Material.class).invoke(null, which, item);
return achievementTooltip(
(String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name")
.get(statistic));
} catch (IllegalAccessException e) {
Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e);
return this;
@ -311,7 +415,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e);
return this;
} catch (InvocationTargetException e) {
Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e);
Bukkit.getLogger()
.log(Level.WARNING, "A error has occurred during invoking of method.", e);
return this;
}
}
@ -331,11 +436,16 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
throw new IllegalArgumentException("That statistic needs no additional parameter!");
}
if (type != Type.ENTITY) {
throw new IllegalArgumentException("Wrong parameter type for that statistic - needs " + type + "!");
throw new IllegalArgumentException(
"Wrong parameter type for that statistic - needs " + type + "!");
}
try {
Object statistic = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getEntityStatistic", Statistic.class, EntityType.class).invoke(null, which, entity);
return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name").get(statistic));
Object statistic = Reflection
.getMethod(Reflection.getOBCClass("CraftStatistic"), "getEntityStatistic",
Statistic.class, EntityType.class).invoke(null, which, entity);
return achievementTooltip(
(String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name")
.get(statistic));
} catch (IllegalAccessException e) {
Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e);
return this;
@ -343,7 +453,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e);
return this;
} catch (InvocationTargetException e) {
Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e);
Bukkit.getLogger()
.log(Level.WARNING, "A error has occurred during invoking of method.", e);
return this;
}
}
@ -356,7 +467,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
* @return This builder instance.
*/
public FancyMessage itemTooltip(final String itemJSON) {
onHover("show_item", new JsonString(itemJSON)); // Seems a bit hacky, considering we have a JSON object as a parameter
onHover("show_item", new JsonString(
itemJSON)); // Seems a bit hacky, considering we have a JSON object as a parameter
return this;
}
@ -369,8 +481,13 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
*/
public FancyMessage itemTooltip(final ItemStack itemStack) {
try {
Object nmsItem = Reflection.getMethod(Reflection.getOBCClass("inventory.CraftItemStack"), "asNMSCopy", ItemStack.class).invoke(null, itemStack);
return itemTooltip(Reflection.getMethod(Reflection.getNMSClass("ItemStack"), "save", Reflection.getNMSClass("NBTTagCompound")).invoke(nmsItem, Reflection.getNMSClass("NBTTagCompound").newInstance()).toString());
Object nmsItem = Reflection
.getMethod(Reflection.getOBCClass("inventory.CraftItemStack"), "asNMSCopy",
ItemStack.class).invoke(null, itemStack);
return itemTooltip(Reflection.getMethod(Reflection.getNMSClass("ItemStack"), "save",
Reflection.getNMSClass("NBTTagCompound"))
.invoke(nmsItem, Reflection.getNMSClass("NBTTagCompound").newInstance())
.toString());
} catch (Exception e) {
e.printStackTrace();
return this;
@ -400,6 +517,22 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
tooltip(com.plotsquared.bukkit.chat.ArrayWrapper.toArray(lines, String.class));
return this;
}
/*
/**
* If the text is a translatable key, and it has replaceable values, this function can be used to set the replacements that will be used in the message.
* @param replacements The replacements, in order, that will be used in the language-specific message.
* @return This builder instance.
*/ /* ------------
public FancyMessage translationReplacements(final Iterable<? extends CharSequence> replacements){
for(CharSequence str : replacements){
latest().translationReplacements.add(new JsonString(str));
}
return this;
}
*/
/**
* Set the behavior of the current editing component to display raw text when the client hovers over the text.
@ -453,15 +586,19 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
}
FancyMessage result = new FancyMessage();
result.messageParts.clear(); // Remove the one existing text component that exists by default, which destabilizes the object
result.messageParts
.clear(); // Remove the one existing text component that exists by default, which destabilizes the object
for (int i = 0; i < lines.length; i++) {
try {
for (MessagePart component : lines[i]) {
if (component.clickActionData != null && component.clickActionName != null) {
throw new IllegalArgumentException("The tooltip text cannot have click data.");
} else if (component.hoverActionData != null && component.hoverActionName != null) {
throw new IllegalArgumentException("The tooltip text cannot have a tooltip.");
throw new IllegalArgumentException(
"The tooltip text cannot have click data.");
} else if (component.hoverActionData != null
&& component.hoverActionName != null) {
throw new IllegalArgumentException(
"The tooltip text cannot have a tooltip.");
}
if (component.hasText()) {
result.messageParts.add(component.clone());
@ -475,7 +612,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
return this;
}
}
return formattedTooltip(result.messageParts.isEmpty() ? null : result); // Throws NPE if size is 0, intended
return formattedTooltip(
result.messageParts.isEmpty() ? null : result); // Throws NPE if size is 0, intended
}
/**
@ -486,7 +624,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
* @return This builder instance.
*/
public FancyMessage formattedTooltip(final Iterable<FancyMessage> lines) {
return formattedTooltip(com.plotsquared.bukkit.chat.ArrayWrapper.toArray(lines, FancyMessage.class));
return formattedTooltip(
com.plotsquared.bukkit.chat.ArrayWrapper.toArray(lines, FancyMessage.class));
}
/**
@ -503,22 +642,6 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
return this;
}
/*
/**
* If the text is a translatable key, and it has replaceable values, this function can be used to set the replacements that will be used in the message.
* @param replacements The replacements, in order, that will be used in the language-specific message.
* @return This builder instance.
*/ /* ------------
public FancyMessage translationReplacements(final Iterable<? extends CharSequence> replacements){
for(CharSequence str : replacements){
latest().translationReplacements.add(new JsonString(str));
}
return this;
}
*/
/**
* If the text is a translatable key, and it has replaceable values, this function can be used to set the replacements that will be used in the message.
@ -543,7 +666,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
* @return This builder instance.
*/
public FancyMessage translationReplacements(final Iterable<FancyMessage> replacements) {
return translationReplacements(com.plotsquared.bukkit.chat.ArrayWrapper.toArray(replacements, FancyMessage.class));
return translationReplacements(
com.plotsquared.bukkit.chat.ArrayWrapper.toArray(replacements, FancyMessage.class));
}
/**
@ -588,8 +712,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
return this;
}
@Override
public void writeJson(JsonWriter writer) throws IOException {
@Override public void writeJson(JsonWriter writer) throws IOException {
if (messageParts.size() == 1) {
latest().writeJson(writer);
} else {
@ -641,8 +764,11 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
Player player = (Player) sender;
try {
Object handle = Reflection.getHandle(player);
Object connection = Reflection.getField(handle.getClass(), "playerConnection").get(handle);
Reflection.getMethod(connection.getClass(), "sendPacket", Reflection.getNMSClass("Packet")).invoke(connection, createChatPacket(jsonString));
Object connection =
Reflection.getField(handle.getClass(), "playerConnection").get(handle);
Reflection
.getMethod(connection.getClass(), "sendPacket", Reflection.getNMSClass("Packet"))
.invoke(connection, createChatPacket(jsonString));
} catch (IllegalArgumentException e) {
Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e);
} catch (IllegalAccessException e) {
@ -650,7 +776,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
} catch (InstantiationException e) {
Bukkit.getLogger().log(Level.WARNING, "Underlying class is abstract.", e);
} catch (InvocationTargetException e) {
Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e);
Bukkit.getLogger()
.log(Level.WARNING, "A error has occurred during invoking of method.", e);
} catch (NoSuchMethodException e) {
Bukkit.getLogger().log(Level.WARNING, "Could not find method.", e);
} catch (ClassNotFoundException e) {
@ -658,11 +785,9 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
}
}
// The ChatSerializer's instance of Gson
private static Object nmsChatSerializerGsonInstance;
private static Method fromJsonMethod;
private Object createChatPacket(String json) throws IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException {
private Object createChatPacket(String json)
throws IllegalArgumentException, IllegalAccessException, InstantiationException,
InvocationTargetException, NoSuchMethodException, ClassNotFoundException {
if (nmsChatSerializerGsonInstance == null) {
// Find the field and its value, completely bypassing obfuscation
Class<?> chatSerializerClazz;
@ -673,7 +798,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
// Y = minor
// Z = revision
final String version = Reflection.getVersion();
String[] split = version.substring(1, version.length() - 1).split("_"); // Remove trailing dot
String[] split =
version.substring(1, version.length() - 1).split("_"); // Remove trailing dot
//int majorVersion = Integer.parseInt(split[0]);
int minorVersion = Integer.parseInt(split[1]);
int revisionVersion = Integer.parseInt(split[2].substring(1)); // Substring to ignore R
@ -689,11 +815,14 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
}
for (Field declaredField : chatSerializerClazz.getDeclaredFields()) {
if (Modifier.isFinal(declaredField.getModifiers()) && Modifier.isStatic(declaredField.getModifiers()) && declaredField.getType().getName().endsWith("Gson")) {
if (Modifier.isFinal(declaredField.getModifiers()) && Modifier
.isStatic(declaredField.getModifiers()) && declaredField.getType().getName()
.endsWith("Gson")) {
// We've found our field
declaredField.setAccessible(true);
nmsChatSerializerGsonInstance = declaredField.get(null);
fromJsonMethod = nmsChatSerializerGsonInstance.getClass().getMethod("fromJson", String.class, Class.class);
fromJsonMethod = nmsChatSerializerGsonInstance.getClass()
.getMethod("fromJson", String.class, Class.class);
break;
}
}
@ -701,7 +830,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
// Since the method is so simple, and all the obfuscated methods have the same name, it's easier to reimplement 'IChatBaseComponent a(String)' than to reflectively call it
// Of course, the implementation may change, but fuzzy matches might break with signature changes
Object serializedChatComponent = fromJsonMethod.invoke(nmsChatSerializerGsonInstance, json, Reflection.getNMSClass("IChatBaseComponent"));
Object serializedChatComponent = fromJsonMethod.invoke(nmsChatSerializerGsonInstance, json,
Reflection.getNMSClass("IChatBaseComponent"));
return nmsPacketPlayOutChatConstructor.newInstance(serializedChatComponent);
}
@ -782,26 +912,10 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
public Map<String, Object> serialize() {
HashMap<String, Object> map = new HashMap<>();
map.put("messageParts", messageParts);
// map.put("JSON", toJSONString());
// map.put("JSON", toJSONString());
return map;
}
/**
* Deserializes a JSON-represented message from a mapping of key-value pairs.
* This is called by the Bukkit serialization API.
* It is not intended for direct public API consumption.
*
* @param serialized The key-value mapping which represents a fancy message.
*/
@SuppressWarnings("unchecked")
public static FancyMessage deserialize(Map<String, Object> serialized) {
FancyMessage msg = new FancyMessage();
msg.messageParts = (List<MessagePart>) serialized.get("messageParts");
msg.jsonString = serialized.containsKey("JSON") ? serialized.get("JSON").toString() : null;
msg.dirty = !serialized.containsKey("JSON");
return msg;
}
/**
* <b>Internally called method. Not for API consumption.</b>
*/
@ -809,78 +923,4 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
return messageParts.iterator();
}
private static JsonParser _stringParser = new JsonParser();
/**
* Deserializes a fancy message from its JSON representation. This JSON representation is of the format of
* that returned by {@link #toJSONString()}, and is compatible with vanilla inputs.
*
* @param json The JSON string which represents a fancy message.
* @return A {@code FancyMessage} representing the parameterized JSON message.
*/
public static FancyMessage deserialize(String json) {
JsonObject serialized = _stringParser.parse(json).getAsJsonObject();
JsonArray extra = serialized.getAsJsonArray("extra"); // Get the extra component
FancyMessage returnVal = new FancyMessage();
returnVal.messageParts.clear();
for (JsonElement mPrt : extra) {
MessagePart component = new MessagePart();
JsonObject messagePart = mPrt.getAsJsonObject();
for (Map.Entry<String, JsonElement> entry : messagePart.entrySet()) {
// Deserialize text
if (TextualComponent.isTextKey(entry.getKey())) {
// The map mimics the YAML serialization, which has a "key" field and one or more "value" fields
Map<String, Object> serializedMapForm = new HashMap<>(); // Must be object due to Bukkit serializer API compliance
serializedMapForm.put("key", entry.getKey());
if (entry.getValue().isJsonPrimitive()) {
// Assume string
serializedMapForm.put("value", entry.getValue().getAsString());
} else {
// Composite object, but we assume each element is a string
for (Map.Entry<String, JsonElement> compositeNestedElement : entry.getValue().getAsJsonObject().entrySet()) {
serializedMapForm.put("value." + compositeNestedElement.getKey(), compositeNestedElement.getValue().getAsString());
}
}
component.text = TextualComponent.deserialize(serializedMapForm);
} else if (MessagePart.stylesToNames.inverse().containsKey(entry.getKey())) {
if (entry.getValue().getAsBoolean()) {
component.styles.add(MessagePart.stylesToNames.inverse().get(entry.getKey()));
}
} else if (entry.getKey().equals("color")) {
component.color = ChatColor.valueOf(entry.getValue().getAsString().toUpperCase());
} else if (entry.getKey().equals("clickEvent")) {
JsonObject object = entry.getValue().getAsJsonObject();
component.clickActionName = object.get("action").getAsString();
component.clickActionData = object.get("value").getAsString();
} else if (entry.getKey().equals("hoverEvent")) {
JsonObject object = entry.getValue().getAsJsonObject();
component.hoverActionName = object.get("action").getAsString();
if (object.get("value").isJsonPrimitive()) {
// Assume string
component.hoverActionData = new JsonString(object.get("value").getAsString());
} else {
// Assume composite type
// The only composite type we currently store is another FancyMessage
// Therefore, recursion time!
component.hoverActionData = deserialize(object.get("value").toString() /* This should properly serialize the JSON object as a JSON string */);
}
} else if (entry.getKey().equals("insertion")) {
component.insertionData = entry.getValue().getAsString();
} else if (entry.getKey().equals("with")) {
for (JsonElement object : entry.getValue().getAsJsonArray()) {
if (object.isJsonPrimitive()) {
component.translationReplacements.add(new JsonString(object.getAsString()));
} else {
// Only composite type stored in this array is - again - FancyMessages
// Recurse within this function to parse this as a translation replacement
component.translationReplacements.add(deserialize(object.toString()));
}
}
}
}
returnVal.messageParts.add(component);
}
return returnVal;
}
}

View File

@ -11,6 +11,7 @@ interface JsonRepresentedObject {
/**
* Writes the JSON representation of this object to the specified writer.
*
* @param writer The JSON writer which will receive the object.
* @throws IOException If an error occurs writing to the stream.
*/

View File

@ -20,8 +20,11 @@ final class JsonString implements JsonRepresentedObject, ConfigurationSerializab
_value = value == null ? null : value.toString();
}
@Override
public void writeJson(JsonWriter writer) throws IOException {
public static JsonString deserialize(Map<String, Object> map) {
return new JsonString(map.get("stringValue").toString());
}
@Override public void writeJson(JsonWriter writer) throws IOException {
writer.value(getValue());
}
@ -35,12 +38,7 @@ final class JsonString implements JsonRepresentedObject, ConfigurationSerializab
return theSingleValue;
}
public static JsonString deserialize(Map<String, Object> map) {
return new JsonString(map.get("stringValue").toString());
}
@Override
public String toString() {
@Override public String toString() {
return _value;
}

View File

@ -19,43 +19,6 @@ import java.util.logging.Level;
*/
final class MessagePart implements JsonRepresentedObject, ConfigurationSerializable, Cloneable {
ChatColor color = ChatColor.WHITE;
ArrayList<ChatColor> styles = new ArrayList<>();
String clickActionName = null;
String clickActionData = null;
String hoverActionName = null;
JsonRepresentedObject hoverActionData = null;
TextualComponent text = null;
String insertionData = null;
ArrayList<JsonRepresentedObject> translationReplacements = new ArrayList<>();
MessagePart(final TextualComponent text) {
this.text = text;
}
MessagePart() {
this.text = null;
}
boolean hasText() {
return text != null;
}
@Override
@SuppressWarnings("unchecked")
public MessagePart clone() throws CloneNotSupportedException {
MessagePart obj = (MessagePart) super.clone();
obj.styles = (ArrayList<ChatColor>) styles.clone();
if (hoverActionData instanceof JsonString) {
obj.hoverActionData = new JsonString(((JsonString) hoverActionData).getValue());
} else if (hoverActionData instanceof FancyMessage) {
obj.hoverActionData = ((FancyMessage) hoverActionData).clone();
}
obj.translationReplacements = (ArrayList<JsonRepresentedObject>) translationReplacements.clone();
return obj;
}
static final BiMap<ChatColor, String> stylesToNames;
static {
@ -83,6 +46,62 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa
stylesToNames = builder.build();
}
static {
ConfigurationSerialization.registerClass(MessagePart.class);
}
ChatColor color = ChatColor.WHITE;
ArrayList<ChatColor> styles = new ArrayList<>();
String clickActionName = null;
String clickActionData = null;
String hoverActionName = null;
JsonRepresentedObject hoverActionData = null;
TextualComponent text = null;
String insertionData = null;
ArrayList<JsonRepresentedObject> translationReplacements = new ArrayList<>();
MessagePart(final TextualComponent text) {
this.text = text;
}
MessagePart() {
this.text = null;
}
@SuppressWarnings("unchecked")
public static MessagePart deserialize(Map<String, Object> serialized) {
MessagePart part = new MessagePart((TextualComponent) serialized.get("text"));
part.styles = (ArrayList<ChatColor>) serialized.get("styles");
part.color = ChatColor.getByChar(serialized.get("color").toString());
part.hoverActionName = (String) serialized.get("hoverActionName");
part.hoverActionData = (JsonRepresentedObject) serialized.get("hoverActionData");
part.clickActionName = (String) serialized.get("clickActionName");
part.clickActionData = (String) serialized.get("clickActionData");
part.insertionData = (String) serialized.get("insertion");
part.translationReplacements =
(ArrayList<JsonRepresentedObject>) serialized.get("translationReplacements");
return part;
}
boolean hasText() {
return text != null;
}
@Override @SuppressWarnings("unchecked") public MessagePart clone()
throws CloneNotSupportedException {
MessagePart obj = (MessagePart) super.clone();
obj.styles = (ArrayList<ChatColor>) styles.clone();
if (hoverActionData instanceof JsonString) {
obj.hoverActionData = new JsonString(((JsonString) hoverActionData).getValue());
} else if (hoverActionData instanceof FancyMessage) {
obj.hoverActionData = ((FancyMessage) hoverActionData).clone();
}
obj.translationReplacements =
(ArrayList<JsonRepresentedObject>) translationReplacements.clone();
return obj;
}
public void writeJson(JsonWriter json) {
try {
json.beginObject();
@ -92,16 +111,11 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa
json.name(stylesToNames.get(style)).value(true);
}
if (clickActionName != null && clickActionData != null) {
json.name("clickEvent")
.beginObject()
.name("action").value(clickActionName)
.name("value").value(clickActionData)
.endObject();
json.name("clickEvent").beginObject().name("action").value(clickActionName)
.name("value").value(clickActionData).endObject();
}
if (hoverActionName != null && hoverActionData != null) {
json.name("hoverEvent")
.beginObject()
.name("action").value(hoverActionName)
json.name("hoverEvent").beginObject().name("action").value(hoverActionName)
.name("value");
hoverActionData.writeJson(json);
json.endObject();
@ -109,7 +123,8 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa
if (insertionData != null) {
json.name("insertion").value(insertionData);
}
if (translationReplacements.size() > 0 && text != null && TextualComponent.isTranslatableText(text)) {
if (translationReplacements.size() > 0 && text != null && TextualComponent
.isTranslatableText(text)) {
json.name("with").beginArray();
for (JsonRepresentedObject obj : translationReplacements) {
obj.writeJson(json);
@ -118,7 +133,8 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa
}
json.endObject();
} catch (IOException e) {
Bukkit.getLogger().log(Level.WARNING, "A problem occured during writing of JSON string", e);
Bukkit.getLogger()
.log(Level.WARNING, "A problem occured during writing of JSON string", e);
}
}
@ -136,22 +152,4 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa
return map;
}
@SuppressWarnings("unchecked")
public static MessagePart deserialize(Map<String, Object> serialized) {
MessagePart part = new MessagePart((TextualComponent) serialized.get("text"));
part.styles = (ArrayList<ChatColor>) serialized.get("styles");
part.color = ChatColor.getByChar(serialized.get("color").toString());
part.hoverActionName = (String) serialized.get("hoverActionName");
part.hoverActionData = (JsonRepresentedObject) serialized.get("hoverActionData");
part.clickActionName = (String) serialized.get("clickActionName");
part.clickActionData = (String) serialized.get("clickActionData");
part.insertionData = (String) serialized.get("insertion");
part.translationReplacements = (ArrayList<JsonRepresentedObject>) serialized.get("translationReplacements");
return part;
}
static {
ConfigurationSerialization.registerClass(MessagePart.class);
}
}

View File

@ -28,10 +28,12 @@ public final class Reflection {
* Contains loaded methods in a cache.
* The map maps [types to maps of [method names to maps of [parameter types to method instances]]].
*/
private static final Map<Class<?>, Map<String, Map<ArrayWrapper<Class<?>>, Method>>> _loadedMethods = new HashMap<>();
private static final Map<Class<?>, Map<String, Map<ArrayWrapper<Class<?>>, Method>>>
_loadedMethods = new HashMap<>();
private static String _versionString;
private Reflection() { }
private Reflection() {
}
/**
* Gets the version string from the package name of the CraftBukkit server implementation.
@ -109,7 +111,8 @@ public final class Reflection {
* @param obj The object for which to retrieve an NMS handle.
* @return The NMS handle of the specified object, or {@code null} if it could not be retrieved using {@code getHandle()}.
*/
public synchronized static Object getHandle(Object obj) throws InvocationTargetException, IllegalAccessException, IllegalArgumentException {
public synchronized static Object getHandle(Object obj)
throws InvocationTargetException, IllegalAccessException, IllegalArgumentException {
return getMethod(obj.getClass(), "getHandle").invoke(obj);
}
@ -181,7 +184,8 @@ public final class Reflection {
_loadedMethods.put(clazz, new HashMap<String, Map<ArrayWrapper<Class<?>>, Method>>());
}
Map<String, Map<ArrayWrapper<Class<?>>, Method>> loadedMethodNames = _loadedMethods.get(clazz);
Map<String, Map<ArrayWrapper<Class<?>>, Method>> loadedMethodNames =
_loadedMethods.get(clazz);
if (!loadedMethodNames.containsKey(name)) {
loadedMethodNames.put(name, new HashMap<ArrayWrapper<Class<?>>, Method>());
}

View File

@ -27,7 +27,8 @@ public abstract class TextualComponent implements Cloneable {
if (map.containsKey("key") && map.size() == 2 && map.containsKey("value")) {
// Arbitrary text component
return ArbitraryTextTypeComponent.deserialize(map);
} else if (map.size() >= 2 && map.containsKey("key") && !map.containsKey("value") /* It contains keys that START WITH value */) {
} else if (map.size() >= 2 && map.containsKey("key") && !map
.containsKey("value") /* It contains keys that START WITH value */) {
// Complex JSON object
return ComplexTextTypeComponent.deserialize(map);
}
@ -36,16 +37,18 @@ public abstract class TextualComponent implements Cloneable {
}
static boolean isTextKey(String key) {
return key.equals("translate") || key.equals("text") || key.equals("score") || key.equals("selector");
return key.equals("translate") || key.equals("text") || key.equals("score") || key
.equals("selector");
}
static boolean isTranslatableText(TextualComponent component) {
return component instanceof ComplexTextTypeComponent && component.getKey().equals("translate");
return component instanceof ComplexTextTypeComponent && component.getKey()
.equals("translate");
}
/**
* Create a textual component representing a string literal.
*
* <p>
* <p>This is the default type of textual component when a single string
* literal is given to a method.
*
@ -73,7 +76,8 @@ public abstract class TextualComponent implements Cloneable {
}
private static void throwUnsupportedSnapshot() {
throw new UnsupportedOperationException("This feature is only supported in snapshot releases.");
throw new UnsupportedOperationException(
"This feature is only supported in snapshot releases.");
}
/**
@ -94,7 +98,7 @@ public abstract class TextualComponent implements Cloneable {
/**
* Create a textual component representing a scoreboard value.
* The client will see the score of the specified player for the specified objective as the text represented by this component.
*
* <p>
* <p><b>This method is currently guaranteed to throw an {@code UnsupportedOperationException}
* as it is only supported on snapshot clients.</b>
*
@ -112,10 +116,9 @@ public abstract class TextualComponent implements Cloneable {
throwUnsupportedSnapshot(); // Remove this line when the feature is released to non-snapshot versions, in addition to updating ALL THE
// OVERLOADS documentation accordingly
return new ComplexTextTypeComponent("score", ImmutableMap.<String, String>builder()
.put("name", playerName)
.put("objective", scoreboardObjective)
.build());
return new ComplexTextTypeComponent("score",
ImmutableMap.<String, String>builder().put("name", playerName)
.put("objective", scoreboardObjective).build());
}
/**
@ -136,8 +139,7 @@ public abstract class TextualComponent implements Cloneable {
return new ArbitraryTextTypeComponent("selector", selector);
}
@Override
public String toString() {
@Override public String toString() {
return getReadableString();
}
@ -155,8 +157,7 @@ public abstract class TextualComponent implements Cloneable {
* Clones a textual component instance.
* The returned object should not reference this textual component instance, but should maintain the same key and value.
*/
@Override
public abstract TextualComponent clone() throws CloneNotSupportedException;
@Override public abstract TextualComponent clone() throws CloneNotSupportedException;
/**
* Writes the text data represented by this textual component to the specified JSON writer object.
@ -171,7 +172,8 @@ public abstract class TextualComponent implements Cloneable {
* Internal class used to represent all types of text components.
* Exception validating done is on keys and values.
*/
private static final class ArbitraryTextTypeComponent extends TextualComponent implements ConfigurationSerializable {
private static final class ArbitraryTextTypeComponent extends TextualComponent
implements ConfigurationSerializable {
private String key;
private String value;
@ -182,16 +184,17 @@ public abstract class TextualComponent implements Cloneable {
}
public static ArbitraryTextTypeComponent deserialize(Map<String, Object> map) {
return new ArbitraryTextTypeComponent(map.get("key").toString(), map.get("value").toString());
return new ArbitraryTextTypeComponent(map.get("key").toString(),
map.get("value").toString());
}
@Override
public String getKey() {
@Override public String getKey() {
return key;
}
public void setKey(String key) {
Preconditions.checkArgument(key != null && !key.isEmpty(), "The key must be specified.");
Preconditions
.checkArgument(key != null && !key.isEmpty(), "The key must be specified.");
this.key = key;
}
@ -204,20 +207,16 @@ public abstract class TextualComponent implements Cloneable {
this.value = value;
}
@Override
public TextualComponent clone() throws CloneNotSupportedException {
@Override public TextualComponent clone() throws CloneNotSupportedException {
// Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone
return new ArbitraryTextTypeComponent(getKey(), getValue());
}
@Override
public void writeJson(JsonWriter writer) throws IOException {
@Override public void writeJson(JsonWriter writer) throws IOException {
writer.name(getKey()).value(getValue());
}
@Override
@SuppressWarnings("serial")
public Map<String, Object> serialize() {
@Override @SuppressWarnings("serial") public Map<String, Object> serialize() {
return new HashMap<String, Object>() {
{
put("key", getKey());
@ -226,19 +225,20 @@ public abstract class TextualComponent implements Cloneable {
};
}
@Override
public String getReadableString() {
@Override public String getReadableString() {
return getValue();
}
}
/**
* Internal class used to represent a text component with a nested JSON
* value.
*
* <p>
* <p>Exception validating done is on keys and values.
*/
private static final class ComplexTextTypeComponent extends TextualComponent implements ConfigurationSerializable {
private static final class ComplexTextTypeComponent extends TextualComponent
implements ConfigurationSerializable {
private String key;
private Map<String, String> value;
@ -255,19 +255,20 @@ public abstract class TextualComponent implements Cloneable {
if (valEntry.getKey().equals("key")) {
key = (String) valEntry.getValue();
} else if (valEntry.getKey().startsWith("value.")) {
value.put(valEntry.getKey().substring(6) /* Strips out the value prefix */, valEntry.getValue().toString());
value.put(valEntry.getKey().substring(6) /* Strips out the value prefix */,
valEntry.getValue().toString());
}
}
return new ComplexTextTypeComponent(key, value);
}
@Override
public String getKey() {
@Override public String getKey() {
return key;
}
public void setKey(String key) {
Preconditions.checkArgument(key != null && !key.isEmpty(), "The key must be specified.");
Preconditions
.checkArgument(key != null && !key.isEmpty(), "The key must be specified.");
this.key = key;
}
@ -280,14 +281,12 @@ public abstract class TextualComponent implements Cloneable {
this.value = value;
}
@Override
public TextualComponent clone() {
@Override public TextualComponent clone() {
// Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone
return new ComplexTextTypeComponent(getKey(), getValue());
}
@Override
public void writeJson(JsonWriter writer) throws IOException {
@Override public void writeJson(JsonWriter writer) throws IOException {
writer.name(getKey());
writer.beginObject();
for (Map.Entry<String, String> jsonPair : value.entrySet()) {
@ -296,9 +295,7 @@ public abstract class TextualComponent implements Cloneable {
writer.endObject();
}
@Override
@SuppressWarnings("serial")
public Map<String, Object> serialize() {
@Override @SuppressWarnings("serial") public Map<String, Object> serialize() {
return new java.util.HashMap<String, Object>() {
{
put("key", getKey());
@ -309,8 +306,7 @@ public abstract class TextualComponent implements Cloneable {
};
}
@Override
public String getReadableString() {
@Override public String getReadableString() {
return getKey();
}
}

View File

@ -11,11 +11,7 @@ import com.intellectualcrafters.plot.object.OfflinePlotPlayer;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.StringWrapper;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.util.WorldUtil;
import com.intellectualcrafters.plot.util.*;
import com.intellectualcrafters.plot.uuid.UUIDWrapper;
import com.plotsquared.bukkit.uuid.DatFileFilter;
import com.plotsquared.bukkit.uuid.DefaultUUIDWrapper;
@ -23,32 +19,22 @@ import com.plotsquared.bukkit.uuid.LowerOfflineUUIDWrapper;
import com.plotsquared.bukkit.uuid.OfflineUUIDWrapper;
import com.plotsquared.general.commands.Argument;
import com.plotsquared.general.commands.CommandDeclaration;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.*;
import java.util.Map.Entry;
import java.util.UUID;
@CommandDeclaration(
command = "uuidconvert",
permission = "plots.admin",
description = "Debug UUID conversion",
usage = "/plot uuidconvert <lower|offline|online>",
requiredType = RequiredType.CONSOLE,
category = CommandCategory.DEBUG)
@CommandDeclaration(command = "uuidconvert", permission = "plots.admin", description = "Debug UUID conversion", usage = "/plot uuidconvert <lower|offline|online>", requiredType = RequiredType.CONSOLE, category = CommandCategory.DEBUG)
public class DebugUUID extends SubCommand {
public DebugUUID() {
super(Argument.String);
}
@Override
public boolean onCommand(final PlotPlayer player, String[] args) {
@Override public boolean onCommand(final PlotPlayer player, String[] args) {
final UUIDWrapper currentUUIDWrapper = UUIDHandler.getUUIDWrapper();
final UUIDWrapper newWrapper;
@ -67,7 +53,8 @@ public class DebugUUID extends SubCommand {
Class<?> clazz = Class.forName(args[0]);
newWrapper = (UUIDWrapper) clazz.newInstance();
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException ignored) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot uuidconvert <lower|offline|online>");
MainUtil.sendMessage(player, C.COMMAND_SYNTAX,
"/plot uuidconvert <lower|offline|online>");
return false;
}
}
@ -75,23 +62,29 @@ public class DebugUUID extends SubCommand {
if (args.length != 2 || !"-o".equals(args[1])) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot uuidconvert " + args[0] + " - o");
MainUtil.sendMessage(player, "&cBe aware of the following!");
MainUtil.sendMessage(player, "&8 - &cUse the database command or another method to backup your plots beforehand");
MainUtil.sendMessage(player, "&8 - &cIf the process is interrupted, all plots could be deleted");
MainUtil.sendMessage(player,
"&8 - &cUse the database command or another method to backup your plots beforehand");
MainUtil.sendMessage(player,
"&8 - &cIf the process is interrupted, all plots could be deleted");
MainUtil.sendMessage(player, "&8 - &cIf an error occurs, all plots could be deleted");
MainUtil.sendMessage(player, "&8 - &cPlot settings WILL be lost upon conversion");
MainUtil.sendMessage(player, "&cTO REITERATE: BACK UP YOUR DATABASE BEFORE USING THIS!!!");
MainUtil.sendMessage(player, "&7Retype the command with the override parameter when ready :)");
MainUtil
.sendMessage(player, "&cTO REITERATE: BACK UP YOUR DATABASE BEFORE USING THIS!!!");
MainUtil.sendMessage(player,
"&7Retype the command with the override parameter when ready :)");
return false;
}
if (currentUUIDWrapper.getClass().getCanonicalName().equals(newWrapper.getClass().getCanonicalName())) {
if (currentUUIDWrapper.getClass().getCanonicalName()
.equals(newWrapper.getClass().getCanonicalName())) {
MainUtil.sendMessage(player, "&cUUID mode already in use!");
return false;
}
MainUtil.sendMessage(player, "&6Beginning UUID mode conversion");
MainUtil.sendMessage(player, "&7 - Disconnecting players");
for (Entry<String, PlotPlayer> entry : UUIDHandler.getPlayers().entrySet()) {
entry.getValue().kick("UUID conversion has been initiated. You may reconnect when finished.");
entry.getValue()
.kick("UUID conversion has been initiated. You may reconnect when finished.");
}
MainUtil.sendMessage(player, "&7 - Initializing map");
@ -135,12 +128,14 @@ public class DebugUUID extends SubCommand {
OfflinePlotPlayer op = wrapper.getOfflinePlayer(uuid);
uuid = currentUUIDWrapper.getUUID(op);
uuid2 = newWrapper.getUUID(op);
if (!uuid.equals(uuid2) && !uCMap.containsKey(uuid) && !uCReverse.containsKey(uuid2)) {
if (!uuid.equals(uuid2) && !uCMap.containsKey(uuid) && !uCReverse
.containsKey(uuid2)) {
uCMap.put(uuid, uuid2);
uCReverse.put(uuid2, uuid);
}
} catch (Throwable ignored) {
MainUtil.sendMessage(player, C.PREFIX + "&6Invalid playerdata: " + uuid.toString() + ".dat");
MainUtil.sendMessage(player,
C.PREFIX + "&6Invalid playerdata: " + uuid.toString() + ".dat");
}
}
for (String name : names) {
@ -175,8 +170,7 @@ public class DebugUUID extends SubCommand {
MainUtil.sendMessage(player, "&7 - Replacing cache");
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
@Override public void run() {
for (Entry<UUID, UUID> entry : uCMap.entrySet()) {
String name = UUIDHandler.getName(entry.getKey());
if (name != null) {
@ -189,7 +183,8 @@ public class DebugUUID extends SubCommand {
File file = new File(PS.get().IMP.getDirectory(), "uuids.txt");
if (file.exists()) {
try {
List<String> lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
List<String> lines =
Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
for (String line : lines) {
try {
line = line.trim();
@ -199,7 +194,8 @@ public class DebugUUID extends SubCommand {
line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", "");
String[] split = line.split("\\|");
String name = split[0];
if (name.isEmpty() || name.length() > 16 || !StringMan.isAlphanumericUnd(name)) {
if (name.isEmpty() || name.length() > 16 || !StringMan
.isAlphanumericUnd(name)) {
continue;
}
UUID old = currentUUIDWrapper.getUUID(name);
@ -249,9 +245,9 @@ public class DebugUUID extends SubCommand {
plot.owner = value;
}
}
DBFunc.createPlotsAndData(new ArrayList<>(PS.get().getPlots()), new Runnable() {
@Override
public void run() {
DBFunc.createPlotsAndData(new ArrayList<>(PS.get().getPlots()),
new Runnable() {
@Override public void run() {
MainUtil.sendMessage(player, "&6Recovery was successful!");
}
});
@ -272,18 +268,17 @@ public class DebugUUID extends SubCommand {
try {
PS.get().worlds.save(PS.get().worldsFile);
} catch (IOException ignored) {
MainUtil.sendMessage(player, "Could not save configuration. It will need to be manual set!");
MainUtil.sendMessage(player,
"Could not save configuration. It will need to be manual set!");
}
MainUtil.sendMessage(player, "&7 - Populating tables");
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
@Override public void run() {
ArrayList<Plot> plots = new ArrayList<>(PS.get().getPlots());
DBFunc.createPlotsAndData(plots, new Runnable() {
@Override
public void run() {
@Override public void run() {
MainUtil.sendMessage(player, "&aConversion complete!");
}
});
@ -291,7 +286,8 @@ public class DebugUUID extends SubCommand {
});
MainUtil.sendMessage(player, "&aIt is now safe for players to join");
MainUtil.sendMessage(player, "&cConversion is still in progress, you will be notified when it is complete");
MainUtil.sendMessage(player,
"&cConversion is still in progress, you will be notified when it is complete");
}
});
return true;

View File

@ -13,9 +13,11 @@ import java.util.HashMap;
public abstract class APlotMeConnector {
public abstract Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, String dataFolder);
public abstract Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig,
String dataFolder);
public abstract HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(Connection connection) throws SQLException;
public abstract HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(Connection connection)
throws SQLException;
public abstract boolean accepts(String version);
@ -31,9 +33,11 @@ public abstract class APlotMeConnector {
String wallBlock = plotConfig.getString("worlds." + world + ".WallBlockId"); //
PS.get().worlds.set("worlds." + actualWorldName + ".wall.block", wallBlock);
String floor = plotConfig.getString("worlds." + world + ".PlotFloorBlockId"); //
PS.get().worlds.set("worlds." + actualWorldName + ".plot.floor", Collections.singletonList(floor));
PS.get().worlds
.set("worlds." + actualWorldName + ".plot.floor", Collections.singletonList(floor));
String filling = plotConfig.getString("worlds." + world + ".PlotFillingBlockId"); //
PS.get().worlds.set("worlds." + actualWorldName + ".plot.filling", Collections.singletonList(filling));
PS.get().worlds
.set("worlds." + actualWorldName + ".plot.filling", Collections.singletonList(filling));
String road = plotConfig.getString("worlds." + world + ".RoadMainBlockId");
PS.get().worlds.set("worlds." + actualWorldName + ".road.block", road);
int height = plotConfig.getInt("worlds." + world + ".RoadHeight"); //
@ -58,20 +62,21 @@ public abstract class APlotMeConnector {
return new Location(null, x, 1, z);
}
public void setMerged(HashMap<String, HashMap<PlotId, boolean[]>> merges, String world, PlotId id, int direction) {
public void setMerged(HashMap<String, HashMap<PlotId, boolean[]>> merges, String world,
PlotId id, int direction) {
HashMap<PlotId, boolean[]> plots = merges.get(world);
PlotId id2 = new PlotId(id.x, id.y);
boolean[] merge1;
if (plots.containsKey(id)) {
merge1 = plots.get(id);
} else {
merge1 = new boolean[] { false, false, false, false };
merge1 = new boolean[] {false, false, false, false};
}
boolean[] merge2;
if (plots.containsKey(id2)) {
merge2 = plots.get(id2);
} else {
merge2 = new boolean[] { false, false, false, false };
merge2 = new boolean[] {false, false, false, false};
}
merge1[direction] = true;
merge2[(direction + 2) % 4] = true;

View File

@ -6,20 +6,12 @@ import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.database.SQLite;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.StringWrapper;
import com.intellectualcrafters.plot.object.*;
import com.intellectualcrafters.plot.util.UUIDHandler;
import java.io.File;
import java.nio.ByteBuffer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.*;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.UUID;
@ -29,8 +21,8 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
private String plugin = "PlotMe";
private String prefix;
@Override
public Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, String dataFolder) {
@Override public Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig,
String dataFolder) {
this.plugin = plugin.toLowerCase();
this.prefix = plotConfig.getString("mySQLprefix", this.plugin.toLowerCase());
try {
@ -40,7 +32,8 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
String con = plotConfig.getString("mySQLconn");
return DriverManager.getConnection(con, user, password);
} else {
return new SQLite(new File(dataFolder + File.separator + "plots.db")).openConnection();
return new SQLite(new File(dataFolder + File.separator + "plots.db"))
.openConnection();
}
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
@ -48,13 +41,14 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
return null;
}
@Override
public HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(Connection connection) throws SQLException {
@Override public HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(Connection connection)
throws SQLException {
HashMap<String, Integer> plotWidth = new HashMap<>();
HashMap<String, Integer> roadWidth = new HashMap<>();
HashMap<String, HashMap<PlotId, Plot>> plots = new HashMap<>();
HashMap<String, HashMap<PlotId, boolean[]>> merges = new HashMap<>();
PreparedStatement statement = connection.prepareStatement("SELECT * FROM `" + this.prefix + "Plots`");
PreparedStatement statement =
connection.prepareStatement("SELECT * FROM `" + this.prefix + "Plots`");
ResultSet resultSet = statement.executeQuery();
String column = null;
boolean checkUUID = DBFunc.hasColumn(resultSet, "ownerid");
@ -64,7 +58,8 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
} else if (checkUUID2) {
column = "ownerId";
}
boolean merge = !"plotme".equalsIgnoreCase(this.plugin) && Settings.Enabled_Components.PLOTME_CONVERTER;
boolean merge =
!"plotme".equalsIgnoreCase(this.plugin) && Settings.Enabled_Components.PLOTME_CONVERTER;
int missing = 0;
while (resultSet.next()) {
PlotId id = new PlotId(resultSet.getInt("idX"), resultSet.getInt("idZ"));
@ -122,7 +117,8 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
missing++;
continue;
}
owner = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name.toLowerCase()).getBytes(Charsets.UTF_8));
owner = UUID.nameUUIDFromBytes(
("OfflinePlayer:" + name.toLowerCase()).getBytes(Charsets.UTF_8));
}
} else {
UUIDHandler.add(new StringWrapper(name), owner);
@ -134,7 +130,8 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
PS.log("&cSome names could not be identified:");
PS.log("&7 - Empty quotes mean PlotMe just stored an unowned plot in the database");
PS.log("&7 - Names you have never seen before could be from people mistyping commands");
PS.log("&7 - Converting from a non-uuid version of PlotMe can't identify owners if the playerdata files are deleted (these plots will "
PS.log(
"&7 - Converting from a non-uuid version of PlotMe can't identify owners if the playerdata files are deleted (these plots will "
+ "remain unknown until the player connects)");
}
@ -228,12 +225,13 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
resultSet.close();
statement.close();
} catch (SQLException ignored) {}
} catch (SQLException ignored) {
}
return plots;
}
@Override
public boolean accepts(String version) {
return version == null || PS.get().canUpdate(version, "0.17.0") || PS.get().canUpdate("0.999.999", version);
@Override public boolean accepts(String version) {
return version == null || PS.get().canUpdate(version, "0.17.0") || PS.get()
.canUpdate("0.999.999", version);
}
}

View File

@ -12,6 +12,11 @@ import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.bukkit.generator.BukkitPlotGenerator;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.WorldCreator;
import org.bukkit.command.CommandException;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@ -20,17 +25,9 @@ import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.*;
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 org.bukkit.command.CommandException;
public class LikePlotMeConverter {
@ -54,7 +51,8 @@ public class LikePlotMeConverter {
}
public String getPlotMePath() {
return new File(".").getAbsolutePath() + File.separator + "plugins" + File.separator + plugin + File.separator;
return new File(".").getAbsolutePath() + File.separator + "plugins" + File.separator
+ plugin + File.separator;
}
public FileConfiguration getPlotMeConfig(String dataFolder) {
@ -71,8 +69,9 @@ public class LikePlotMeConverter {
public void mergeWorldYml(FileConfiguration plotConfig) {
try {
File genConfig =
new File("plugins" + File.separator + plugin + File.separator + "PlotMe-DefaultGenerator" + File.separator + "config.yml");
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)) {
@ -103,7 +102,8 @@ public class LikePlotMeConverter {
content = content.replace("AthionPlots", pluginName);
content = content.replace("PlotZWorld", pluginName);
Files.write(path, content.getBytes(StandardCharsets.UTF_8));
} catch (IOException ignored) {}
} catch (IOException ignored) {
}
}
private void copyConfig(ConfigurationSection plotmeDgYml, String world) throws IOException {
@ -111,20 +111,25 @@ public class LikePlotMeConverter {
String plotMeWorldName = world.toLowerCase();
Integer pathWidth = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".PathWidth"); //
PS.get().worlds.set("worlds." + world + ".road.width", pathWidth);
int height = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".RoadHeight", plotmeDgYml.getInt("worlds." + plotMeWorldName + ".GroundHeight", 64)); //
int height = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".RoadHeight",
plotmeDgYml.getInt("worlds." + plotMeWorldName + ".GroundHeight", 64)); //
PS.get().worlds.set("worlds." + world + ".road.height", height);
PS.get().worlds.set("worlds." + world + ".wall.height", height);
PS.get().worlds.set("worlds." + world + ".plot.height", height);
int plotSize = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".PlotSize", 32); //
PS.get().worlds.set("worlds." + world + ".plot.size", plotSize);
String wallblock = plotmeDgYml.getString("worlds." + plotMeWorldName + ".UnclaimedBorder", plotmeDgYml.getString("worlds." + plotMeWorldName + ".WallBlock", "44")); //
String wallblock = plotmeDgYml.getString("worlds." + plotMeWorldName + ".UnclaimedBorder",
plotmeDgYml.getString("worlds." + plotMeWorldName + ".WallBlock", "44")); //
PS.get().worlds.set("worlds." + world + ".wall.block", wallblock);
String claimed = plotmeDgYml.getString("worlds." + plotMeWorldName + ".ProtectedWallBlock", "44:1"); //
String claimed =
plotmeDgYml.getString("worlds." + plotMeWorldName + ".ProtectedWallBlock", "44:1"); //
PS.get().worlds.set("worlds." + world + ".wall.block_claimed", claimed);
String floor = plotmeDgYml.getString("worlds." + plotMeWorldName + ".PlotFloorBlock", "2"); //
String floor =
plotmeDgYml.getString("worlds." + plotMeWorldName + ".PlotFloorBlock", "2"); //
PS.get().worlds.set("worlds." + world + ".plot.floor", Collections.singletonList(floor));
String filling = plotmeDgYml.getString("worlds." + plotMeWorldName + ".FillBlock", "3"); //
PS.get().worlds.set("worlds." + world + ".plot.filling", Collections.singletonList(filling));
PS.get().worlds
.set("worlds." + world + ".plot.filling", Collections.singletonList(filling));
String road = plotmeDgYml.getString("worlds." + plotMeWorldName + ".RoadMainBlock", "5");
PS.get().worlds.set("worlds." + world + ".road.block", road);
PS.get().worlds.set("worlds." + actualWorldName + ".road.height", height);
@ -151,14 +156,15 @@ public class LikePlotMeConverter {
PS.debug("&3Using connector: " + connector.getClass().getCanonicalName());
Connection connection = connector.getPlotMeConnection(plugin,plotConfig, dataFolder);
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("PlotMe conversion has started. To disable this, please set 'enabled-components -> plotme-converter' to false in the 'settings.yml'");
sendMessage(
"PlotMe conversion has started. To disable this, please set 'enabled-components -> plotme-converter' to false in the 'settings.yml'");
mergeWorldYml(plotConfig);
@ -201,7 +207,9 @@ public class LikePlotMeConverter {
sendMessage(" - " + dbPrefix + "Allowed");
sendMessage("Collected " + plotCount + " plots from PlotMe");
File plotmeDgFile = new File(dataFolder + File.separator + "PlotMe-DefaultGenerator" + File.separator + "config.yml");
File plotmeDgFile = new File(
dataFolder + File.separator + "PlotMe-DefaultGenerator" + File.separator
+ "config.yml");
if (plotmeDgFile.exists()) {
YamlConfiguration plotmeDgYml = YamlConfiguration.loadConfiguration(plotmeDgFile);
try {
@ -227,7 +235,8 @@ public class LikePlotMeConverter {
}
}
if (duplicate > 0) {
PS.debug("&c[WARNING] Found " + duplicate + " duplicate plots already in DB for world: '" + world
PS.debug("&c[WARNING] Found " + duplicate
+ " duplicate plots already in DB for world: '" + world
+ "'. Have you run the converter already?");
}
} else {
@ -242,7 +251,8 @@ public class LikePlotMeConverter {
}
}
if (duplicate > 0) {
PS.debug("&c[WARNING] Found " + duplicate + " duplicate plots already in DB for world: '" + world
PS.debug("&c[WARNING] Found " + duplicate
+ " duplicate plots already in DB for world: '" + world
+ "'. Have you run the converter already?");
}
continue;
@ -255,18 +265,20 @@ public class LikePlotMeConverter {
Thread.sleep(1000);
final AtomicBoolean done = new AtomicBoolean(false);
DBFunc.createPlotsAndData(createdPlots, new Runnable() {
@Override
public void run() {
@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-converter' 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 - Disable 'plotme-converter' 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!");
sendMessage(
"&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!");
done.set(true);
}
}
@ -278,57 +290,70 @@ public class LikePlotMeConverter {
sendMessage(" - &cFailed to save configuration.");
}
TaskManager.runTask(new Runnable() {
@Override
public void run() {
@Override public void run() {
try {
boolean mv = false;
boolean mw = false;
if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) && Bukkit.getPluginManager().getPlugin("Multiverse-Core")
.isEnabled()) {
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()) {
} else if ((Bukkit.getPluginManager().getPlugin("MultiWorld") != null)
&& Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled()) {
mw = true;
}
for (String worldName : worlds) {
World world = Bukkit.getWorld(getWorld(worldName));
if (world == null) {
sendMessage("&cInvalid world in PlotMe configuration: " + worldName);
sendMessage(
"&cInvalid world in PlotMe configuration: " + worldName);
continue;
}
String actualWorldName = world.getName();
sendMessage("Reloading generator for world: '" + actualWorldName + "'...");
if (!Bukkit.getWorlds().isEmpty() && Bukkit.getWorlds().get(0).getName().equals(worldName)) {
sendMessage("&cYou need to stop the server to reload this world properly");
sendMessage(
"Reloading generator for world: '" + actualWorldName + "'...");
if (!Bukkit.getWorlds().isEmpty() && Bukkit.getWorlds().get(0).getName()
.equals(worldName)) {
sendMessage(
"&cYou need to stop the server to reload this world properly");
} else {
PS.get().removePlotAreas(actualWorldName);
if (mv) {
// unload world with MV
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv unload " + actualWorldName);
Bukkit.getServer()
.dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mv unload " + actualWorldName);
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
// load world with MV
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mv import " + actualWorldName + " normal -g " + PS.imp().getPluginName());
Bukkit.getServer()
.dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mv import " + actualWorldName + " normal -g " + PS
.imp().getPluginName());
} else if (mw) {
// unload world with MW
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw unload " + actualWorldName);
Bukkit.getServer()
.dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mw unload " + actualWorldName);
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
// load world with MW
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mw create " + actualWorldName + " plugin:" + PS.imp().getPluginName());
Bukkit.getServer()
.dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mw create " + actualWorldName + " plugin:" + PS.imp()
.getPluginName());
} else {
// Load using Bukkit API
// - User must set generator manually
Bukkit.getServer().unloadWorld(world, true);
World myWorld = WorldCreator.name(actualWorldName).generator(new BukkitPlotGenerator(PS.get().IMP.getDefaultGenerator())).createWorld();
World myWorld = WorldCreator.name(actualWorldName).generator(
new BukkitPlotGenerator(PS.get().IMP.getDefaultGenerator()))
.createWorld();
myWorld.save();
}
}
@ -340,11 +365,14 @@ public class LikePlotMeConverter {
done();
sendMessage("&aDatabase conversion is now complete!");
PS.debug("&c - Stop the server");
PS.debug("&c - Disable 'plotme-converter' 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 - Disable 'plotme-converter' 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!");
sendMessage(
"&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!");
done.set(true);
}
}

View File

@ -5,19 +5,11 @@ import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.database.SQLite;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.StringWrapper;
import com.intellectualcrafters.plot.object.*;
import com.intellectualcrafters.plot.util.UUIDHandler;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.*;
import java.util.HashMap;
import java.util.UUID;
@ -25,8 +17,8 @@ public class PlotMeConnector_017 extends APlotMeConnector {
private String plugin;
@Override
public Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, String dataFolder) {
@Override public Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig,
String dataFolder) {
this.plugin = plugin.toLowerCase();
try {
if (plotConfig.getBoolean("usemySQL")) {
@ -39,7 +31,8 @@ public class PlotMeConnector_017 extends APlotMeConnector {
if (file.exists()) {
return new SQLite(file).openConnection();
}
return new SQLite(new File(dataFolder + File.separator + "plots.db")).openConnection();
return new SQLite(new File(dataFolder + File.separator + "plots.db"))
.openConnection();
}
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
@ -47,8 +40,8 @@ public class PlotMeConnector_017 extends APlotMeConnector {
return null;
}
@Override
public HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(Connection connection) throws SQLException {
@Override public HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(Connection connection)
throws SQLException {
ResultSet resultSet;
PreparedStatement statement;
HashMap<String, Integer> plotWidth = new HashMap<>();
@ -56,18 +49,21 @@ public class PlotMeConnector_017 extends APlotMeConnector {
HashMap<Integer, Plot> plots = new HashMap<>();
HashMap<String, HashMap<PlotId, boolean[]>> merges = new HashMap<>();
try {
statement = connection.prepareStatement("SELECT * FROM `" + this.plugin + "core_plots`");
statement =
connection.prepareStatement("SELECT * FROM `" + this.plugin + "core_plots`");
resultSet = statement.executeQuery();
} catch (SQLException e) {
PS.debug("========= Table does not exist =========");
e.printStackTrace();
PS.debug("=======================================");
PS.debug("&8 - &7The database does not match the version specified in the PlotMe config");
PS.debug(
"&8 - &7The database does not match the version specified in the PlotMe config");
PS.debug("&8 - &7Please correct this, or if you are unsure, the most common is 0.16.3");
return null;
}
boolean checkUUID = DBFunc.hasColumn(resultSet, "ownerID");
boolean merge = !"plotme".equals(this.plugin) && Settings.Enabled_Components.PLOTME_CONVERTER;
boolean merge =
!"plotme".equals(this.plugin) && Settings.Enabled_Components.PLOTME_CONVERTER;
while (resultSet.next()) {
int key = resultSet.getInt("plot_id");
PlotId id = new PlotId(resultSet.getInt("plotX"), resultSet.getInt("plotZ"));
@ -115,7 +111,8 @@ public class PlotMeConnector_017 extends APlotMeConnector {
}
}
if (owner == null) {
PS.log("&cCould not identify owner for plot: " + id + " -> '" + name + '\'');
PS.log(
"&cCould not identify owner for plot: " + id + " -> '" + name + '\'');
continue;
}
}
@ -137,7 +134,8 @@ public class PlotMeConnector_017 extends APlotMeConnector {
statement.close();
try {
PS.log(" - " + this.plugin + "core_denied");
statement = connection.prepareStatement("SELECT * FROM `" + this.plugin + "core_denied`");
statement =
connection.prepareStatement("SELECT * FROM `" + this.plugin + "core_denied`");
resultSet = statement.executeQuery();
while (resultSet.next()) {
@ -153,7 +151,8 @@ public class PlotMeConnector_017 extends APlotMeConnector {
}
PS.log(" - " + this.plugin + "core_allowed");
statement = connection.prepareStatement("SELECT * FROM `" + this.plugin + "core_allowed`");
statement =
connection.prepareStatement("SELECT * FROM `" + this.plugin + "core_allowed`");
resultSet = statement.executeQuery();
while (resultSet.next()) {
@ -186,8 +185,7 @@ public class PlotMeConnector_017 extends APlotMeConnector {
return processed;
}
@Override
public boolean accepts(String version) {
@Override public boolean accepts(String version) {
if (version == null) {
return false;
}

View File

@ -49,18 +49,15 @@ public class ClusterFlagRemoveEvent extends Event implements Cancellable {
return this.flag;
}
@Override
public HandlerList getHandlers() {
@Override public HandlerList getHandlers() {
return handlers;
}
@Override
public boolean isCancelled() {
@Override public boolean isCancelled() {
return this.cancelled;
}
@Override
public void setCancelled(boolean b) {
@Override public void setCancelled(boolean b) {
this.cancelled = b;
}
}

View File

@ -45,18 +45,15 @@ public class PlayerClaimPlotEvent extends PlayerEvent implements Cancellable {
return this.auto;
}
@Override
public HandlerList getHandlers() {
@Override public HandlerList getHandlers() {
return handlers;
}
@Override
public boolean isCancelled() {
@Override public boolean isCancelled() {
return this.cancelled;
}
@Override
public void setCancelled(boolean b) {
@Override public void setCancelled(boolean b) {
this.cancelled = b;
}
}

View File

@ -34,8 +34,7 @@ public class PlayerEnterPlotEvent extends PlayerEvent {
return this.plot;
}
@Override
public HandlerList getHandlers() {
@Override public HandlerList getHandlers() {
return handlers;
}
}

View File

@ -38,8 +38,7 @@ public class PlayerLeavePlotEvent extends PlayerEvent {
return this.plot;
}
@Override
public HandlerList getHandlers() {
@Override public HandlerList getHandlers() {
return handlers;
}
}

View File

@ -59,8 +59,7 @@ public class PlayerPlotDeniedEvent extends PlotEvent {
return this.initiator;
}
@Override
public HandlerList getHandlers() {
@Override public HandlerList getHandlers() {
return handlers;
}
}

View File

@ -63,8 +63,7 @@ public class PlayerPlotHelperEvent extends PlotEvent {
return this.initiator;
}
@Override
public HandlerList getHandlers() {
@Override public HandlerList getHandlers() {
return handlers;
}
}

View File

@ -63,8 +63,7 @@ public class PlayerPlotTrustedEvent extends PlotEvent {
return this.initiator;
}
@Override
public HandlerList getHandlers() {
@Override public HandlerList getHandlers() {
return handlers;
}
}

View File

@ -9,9 +9,6 @@ import org.bukkit.event.player.PlayerEvent;
/**
* Called when a player teleports to a plot
*
*/
public class PlayerTeleportToPlotEvent extends PlayerEvent implements Cancellable {
@ -37,8 +34,7 @@ public class PlayerTeleportToPlotEvent extends PlayerEvent implements Cancellabl
return handlers;
}
@Override
public HandlerList getHandlers() {
@Override public HandlerList getHandlers() {
return handlers;
}
@ -60,13 +56,11 @@ public class PlayerTeleportToPlotEvent extends PlayerEvent implements Cancellabl
return this.plot;
}
@Override
public boolean isCancelled() {
@Override public boolean isCancelled() {
return this.cancelled;
}
@Override
public void setCancelled(boolean cancelled) {
@Override public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
}

View File

@ -7,12 +7,12 @@ import org.bukkit.event.HandlerList;
/**
* Called when a plot is cleared
*
*/
public class PlotClearEvent extends PlotEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private boolean cancelled;
public PlotClearEvent(Plot plot) {
super(plot);
}
@ -39,18 +39,15 @@ public class PlotClearEvent extends PlotEvent implements Cancellable {
return getPlot().getWorldName();
}
@Override
public HandlerList getHandlers() {
@Override public HandlerList getHandlers() {
return handlers;
}
@Override
public boolean isCancelled() {
@Override public boolean isCancelled() {
return this.cancelled;
}
@Override
public void setCancelled(boolean b) {
@Override public void setCancelled(boolean b) {
this.cancelled = b;
}
}

View File

@ -6,7 +6,6 @@ import org.bukkit.event.HandlerList;
/**
* Called when a plot component is set
*
*/
public class PlotComponentSetEvent extends PlotEvent {
@ -49,8 +48,7 @@ public class PlotComponentSetEvent extends PlotEvent {
return this.component;
}
@Override
public HandlerList getHandlers() {
@Override public HandlerList getHandlers() {
return handlers;
}
}

View File

@ -6,7 +6,6 @@ import org.bukkit.event.HandlerList;
/**
* Called when a plot is deleted
*
*/
public class PlotDeleteEvent extends PlotEvent {
@ -38,8 +37,7 @@ public class PlotDeleteEvent extends PlotEvent {
return getPlot().getWorldName();
}
@Override
public HandlerList getHandlers() {
@Override public HandlerList getHandlers() {
return handlers;
}
}

View File

@ -7,7 +7,6 @@ import org.bukkit.event.HandlerList;
/**
* Called when a Flag is added to a plot.
*
*/
public class PlotFlagAddEvent extends PlotEvent implements Cancellable {
@ -39,18 +38,15 @@ public class PlotFlagAddEvent extends PlotEvent implements Cancellable {
return this.flag;
}
@Override
public HandlerList getHandlers() {
@Override public HandlerList getHandlers() {
return handlers;
}
@Override
public final boolean isCancelled() {
@Override public final boolean isCancelled() {
return this.cancelled;
}
@Override
public final void setCancelled(boolean cancelled) {
@Override public final void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
}

View File

@ -7,7 +7,6 @@ import org.bukkit.event.HandlerList;
/**
* Called when a flag is removed from a plot
*
*/
public class PlotFlagRemoveEvent extends PlotEvent implements Cancellable {
@ -39,18 +38,15 @@ public class PlotFlagRemoveEvent extends PlotEvent implements Cancellable {
return this.flag;
}
@Override
public HandlerList getHandlers() {
@Override public HandlerList getHandlers() {
return handlers;
}
@Override
public final boolean isCancelled() {
@Override public final boolean isCancelled() {
return this.cancelled;
}
@Override
public final void setCancelled(boolean cancelled) {
@Override public final void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
}

View File

@ -45,18 +45,15 @@ public class PlotMergeEvent extends PlotEvent implements Cancellable {
return this.world;
}
@Override
public HandlerList getHandlers() {
@Override public HandlerList getHandlers() {
return handlers;
}
@Override
public boolean isCancelled() {
@Override public boolean isCancelled() {
return this.cancelled;
}
@Override
public void setCancelled(boolean b) {
@Override public void setCancelled(boolean b) {
this.cancelled = b;
}
}

View File

@ -33,8 +33,7 @@ public class PlotRateEvent extends PlotEvent {
this.rating = rating;
}
@Override
public HandlerList getHandlers() {
@Override public HandlerList getHandlers() {
return handlers;
}

View File

@ -50,18 +50,15 @@ public class PlotUnlinkEvent extends Event implements Cancellable {
return this.area;
}
@Override
public HandlerList getHandlers() {
@Override public HandlerList getHandlers() {
return handlers;
}
@Override
public boolean isCancelled() {
@Override public boolean isCancelled() {
return this.cancelled;
}
@Override
public void setCancelled(boolean b) {
@Override public void setCancelled(boolean b) {
this.cancelled = b;
}
}

View File

@ -24,8 +24,7 @@ public class BukkitAugmentedGenerator extends BlockPopulator {
return generator;
}
@Override
public void populate(World world, Random r, Chunk chunk) {
@Override public void populate(World world, Random r, Chunk chunk) {
AugmentedUtils.generate(world.getName(), chunk.getX(), chunk.getZ(), null);
}
}

View File

@ -3,14 +3,7 @@ package com.plotsquared.bukkit.generator;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.generator.GeneratorWrapper;
import com.intellectualcrafters.plot.generator.IndependentPlotGenerator;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.object.ChunkWrapper;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotManager;
import com.intellectualcrafters.plot.object.PseudoRandom;
import com.intellectualcrafters.plot.object.SetupObject;
import com.intellectualcrafters.plot.object.*;
import com.intellectualcrafters.plot.object.worlds.SingleWorldGenerator;
import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.MainUtil;
@ -20,26 +13,24 @@ import com.intellectualcrafters.plot.util.block.LocalBlockQueue;
import com.intellectualcrafters.plot.util.block.ScopedLocalBlockQueue;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.bukkit.util.block.GenChunk;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.Set;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator;
public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrapper<ChunkGenerator> {
import java.util.*;
public class BukkitPlotGenerator extends ChunkGenerator
implements GeneratorWrapper<ChunkGenerator> {
private final GenChunk chunkSetter;
private final PseudoRandom random = new PseudoRandom();
private final IndependentPlotGenerator plotGenerator;
private List<BlockPopulator> populators;
private final ChunkGenerator platformGenerator;
private final boolean full;
private final HashMap<ChunkLoc, byte[][]> dataMap = new HashMap<>();
private List<BlockPopulator> populators;
private boolean loaded = false;
public BukkitPlotGenerator(IndependentPlotGenerator generator) {
@ -53,12 +44,12 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
private LocalBlockQueue queue;
@Override
public void populate(World world, Random r, Chunk c) {
@Override public void populate(World world, Random r, Chunk c) {
if (queue == null) {
queue = GlobalBlockQueue.IMP.getNewQueue(world.getName(), false);
}
byte[][] resultData = dataMap.isEmpty() ? null : dataMap.remove(new ChunkLoc(c.getX(), c.getZ()));
byte[][] resultData =
dataMap.isEmpty() ? null : dataMap.remove(new ChunkLoc(c.getX(), c.getZ()));
if (resultData == null) {
GenChunk result = BukkitPlotGenerator.this.chunkSetter;
// Set the chunk location
@ -90,7 +81,8 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
PlotArea area = PS.get().getPlotArea(world.getName(), null);
ChunkWrapper wrap = new ChunkWrapper(area.worldname, c.getX(), c.getZ());
ScopedLocalBlockQueue chunk = queue.getForChunk(wrap.x, wrap.z);
if (BukkitPlotGenerator.this.plotGenerator.populateChunk(chunk, area, BukkitPlotGenerator.this.random)) {
if (BukkitPlotGenerator.this.plotGenerator
.populateChunk(chunk, area, BukkitPlotGenerator.this.random)) {
queue.flush();
}
}
@ -102,25 +94,24 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
public BukkitPlotGenerator(final String world, final ChunkGenerator cg) {
if (cg instanceof BukkitPlotGenerator) {
throw new IllegalArgumentException("ChunkGenerator: " + cg.getClass().getName() + " is already a BukkitPlotGenerator!");
throw new IllegalArgumentException("ChunkGenerator: " + cg.getClass().getName()
+ " is already a BukkitPlotGenerator!");
}
this.full = false;
PS.debug("BukkitPlotGenerator does not fully support: " + cg);
this.platformGenerator = cg;
this.plotGenerator = new IndependentPlotGenerator() {
@Override
public void processSetup(SetupObject setup) {}
@Override public void processSetup(SetupObject setup) {
}
@Override
public void initialize(PlotArea area) {}
@Override public void initialize(PlotArea area) {
}
@Override
public PlotManager getNewPlotManager() {
@Override public PlotManager getNewPlotManager() {
return PS.get().IMP.getDefaultGenerator().getNewPlotManager();
}
@Override
public String getName() {
@Override public String getName() {
return cg.getClass().getName();
}
@ -130,20 +121,19 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
}
@Override
public void generateChunk(final ScopedLocalBlockQueue result, PlotArea settings, PseudoRandom random) {
public void generateChunk(final ScopedLocalBlockQueue result, PlotArea settings,
PseudoRandom random) {
World w = BukkitUtil.getWorld(world);
Location min = result.getMin();
int cx = min.getX() >> 4;
int cz = min.getZ() >> 4;
Random r = new Random(MathMan.pair((short) cx, (short) cz));
BiomeGrid grid = new BiomeGrid() {
@Override
public void setBiome(int x, int z, Biome biome) {
@Override public void setBiome(int x, int z, Biome biome) {
result.setBiome(x, z, biome.name());
}
@Override
public Biome getBiome(int arg0, int arg1) {
@Override public Biome getBiome(int arg0, int arg1) {
return Biome.FOREST;
}
};
@ -153,7 +143,8 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
if (data != null) {
return;
}
} catch (Throwable ignored) {}
} catch (Throwable ignored) {
}
// Populator spillage
short[][] tmp = cg.generateExtBlockSections(w, r, cx, cz, grid);
if (tmp != null) {
@ -188,28 +179,23 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
MainUtil.initCache();
}
@Override
public void augment(PlotArea area) {
@Override public void augment(PlotArea area) {
BukkitAugmentedGenerator.get(BukkitUtil.getWorld(area.worldname));
}
@Override
public boolean isFull() {
@Override public boolean isFull() {
return this.full;
}
@Override
public IndependentPlotGenerator getPlotGenerator() {
@Override public IndependentPlotGenerator getPlotGenerator() {
return this.plotGenerator;
}
@Override
public ChunkGenerator getPlatformGenerator() {
@Override public ChunkGenerator getPlatformGenerator() {
return this.platformGenerator;
}
@Override
public List<BlockPopulator> getDefaultPopulators(World world) {
@Override public List<BlockPopulator> getDefaultPopulators(World world) {
try {
if (!this.loaded) {
String name = world.getName();
@ -309,8 +295,8 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
ChunkManager.postProcessChunk(result);
}
@Override
public short[][] generateExtBlockSections(World world, Random r, int cx, int cz, BiomeGrid grid) {
@Override public short[][] generateExtBlockSections(World world, Random r, int cx, int cz,
BiomeGrid grid) {
GenChunk result = this.chunkSetter;
// Set the chunk location
result.setChunk(new ChunkWrapper(world.getName(), cx, cz));
@ -342,18 +328,17 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
/**
* Allow spawning everywhere.
*
* @param world Ignored
* @param x Ignored
* @param z Ignored
* @return always true
*/
@Override
public boolean canSpawn(World world, int x, int z) {
@Override public boolean canSpawn(World world, int x, int z) {
return true;
}
@Override
public String toString() {
@Override public String toString() {
if (this.platformGenerator == this) {
return this.plotGenerator.getName();
}
@ -364,8 +349,7 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
}
}
@Override
public boolean equals(Object obj) {
@Override public boolean equals(Object obj) {
if (obj == null) {
return false;
}

View File

@ -9,8 +9,6 @@ import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefField;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod;
import com.intellectualcrafters.plot.util.TaskManager;
import java.lang.reflect.Method;
import java.util.HashSet;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Material;
@ -29,6 +27,8 @@ import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.event.world.ChunkUnloadEvent;
import java.lang.reflect.Method;
import java.util.HashSet;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
@ -37,6 +37,7 @@ public class ChunkListener implements Listener {
private RefMethod methodGetHandleChunk;
private RefField mustSave;
private Chunk lastChunk;
private boolean ignoreUnload = false;
public ChunkListener() {
if (Settings.Chunk_Processor.AUTO_TRIM) {
@ -46,7 +47,8 @@ public class ChunkListener implements Listener {
this.mustSave = classChunk.getField("mustSave");
this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle");
} catch (Throwable ignored) {
PS.debug(PS.imp().getPluginName() + "/Server not compatible for chunk processor trim/gc");
PS.debug(PS.imp().getPluginName()
+ "/Server not compatible for chunk processor trim/gc");
Settings.Chunk_Processor.AUTO_TRIM = false;
}
}
@ -57,8 +59,7 @@ public class ChunkListener implements Listener {
world.setAutoSave(false);
}
TaskManager.runTaskRepeat(new Runnable() {
@Override
public void run() {
@Override public void run() {
try {
HashSet<Chunk> toUnload = new HashSet<>();
for (World world : Bukkit.getWorlds()) {
@ -67,11 +68,14 @@ public class ChunkListener implements Listener {
continue;
}
Object w = world.getClass().getDeclaredMethod("getHandle").invoke(world);
Object chunkMap = w.getClass().getDeclaredMethod("getPlayerChunkMap").invoke(w);
Method methodIsChunkInUse = chunkMap.getClass().getDeclaredMethod("isChunkInUse", int.class, int.class);
Object chunkMap =
w.getClass().getDeclaredMethod("getPlayerChunkMap").invoke(w);
Method methodIsChunkInUse = chunkMap.getClass()
.getDeclaredMethod("isChunkInUse", int.class, int.class);
Chunk[] chunks = world.getLoadedChunks();
for (Chunk chunk : chunks) {
if ((boolean) methodIsChunkInUse.invoke(chunkMap, chunk.getX(), chunk.getZ())) {
if ((boolean) methodIsChunkInUse
.invoke(chunkMap, chunk.getX(), chunk.getZ())) {
continue;
}
int x = chunk.getX();
@ -100,8 +104,6 @@ public class ChunkListener implements Listener {
}, 1);
}
private boolean ignoreUnload = false;
public boolean unloadChunk(String world, Chunk chunk, boolean safe) {
if (safe && shouldSave(world, chunk.getX(), chunk.getZ())) {
return false;
@ -144,8 +146,7 @@ public class ChunkListener implements Listener {
return plot != null && plot.hasOwner();
}
@EventHandler
public void onChunkUnload(ChunkUnloadEvent event) {
@EventHandler public void onChunkUnload(ChunkUnloadEvent event) {
if (ignoreUnload) {
return;
}
@ -163,13 +164,11 @@ public class ChunkListener implements Listener {
}
}
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
@EventHandler public void onChunkLoad(ChunkLoadEvent event) {
processChunk(event.getChunk(), false);
}
@EventHandler(priority = EventPriority.LOWEST)
public void onItemSpawn(ItemSpawnEvent event) {
@EventHandler(priority = EventPriority.LOWEST) public void onItemSpawn(ItemSpawnEvent event) {
Item entity = event.getEntity();
Chunk chunk = entity.getLocation().getChunk();
if (chunk == this.lastChunk) {
@ -223,8 +222,7 @@ public class ChunkListener implements Listener {
TaskManager.index.incrementAndGet();
final Integer currentIndex = TaskManager.index.get();
Integer task = TaskManager.runTaskRepeat(new Runnable() {
@Override
public void run() {
@Override public void run() {
if (!chunk.isLoaded()) {
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex);
@ -270,11 +268,13 @@ public class ChunkListener implements Listener {
ent.remove();
}
}
PS.debug(C.PREFIX.s() + "&a detected unsafe chunk and processed: " + (chunk.getX() << 4) + "," + (chunk.getX() << 4));
PS.debug(C.PREFIX.s() + "&a detected unsafe chunk and processed: " + (chunk.getX() << 4)
+ "," + (chunk.getX() << 4));
}
if (tiles.length > Settings.Chunk_Processor.MAX_TILES) {
if (unload) {
PS.debug(C.PREFIX.s() + "&c detected unsafe chunk: " + (chunk.getX() << 4) + "," + (chunk.getX() << 4));
PS.debug(C.PREFIX.s() + "&c detected unsafe chunk: " + (chunk.getX() << 4) + "," + (
chunk.getX() << 4));
cleanChunk(chunk);
return true;
}

View File

@ -1,7 +1,6 @@
package com.plotsquared.bukkit.listeners;
import com.intellectualcrafters.plot.PS;
import java.util.List;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.ArmorStand;
@ -17,62 +16,21 @@ import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.plugin.Plugin;
import java.util.List;
public class EntityPortal_1_7_9 implements Listener {
private static boolean ignoreTP = false;
public EntityPortal_1_7_9() {
}
@EventHandler
public void onVehicle(VehicleUpdateEvent event) {
test(event.getVehicle());
}
@EventHandler
public void onVehicle(VehicleDestroyEvent event) {
test(event.getVehicle());
}
@EventHandler
public void onVehicle(VehicleEntityCollisionEvent event) {
test(event.getVehicle());
}
@EventHandler
public void onVehicle(VehicleCreateEvent event) {
test(event.getVehicle());
}
@EventHandler
public void onVehicle(VehicleBlockCollisionEvent event) {
test(event.getVehicle());
}
@EventHandler
public void onTeleport(EntityTeleportEvent event) {
Entity ent = event.getEntity();
if (ent instanceof Vehicle || ent instanceof ArmorStand) test(event.getEntity());
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void vehicleMove(VehicleMoveEvent event) throws IllegalAccessException {
test(event.getVehicle());
}
@EventHandler
public void spawn(CreatureSpawnEvent event) {
switch (event.getEntityType()) {
case ARMOR_STAND:
test(event.getEntity());
}
}
private static boolean ignoreTP = false;
public static void test(Entity entity) {
List<MetadataValue> meta = entity.getMetadata("plotworld");
World world = entity.getLocation().getWorld();
if (meta == null || meta.isEmpty()) {
if (PS.get().isPlotWorld(world.getName())) {
entity.setMetadata("plotworld", new FixedMetadataValue((Plugin) PS.get().IMP, entity.getLocation()));
entity.setMetadata("plotworld",
new FixedMetadataValue((Plugin) PS.get().IMP, entity.getLocation()));
}
} else {
Location origin = (Location) meta.get(0).value();
@ -96,4 +54,42 @@ public class EntityPortal_1_7_9 implements Listener {
}
}
}
@EventHandler public void onVehicle(VehicleUpdateEvent event) {
test(event.getVehicle());
}
@EventHandler public void onVehicle(VehicleDestroyEvent event) {
test(event.getVehicle());
}
@EventHandler public void onVehicle(VehicleEntityCollisionEvent event) {
test(event.getVehicle());
}
@EventHandler public void onVehicle(VehicleCreateEvent event) {
test(event.getVehicle());
}
@EventHandler public void onVehicle(VehicleBlockCollisionEvent event) {
test(event.getVehicle());
}
@EventHandler public void onTeleport(EntityTeleportEvent event) {
Entity ent = event.getEntity();
if (ent instanceof Vehicle || ent instanceof ArmorStand)
test(event.getEntity());
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void vehicleMove(VehicleMoveEvent event) throws IllegalAccessException {
test(event.getVehicle());
}
@EventHandler public void spawn(CreatureSpawnEvent event) {
switch (event.getEntityType()) {
case ARMOR_STAND:
test(event.getEntity());
}
}
}

View File

@ -52,8 +52,9 @@ public class EntitySpawnListener implements Listener {
event.setCancelled(true);
}
case SHULKER:
if(!entity.hasMetadata("plot")) {
entity.setMetadata("plot", new FixedMetadataValue((Plugin) PS.get().IMP, plot.getId()));
if (!entity.hasMetadata("plot")) {
entity.setMetadata("plot",
new FixedMetadataValue((Plugin) PS.get().IMP, plot.getId()));
}
}
}

View File

@ -9,19 +9,22 @@ import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.Permissions;
import com.plotsquared.bukkit.object.BukkitPlayer;
import com.plotsquared.bukkit.util.BukkitUtil;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
public class ForceFieldListener {
private static Set<PlotPlayer> getNearbyPlayers(Player player, Plot plot) {
Set<PlotPlayer> players = new HashSet<>();
for (Player nearPlayer : Iterables.filter(player.getNearbyEntities(5d, 5d, 5d),Player.class)) {
for (Player nearPlayer : Iterables
.filter(player.getNearbyEntities(5d, 5d, 5d), Player.class)) {
PlotPlayer plotPlayer;
if ((plotPlayer = BukkitUtil.getPlayer(nearPlayer)) == null || !plot.equals(plotPlayer.getCurrentPlot())) {
if ((plotPlayer = BukkitUtil.getPlayer(nearPlayer)) == null || !plot
.equals(plotPlayer.getCurrentPlot())) {
continue;
}
if (!plot.isAdded(plotPlayer.getUUID())) {
@ -32,9 +35,11 @@ public class ForceFieldListener {
}
private static PlotPlayer hasNearbyPermitted(Player player, Plot plot) {
for (Player nearPlayer : Iterables.filter(player.getNearbyEntities(5d, 5d, 5d),Player.class)) {
for (Player nearPlayer : Iterables
.filter(player.getNearbyEntities(5d, 5d, 5d), Player.class)) {
PlotPlayer plotPlayer;
if ((plotPlayer = BukkitUtil.getPlayer(nearPlayer)) == null || !plot.equals(plotPlayer.getCurrentPlot())) {
if ((plotPlayer = BukkitUtil.getPlayer(nearPlayer)) == null || !plot
.equals(plotPlayer.getCurrentPlot())) {
continue;
}
if (plot.isAdded(plotPlayer.getUUID())) {
@ -81,7 +86,8 @@ public class ForceFieldListener {
Set<PlotPlayer> players = getNearbyPlayers(player, plot);
for (PlotPlayer oPlayer : players) {
if (!Permissions.hasPermission(oPlayer, C.PERMISSION_ADMIN_ENTRY_FORCEFIELD)) {
((BukkitPlayer) oPlayer).player.setVelocity(calculateVelocity(plotPlayer, oPlayer));
((BukkitPlayer) oPlayer).player
.setVelocity(calculateVelocity(plotPlayer, oPlayer));
}
}
} else {

View File

@ -11,9 +11,6 @@ import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.listener.PlotListener;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
@ -31,12 +28,17 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;
public class PlayerEvents_1_8 extends PlotListener implements Listener {
@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onInventoryClick(InventoryClickEvent event) {
if (!event.isLeftClick() || (event.getAction() != InventoryAction.PLACE_ALL) || event.isShiftClick()) {
if (!event.isLeftClick() || (event.getAction() != InventoryAction.PLACE_ALL) || event
.isShiftClick()) {
return;
}
HumanEntity entity = event.getWhoClicked();
@ -71,7 +73,8 @@ public class PlayerEvents_1_8 extends PlotListener implements Listener {
switch (newItem.getType()) {
case BANNER:
case SKULL_ITEM:
if (newMeta != null) break;
if (newMeta != null)
break;
default:
return;
}
@ -89,9 +92,11 @@ public class PlayerEvents_1_8 extends PlotListener implements Listener {
switch (stateType) {
case STANDING_BANNER:
case WALL_BANNER:
if (itemType == Material.BANNER) break;
if (itemType == Material.BANNER)
break;
case SKULL:
if (itemType == Material.SKULL_ITEM) break;
if (itemType == Material.SKULL_ITEM)
break;
default:
return;
}
@ -124,12 +129,15 @@ public class PlayerEvents_1_8 extends PlotListener implements Listener {
}
}
if (cancelled) {
if ((current.getType() == newItem.getType()) && (current.getDurability() == newItem.getDurability())) {
event.setCursor(new ItemStack(newItem.getType(), newItem.getAmount(), newItem.getDurability()));
if ((current.getType() == newItem.getType()) && (current.getDurability() == newItem
.getDurability())) {
event.setCursor(
new ItemStack(newItem.getType(), newItem.getAmount(), newItem.getDurability()));
event.setCancelled(true);
return;
}
event.setCursor(new ItemStack(newItem.getType(), newItem.getAmount(), newItem.getDurability()));
event.setCursor(
new ItemStack(newItem.getType(), newItem.getAmount(), newItem.getDurability()));
}
}

View File

@ -8,10 +8,6 @@ import com.plotsquared.bukkit.events.PlayerEnterPlotEvent;
import com.plotsquared.bukkit.events.PlayerLeavePlotEvent;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.listener.PlotListener;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.block.Block;
@ -27,6 +23,11 @@ import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.UUID;
public class PlotPlusListener extends PlotListener implements Listener {
private static final HashMap<String, Interval> feedRunnable = new HashMap<>();
@ -34,10 +35,10 @@ public class PlotPlusListener extends PlotListener implements Listener {
public static void startRunnable(JavaPlugin plugin) {
plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
@Override
public void run() {
@Override public void run() {
if (!healRunnable.isEmpty()) {
for (Iterator<Entry<String, Interval>> iterator = healRunnable.entrySet().iterator(); iterator.hasNext(); ) {
for (Iterator<Entry<String, Interval>> iterator =
healRunnable.entrySet().iterator(); iterator.hasNext(); ) {
Entry<String, Interval> entry = iterator.next();
Interval value = entry.getValue();
++value.count;
@ -56,7 +57,8 @@ public class PlotPlusListener extends PlotListener implements Listener {
}
}
if (!feedRunnable.isEmpty()) {
for (Iterator<Entry<String, Interval>> iterator = feedRunnable.entrySet().iterator(); iterator.hasNext(); ) {
for (Iterator<Entry<String, Interval>> iterator =
feedRunnable.entrySet().iterator(); iterator.hasNext(); ) {
Entry<String, Interval> entry = iterator.next();
Interval value = entry.getValue();
++value.count;
@ -78,8 +80,7 @@ public class PlotPlusListener extends PlotListener implements Listener {
}, 0L, 20L);
}
@EventHandler(priority = EventPriority.HIGH)
public void onInteract(BlockDamageEvent event) {
@EventHandler(priority = EventPriority.HIGH) public void onInteract(BlockDamageEvent event) {
Player player = event.getPlayer();
if (player.getGameMode() != GameMode.SURVIVAL) {
return;
@ -98,8 +99,7 @@ public class PlotPlusListener extends PlotListener implements Listener {
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onDamage(EntityDamageEvent event) {
@EventHandler(priority = EventPriority.HIGH) public void onDamage(EntityDamageEvent event) {
if (event.getEntityType() != EntityType.PLAYER) {
return;
}
@ -113,8 +113,7 @@ public class PlotPlusListener extends PlotListener implements Listener {
}
}
@EventHandler
public void onItemDrop(PlayerDropItemEvent event) {
@EventHandler public void onItemDrop(PlayerDropItemEvent event) {
Player player = event.getPlayer();
PlotPlayer pp = BukkitUtil.getPlayer(player);
Plot plot = BukkitUtil.getLocation(player).getOwnedPlot();
@ -129,8 +128,7 @@ public class PlotPlusListener extends PlotListener implements Listener {
}
}
@EventHandler
public void onPlotEnter(PlayerEnterPlotEvent event) {
@EventHandler public void onPlotEnter(PlayerEnterPlotEvent event) {
Player player = event.getPlayer();
Plot plot = event.getPlot();
Optional<Integer[]> feed = plot.getFlag(Flags.FEED);
@ -145,16 +143,14 @@ public class PlotPlusListener extends PlotListener implements Listener {
}
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
@EventHandler public void onPlayerQuit(PlayerQuitEvent event) {
Player player = event.getPlayer();
String name = player.getName();
feedRunnable.remove(name);
healRunnable.remove(name);
}
@EventHandler
public void onPlotLeave(PlayerLeavePlotEvent event) {
@EventHandler public void onPlotLeave(PlayerLeavePlotEvent event) {
Player leaver = event.getPlayer();
Plot plot = event.getPlot();
if (!plot.hasOwner()) {

View File

@ -4,16 +4,16 @@ import com.intellectualcrafters.plot.flag.Flags;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.plotsquared.bukkit.util.BukkitUtil;
import java.util.UUID;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityPickupItemEvent;
import java.util.UUID;
public class PlotPlusListener_1_12 implements Listener {
@EventHandler
public void onItemPickup(EntityPickupItemEvent event) {
@EventHandler public void onItemPickup(EntityPickupItemEvent event) {
LivingEntity ent = event.getEntity();
if (ent instanceof Player) {
Player player = (Player) ent;

View File

@ -4,15 +4,15 @@ import com.intellectualcrafters.plot.flag.Flags;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.plotsquared.bukkit.util.BukkitUtil;
import java.util.UUID;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerPickupItemEvent;
import java.util.UUID;
public class PlotPlusListener_Legacy implements Listener {
@EventHandler
public void onItemPickup(PlayerPickupItemEvent event) {
@EventHandler public void onItemPickup(PlayerPickupItemEvent event) {
Player player = event.getPlayer();
PlotPlayer pp = BukkitUtil.getPlayer(player);
Plot plot = BukkitUtil.getLocation(player).getOwnedPlot();

View File

@ -4,8 +4,6 @@ import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.object.worlds.PlotAreaManager;
import com.intellectualcrafters.plot.object.worlds.SinglePlotAreaManager;
import com.intellectualcrafters.plot.util.ReflectionUtils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.World;
@ -16,6 +14,8 @@ import org.bukkit.event.world.ChunkEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.plugin.Plugin;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
@ -42,10 +42,14 @@ public class SingleWorldListener implements Listener {
public void markChunkAsClean(Chunk chunk) {
try {
Object nmsChunk = methodGetHandleChunk.invoke(chunk);
if (done != null) this.done.set(nmsChunk, true);
if (mustSave != null) this.mustSave.set(nmsChunk, false);
if (lit != null) this.lit.set(nmsChunk, false);
if (s != null) this.s.set(nmsChunk, false);
if (done != null)
this.done.set(nmsChunk, true);
if (mustSave != null)
this.mustSave.set(nmsChunk, false);
if (lit != null)
this.lit.set(nmsChunk, false);
if (s != null)
this.s.set(nmsChunk, false);
} catch (Throwable e) {
e.printStackTrace();
}
@ -55,19 +59,20 @@ public class SingleWorldListener implements Listener {
World world = event.getWorld();
String name = world.getName();
PlotAreaManager man = PS.get().getPlotAreaManager();
if (!(man instanceof SinglePlotAreaManager)) return;
if (!isPlotId(name)) return;
if (!(man instanceof SinglePlotAreaManager))
return;
if (!isPlotId(name))
return;
markChunkAsClean(event.getChunk());
}
// @EventHandler
// public void onPopulate(ChunkPopulateEvent event) {
// handle(event);
// }
// @EventHandler
// public void onPopulate(ChunkPopulateEvent event) {
// handle(event);
// }
@EventHandler(priority = EventPriority.LOWEST)
public void onChunkLoad(ChunkLoadEvent event) {
@EventHandler(priority = EventPriority.LOWEST) public void onChunkLoad(ChunkLoadEvent event) {
handle(event);
}

View File

@ -24,8 +24,7 @@ public class BukkitLazyBlock extends LazyBlock {
this.block = block;
}
@Override
public PlotBlock getPlotBlock() {
@Override public PlotBlock getPlotBlock() {
if (this.pb != null) {
return this.pb;
}
@ -127,8 +126,7 @@ public class BukkitLazyBlock extends LazyBlock {
}
@Override
public int getId() {
@Override public int getId() {
if (this.id == 0) {
this.id = this.block.getTypeId();
}

View File

@ -19,23 +19,19 @@ public class BukkitOfflinePlayer implements OfflinePlotPlayer {
this.player = player;
}
@Override
public UUID getUUID() {
@Override public UUID getUUID() {
return this.player.getUniqueId();
}
@Override
public long getLastPlayed() {
@Override public long getLastPlayed() {
return this.player.getLastPlayed();
}
@Override
public boolean isOnline() {
@Override public boolean isOnline() {
return this.player.isOnline();
}
@Override
public String getName() {
@Override public String getName() {
return this.player.getName();
}
}

View File

@ -6,7 +6,6 @@ import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.*;
import com.plotsquared.bukkit.util.BukkitUtil;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Effect;
import org.bukkit.GameMode;
import org.bukkit.WeatherType;
@ -14,13 +13,12 @@ import org.bukkit.entity.Player;
import org.bukkit.event.EventException;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.permissions.PermissionAttachmentInfo;
import org.bukkit.plugin.RegisteredListener;
import java.util.Set;
import java.util.UUID;
import org.bukkit.permissions.PermissionAttachmentInfo;
import org.bukkit.plugin.RegisteredListener;
public class BukkitPlayer extends PlotPlayer {
public final Player player;
@ -31,6 +29,7 @@ public class BukkitPlayer extends PlotPlayer {
/**
* <p>Please do not use this method. Instead use
* BukkitUtil.getPlayer(Player), as it caches player objects.</p>
*
* @param player
*/
public BukkitPlayer(Player player) {
@ -44,14 +43,12 @@ public class BukkitPlayer extends PlotPlayer {
super.populatePersistentMetaMap();
}
@Override
public Location getLocation() {
@Override public Location getLocation() {
Location location = super.getLocation();
return location == null ? BukkitUtil.getLocation(this.player) : location;
}
@Override
public UUID getUUID() {
@Override public UUID getUUID() {
if (this.uuid == null) {
this.uuid = UUIDHandler.getUUID(this);
}
@ -62,8 +59,7 @@ public class BukkitPlayer extends PlotPlayer {
return this.player.getLastPlayed();
}
@Override
public boolean canTeleport(Location loc) {
@Override public boolean canTeleport(Location loc) {
org.bukkit.Location to = BukkitUtil.getLocation(loc);
org.bukkit.Location from = player.getLocation();
PlayerTeleportEvent event = new PlayerTeleportEvent(player, from, to);
@ -95,16 +91,14 @@ public class BukkitPlayer extends PlotPlayer {
return true;
}
@Override
public boolean hasPermission(String permission) {
@Override public boolean hasPermission(String permission) {
if (this.offline && EconHandler.manager != null) {
return EconHandler.manager.hasPermission(getName(), permission);
}
return this.player.hasPermission(permission);
}
@Override
public int hasPermissionRange(String stub, int range) {
@Override public int hasPermissionRange(String stub, int range) {
if (hasPermission(C.PERMISSION_ADMIN.s())) {
return Integer.MAX_VALUE;
}
@ -131,8 +125,10 @@ public class BukkitPlayer extends PlotPlayer {
String end = perm.substring(stubPlus.length());
if (MathMan.isInteger(end)) {
int val = Integer.parseInt(end);
if (val > range) return val;
if (val > max) max = val;
if (val > range)
return val;
if (val > max)
max = val;
}
}
}
@ -146,57 +142,52 @@ public class BukkitPlayer extends PlotPlayer {
return max;
}
@Override
public boolean isPermissionSet(String permission) {
@Override public boolean isPermissionSet(String permission) {
return this.player.isPermissionSet(permission);
}
@Override
public void sendMessage(String message) {
if (!StringMan.isEqual(this.<String>getMeta("lastMessage"), message) || (System.currentTimeMillis() - this.<Long>getMeta("lastMessageTime") > 5000)) {
@Override public void sendMessage(String message) {
if (!StringMan.isEqual(this.<String>getMeta("lastMessage"), message) || (
System.currentTimeMillis() - this.<Long>getMeta("lastMessageTime") > 5000)) {
setMeta("lastMessage", message);
setMeta("lastMessageTime", System.currentTimeMillis());
this.player.sendMessage(message);
}
}
@Override
public void teleport(Location location) {
@Override public void teleport(Location location) {
if (Math.abs(location.getX()) >= 30000000 || Math.abs(location.getZ()) >= 30000000) {
return;
}
this.player.teleport(
new org.bukkit.Location(BukkitUtil.getWorld(location.getWorld()), location.getX() + 0.5, location.getY(), location.getZ() + 0.5,
location.getYaw(), location.getPitch()), TeleportCause.COMMAND);
new org.bukkit.Location(BukkitUtil.getWorld(location.getWorld()), location.getX() + 0.5,
location.getY(), location.getZ() + 0.5, location.getYaw(), location.getPitch()),
TeleportCause.COMMAND);
}
@Override
public String getName() {
@Override public String getName() {
if (this.name == null) {
this.name = this.player.getName();
}
return this.name;
}
@Override
public boolean isOnline() {
@Override public boolean isOnline() {
return !this.offline && this.player.isOnline();
}
@Override
public void setCompassTarget(Location location) {
@Override public void setCompassTarget(Location location) {
this.player.setCompassTarget(
new org.bukkit.Location(BukkitUtil.getWorld(location.getWorld()), location.getX(), location.getY(), location.getZ()));
new org.bukkit.Location(BukkitUtil.getWorld(location.getWorld()), location.getX(),
location.getY(), location.getZ()));
}
@Override
public Location getLocationFull() {
@Override public Location getLocationFull() {
return BukkitUtil.getLocationFull(this.player);
}
@Override
public void setWeather(PlotWeather weather) {
@Override public void setWeather(PlotWeather weather) {
switch (weather) {
case CLEAR:
this.player.setPlayerWeather(WeatherType.CLEAR);
@ -213,8 +204,7 @@ public class BukkitPlayer extends PlotPlayer {
}
}
@Override
public PlotGameMode getGameMode() {
@Override public PlotGameMode getGameMode() {
switch (this.player.getGameMode()) {
case ADVENTURE:
return PlotGameMode.ADVENTURE;
@ -229,8 +219,7 @@ public class BukkitPlayer extends PlotPlayer {
}
}
@Override
public void setGameMode(PlotGameMode gameMode) {
@Override public void setGameMode(PlotGameMode gameMode) {
switch (gameMode) {
case ADVENTURE:
this.player.setGameMode(GameMode.ADVENTURE);
@ -250,8 +239,7 @@ public class BukkitPlayer extends PlotPlayer {
}
}
@Override
public void setTime(long time) {
@Override public void setTime(long time) {
if (time != Long.MAX_VALUE) {
this.player.setPlayerTime(time, false);
} else {
@ -259,24 +247,20 @@ public class BukkitPlayer extends PlotPlayer {
}
}
@Override
public void setFlight(boolean fly) {
this.player.setAllowFlight(fly);
}
@Override
public boolean getFlight() {
@Override public boolean getFlight() {
return player.getAllowFlight();
}
@Override
public void playMusic(Location location, int id) {
@Override public void setFlight(boolean fly) {
this.player.setAllowFlight(fly);
}
@Override public void playMusic(Location location, int id) {
//noinspection deprecation
this.player.playEffect(BukkitUtil.getLocation(location), Effect.RECORD_PLAY, id);
}
@Override
public void kick(String message) {
@Override public void kick(String message) {
this.player.kickPlayer(message);
}
@ -286,8 +270,7 @@ public class BukkitPlayer extends PlotPlayer {
}
}
@Override
public boolean isBanned() {
@Override public boolean isBanned() {
return this.player.isBanned();
}
}

View File

@ -2,34 +2,11 @@ package com.plotsquared.bukkit.object.entity;
import com.intellectualcrafters.plot.PS;
import com.plotsquared.bukkit.util.BukkitVersion;
import org.bukkit.Art;
import org.bukkit.DyeColor;
import org.bukkit.Location;
import org.bukkit.Rotation;
import org.bukkit.TreeSpecies;
import org.bukkit.World;
import org.bukkit.*;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Ageable;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Bat;
import org.bukkit.entity.Boat;
import org.bukkit.entity.EnderDragon;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Guardian;
import org.bukkit.entity.Horse;
import org.bukkit.entity.IronGolem;
import org.bukkit.entity.Item;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Painting;
import org.bukkit.entity.Rabbit;
import org.bukkit.entity.*;
import org.bukkit.entity.Rabbit.Type;
import org.bukkit.entity.Sheep;
import org.bukkit.entity.Skeleton;
import org.bukkit.entity.Skeleton.SkeletonType;
import org.bukkit.entity.Slime;
import org.bukkit.entity.Tameable;
import org.bukkit.inventory.EntityEquipment;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
@ -87,7 +64,8 @@ public class EntityWrapper {
if (depth == 1) {
return;
}
if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_10_0) || entity instanceof ArmorStand) {
if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_10_0)
|| entity instanceof ArmorStand) {
if (!entity.hasGravity()) {
this.noGravity = true;
}
@ -220,13 +198,16 @@ public class EntityWrapper {
storeLiving((LivingEntity) entity);
return;
case SKELETON:
this.dataByte = getOrdinal(SkeletonType.values(),((Skeleton)entity).getSkeletonType());
this.dataByte =
getOrdinal(SkeletonType.values(), ((Skeleton) entity).getSkeletonType());
storeLiving((LivingEntity) entity);
return;
case ARMOR_STAND:
ArmorStand stand = (ArmorStand) entity;
this.inventory = new ItemStack[]{stand.getItemInHand().clone(), stand.getHelmet().clone(), stand.getChestplate().clone(),
stand.getLeggings().clone(), stand.getBoots().clone()};
this.inventory =
new ItemStack[] {stand.getItemInHand().clone(), stand.getHelmet().clone(),
stand.getChestplate().clone(), stand.getLeggings().clone(),
stand.getBoots().clone()};
storeLiving(stand);
this.stand = new ArmorStandStats();
@ -315,13 +296,11 @@ public class EntityWrapper {
}
}
@Override
public boolean equals(Object obj) {
@Override public boolean equals(Object obj) {
return this.hash == obj.hashCode();
}
@Override
public int hashCode() {
@Override public int hashCode() {
return this.hash;
}
@ -473,7 +452,8 @@ public class EntityWrapper {
if (this.base.passenger != null) {
try {
entity.setPassenger(this.base.passenger.spawn(world, xOffset, zOffset));
} catch (Exception ignored) { }
} catch (Exception ignored) {
}
}
if (this.base.fall != 0) {
entity.setFallDistance(this.base.fall);
@ -488,7 +468,8 @@ public class EntityWrapper {
if (this.depth == 1) {
return entity;
}
if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_10_0) || entity instanceof ArmorStand) {
if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_10_0)
|| entity instanceof ArmorStand) {
if (this.noGravity) {
entity.setGravity(false);
}
@ -642,27 +623,37 @@ public class EntityWrapper {
stand.setBoots(this.inventory[4]);
}
if (this.stand.head[0] != 0 || this.stand.head[1] != 0 || this.stand.head[2] != 0) {
EulerAngle pose = new EulerAngle(this.stand.head[0], this.stand.head[1], this.stand.head[2]);
EulerAngle pose =
new EulerAngle(this.stand.head[0], this.stand.head[1], this.stand.head[2]);
stand.setHeadPose(pose);
}
if (this.stand.body[0] != 0 || this.stand.body[1] != 0 || this.stand.body[2] != 0) {
EulerAngle pose = new EulerAngle(this.stand.body[0], this.stand.body[1], this.stand.body[2]);
EulerAngle pose =
new EulerAngle(this.stand.body[0], this.stand.body[1], this.stand.body[2]);
stand.setBodyPose(pose);
}
if (this.stand.leftLeg[0] != 0 || this.stand.leftLeg[1] != 0 || this.stand.leftLeg[2] != 0) {
EulerAngle pose = new EulerAngle(this.stand.leftLeg[0], this.stand.leftLeg[1], this.stand.leftLeg[2]);
if (this.stand.leftLeg[0] != 0 || this.stand.leftLeg[1] != 0
|| this.stand.leftLeg[2] != 0) {
EulerAngle pose = new EulerAngle(this.stand.leftLeg[0], this.stand.leftLeg[1],
this.stand.leftLeg[2]);
stand.setLeftLegPose(pose);
}
if (this.stand.rightLeg[0] != 0 || this.stand.rightLeg[1] != 0 || this.stand.rightLeg[2] != 0) {
EulerAngle pose = new EulerAngle(this.stand.rightLeg[0], this.stand.rightLeg[1], this.stand.rightLeg[2]);
if (this.stand.rightLeg[0] != 0 || this.stand.rightLeg[1] != 0
|| this.stand.rightLeg[2] != 0) {
EulerAngle pose = new EulerAngle(this.stand.rightLeg[0], this.stand.rightLeg[1],
this.stand.rightLeg[2]);
stand.setRightLegPose(pose);
}
if (this.stand.leftArm[0] != 0 || this.stand.leftArm[1] != 0 || this.stand.leftArm[2] != 0) {
EulerAngle pose = new EulerAngle(this.stand.leftArm[0], this.stand.leftArm[1], this.stand.leftArm[2]);
if (this.stand.leftArm[0] != 0 || this.stand.leftArm[1] != 0
|| this.stand.leftArm[2] != 0) {
EulerAngle pose = new EulerAngle(this.stand.leftArm[0], this.stand.leftArm[1],
this.stand.leftArm[2]);
stand.setLeftArmPose(pose);
}
if (this.stand.rightArm[0] != 0 || this.stand.rightArm[1] != 0 || this.stand.rightArm[2] != 0) {
EulerAngle pose = new EulerAngle(this.stand.rightArm[0], this.stand.rightArm[1], this.stand.rightArm[2]);
if (this.stand.rightArm[0] != 0 || this.stand.rightArm[1] != 0
|| this.stand.rightArm[2] != 0) {
EulerAngle pose = new EulerAngle(this.stand.rightArm[0], this.stand.rightArm[1],
this.stand.rightArm[2]);
stand.setRightArmPose(pose);
}
if (this.stand.invisible) {
@ -729,9 +720,7 @@ public class EntityWrapper {
return 0;
}
@SuppressWarnings("deprecation")
@Override
public String toString() {
@SuppressWarnings("deprecation") @Override public String toString() {
return String.format("[%s, x=%s, y=%s, z=%s]", type.getName(), x, y, z);
}
}

View File

@ -1,10 +1,6 @@
package com.plotsquared.bukkit.object.schematic;
import com.intellectualcrafters.jnbt.ByteTag;
import com.intellectualcrafters.jnbt.CompoundTag;
import com.intellectualcrafters.jnbt.ListTag;
import com.intellectualcrafters.jnbt.ShortTag;
import com.intellectualcrafters.jnbt.Tag;
import com.intellectualcrafters.jnbt.*;
import com.intellectualcrafters.plot.object.schematic.ItemType;
import com.intellectualcrafters.plot.util.MathMan;
import com.plotsquared.bukkit.util.BukkitUtil;
@ -89,7 +85,8 @@ public class StateWrapper {
InventoryHolder inv = (InventoryHolder) this.state;
ItemStack[] contents = inv.getInventory().getContents();
Map<String, Tag> values = new HashMap<>();
values.put("Items", new ListTag("Items", CompoundTag.class, serializeInventory(contents)));
values.put("Items",
new ListTag("Items", CompoundTag.class, serializeInventory(contents)));
return new CompoundTag(values);
}
return null;

View File

@ -18,7 +18,8 @@ public class DefaultTitleManager extends TitleManager {
* @param stayTime Stay on screen time
* @param fadeOutTime Fade out time
*/
DefaultTitleManager(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) {
DefaultTitleManager(String title, String subtitle, int fadeInTime, int stayTime,
int fadeOutTime) {
super(title, subtitle, fadeInTime, stayTime, fadeOutTime);
}
@ -32,7 +33,8 @@ public class DefaultTitleManager extends TitleManager {
this.nmsChatSerializer = Reflection.getNMSClass("ChatSerializer");
}
@Override public void send(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
@Override public void send(Player player)
throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
if (this.packetTitle != null) {
// First reset previous settings
resetTitle(player);
@ -41,38 +43,44 @@ public class DefaultTitleManager extends TitleManager {
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = this.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent, Integer.TYPE, Integer.TYPE, Integer.TYPE)
Object packet = this.packetTitle
.getConstructor(this.packetActions, this.chatBaseComponent, Integer.TYPE,
Integer.TYPE, Integer.TYPE)
.newInstance(actions[2], null, this.fadeInTime * (this.ticks ? 1 : 20),
this.stayTime * (this.ticks ? 1 : 20), this.fadeOutTime * (this.ticks ? 1 : 20));
this.stayTime * (this.ticks ? 1 : 20),
this.fadeOutTime * (this.ticks ? 1 : 20));
// Send if set
if (this.fadeInTime != -1 && this.fadeOutTime != -1 && this.stayTime != -1) {
sendPacket.invoke(connection, packet);
}
// Send title
Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getTitle()) + "\",color:" + this.titleColor.name().toLowerCase()
+ '}');
packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[0], serialized);
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getTitle())
+ "\",color:" + this.titleColor.name().toLowerCase() + '}');
packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent)
.newInstance(actions[0], serialized);
sendPacket.invoke(connection, packet);
if (!this.getSubtitle().isEmpty()) {
// Send subtitle if present
serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getSubtitle()) + "\",color:" + this.subtitleColor.name()
.toLowerCase() + '}');
packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[1], serialized);
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getSubtitle())
+ "\",color:" + this.subtitleColor.name().toLowerCase() + '}');
packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent)
.newInstance(actions[1], serialized);
sendPacket.invoke(connection, packet);
}
}
}
@Override
public void clearTitle(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
@Override public void clearTitle(Player player)
throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
// Send timings first
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = this.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[3], null);
Object packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent)
.newInstance(actions[3], null);
sendPacket.invoke(connection, packet);
}
@ -84,14 +92,15 @@ public class DefaultTitleManager extends TitleManager {
* @throws ReflectiveOperationException
* @throws SecurityException
*/
@Override
public void resetTitle(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
@Override public void resetTitle(Player player)
throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
// Send timings first
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = this.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[4], null);
Object packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent)
.newInstance(actions[4], null);
sendPacket.invoke(connection, packet);
}
@ -108,7 +117,8 @@ public class DefaultTitleManager extends TitleManager {
Method getMethod(Class<?> clazz, String name, Class<?>... args) {
for (Method m : clazz.getMethods()) {
if (m.getName().equals(name) && (args.length == 0 || classListEqual(args, m.getParameterTypes()))) {
if (m.getName().equals(name) && (args.length == 0 || classListEqual(args,
m.getParameterTypes()))) {
m.setAccessible(true);
return m;
}

View File

@ -17,23 +17,23 @@ public class DefaultTitleManager_183 extends DefaultTitleManager {
* @param stayTime Stay on screen time
* @param fadeOutTime Fade out time
*/
DefaultTitleManager_183(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) {
DefaultTitleManager_183(String title, String subtitle, int fadeInTime, int stayTime,
int fadeOutTime) {
super(title, subtitle, fadeInTime, stayTime, fadeOutTime);
}
/**
* Load spigot and NMS classes.
*/
@Override
void loadClasses() {
@Override void loadClasses() {
this.packetTitle = Reflection.getNMSClass("PacketPlayOutTitle");
this.chatBaseComponent = Reflection.getNMSClass("IChatBaseComponent");
this.packetActions = Reflection.getNMSClass("PacketPlayOutTitle$EnumTitleAction");
this.nmsChatSerializer = Reflection.getNMSClass("IChatBaseComponent$ChatSerializer");
}
@Override
public void send(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
@Override public void send(Player player)
throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
if (this.packetTitle != null) {
// First reset previous settings
resetTitle(player);
@ -43,26 +43,29 @@ public class DefaultTitleManager_183 extends DefaultTitleManager {
Object[] actions = this.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = this.packetTitle
.getConstructor(this.packetActions, this.chatBaseComponent, Integer.TYPE, Integer.TYPE, Integer.TYPE)
.newInstance(actions[2], null,
this.fadeInTime * (this.ticks ? 1 : 20),
this.stayTime * (this.ticks ? 1 : 20), this.fadeOutTime * (this.ticks ? 1 : 20));
.getConstructor(this.packetActions, this.chatBaseComponent, Integer.TYPE,
Integer.TYPE, Integer.TYPE)
.newInstance(actions[2], null, this.fadeInTime * (this.ticks ? 1 : 20),
this.stayTime * (this.ticks ? 1 : 20),
this.fadeOutTime * (this.ticks ? 1 : 20));
// Send if set
if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) && (this.stayTime != -1)) {
sendPacket.invoke(connection, packet);
}
// Send title
Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getTitle()) + "\",color:" + this.titleColor.name().toLowerCase()
+ "}");
packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[0], serialized);
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getTitle())
+ "\",color:" + this.titleColor.name().toLowerCase() + "}");
packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent)
.newInstance(actions[0], serialized);
sendPacket.invoke(connection, packet);
if (!this.getSubtitle().isEmpty()) {
// Send subtitle if present
serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getSubtitle()) + "\",color:" + this.subtitleColor.name()
.toLowerCase() + "}");
packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[1], serialized);
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getSubtitle())
+ "\",color:" + this.subtitleColor.name().toLowerCase() + "}");
packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent)
.newInstance(actions[1], serialized);
sendPacket.invoke(connection, packet);
}
}

View File

@ -7,8 +7,7 @@ import com.plotsquared.bukkit.object.BukkitPlayer;
import com.plotsquared.bukkit.util.BukkitVersion;
import org.bukkit.entity.Player;
@SuppressWarnings("deprecation")
public class DefaultTitle_111 extends AbstractTitle {
@SuppressWarnings("deprecation") public class DefaultTitle_111 extends AbstractTitle {
private final boolean valid;
@ -24,7 +23,8 @@ public class DefaultTitle_111 extends AbstractTitle {
TitleManager_1_11 title = new TitleManager_1_11(head, sub, in, delay, out);
title.send(playerObj);
return;
} catch (Throwable ignored) {}
} catch (Throwable ignored) {
}
}
AbstractTitle.TITLE_CLASS = new DefaultTitle_180();
AbstractTitle.TITLE_CLASS.sendTitle(player, head, sub, in, delay, out);

View File

@ -6,8 +6,7 @@ import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.bukkit.object.BukkitPlayer;
import org.bukkit.entity.Player;
@SuppressWarnings("deprecation")
public class DefaultTitle_19 extends AbstractTitle {
@SuppressWarnings("deprecation") public class DefaultTitle_19 extends AbstractTitle {
@Override
public void sendTitle(PlotPlayer player, String head, String sub, int in, int delay, int out) {
@ -15,8 +14,7 @@ public class DefaultTitle_19 extends AbstractTitle {
final Player playerObj = ((BukkitPlayer) player).player;
playerObj.sendTitle(head, sub);
TaskManager.runTaskLater(new Runnable() {
@Override
public void run() {
@Override public void run() {
playerObj.sendTitle("", "");
}
}, delay * 20);

View File

@ -26,14 +26,14 @@ public class HackTitleManager extends TitleManager {
/**
* Load spigot and NMS classes.
*/
@Override
void loadClasses() {
@Override void loadClasses() {
this.packetTitle = getClass("org.spigotmc.ProtocolInjector$PacketTitle");
this.packetActions = getClass("org.spigotmc.ProtocolInjector$PacketTitle$Action");
this.nmsChatSerializer = Reflection.getNMSClass("ChatSerializer");
}
@Override public void send(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
@Override public void send(Player player)
throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
if ((getProtocolVersion(player) >= 47) && isSpigot() && (this.packetTitle != null)) {
// First reset previous settings
resetTitle(player);
@ -42,8 +42,9 @@ public class HackTitleManager extends TitleManager {
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = this.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = this.packetTitle.getConstructor(this.packetActions, Integer.TYPE, Integer.TYPE, Integer.TYPE).newInstance(actions[2],
this.fadeInTime * (this.ticks ? 1 : 20),
Object packet = this.packetTitle
.getConstructor(this.packetActions, Integer.TYPE, Integer.TYPE, Integer.TYPE)
.newInstance(actions[2], this.fadeInTime * (this.ticks ? 1 : 20),
this.stayTime * (this.ticks ? 1 : 20),
this.fadeOutTime * (this.ticks ? 1 : 20));
// Send if set
@ -52,43 +53,49 @@ public class HackTitleManager extends TitleManager {
}
// Send title
Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getTitle()) + "\",color:" + this.titleColor.name().toLowerCase()
+ "}");
packet = this.packetTitle.getConstructor(this.packetActions, Reflection.getNMSClass("IChatBaseComponent"))
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getTitle())
+ "\",color:" + this.titleColor.name().toLowerCase() + "}");
packet = this.packetTitle
.getConstructor(this.packetActions, Reflection.getNMSClass("IChatBaseComponent"))
.newInstance(actions[0], serialized);
sendPacket.invoke(connection, packet);
if (!this.getSubtitle().isEmpty()) {
// Send subtitle if present
serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getSubtitle()) + "\",color:" + this.subtitleColor.name()
.toLowerCase() + "}");
packet = this.packetTitle.getConstructor(this.packetActions, Reflection.getNMSClass("IChatBaseComponent"))
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getSubtitle())
+ "\",color:" + this.subtitleColor.name().toLowerCase() + "}");
packet = this.packetTitle.getConstructor(this.packetActions,
Reflection.getNMSClass("IChatBaseComponent"))
.newInstance(actions[1], serialized);
sendPacket.invoke(connection, packet);
}
}
}
@Override public void clearTitle(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
@Override public void clearTitle(Player player)
throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
if ((getProtocolVersion(player) >= 47) && isSpigot()) {
// Send timings first
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = this.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = this.packetTitle.getConstructor(this.packetActions).newInstance(actions[3]);
Object packet =
this.packetTitle.getConstructor(this.packetActions).newInstance(actions[3]);
sendPacket.invoke(connection, packet);
}
}
@Override public void resetTitle(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
@Override public void resetTitle(Player player)
throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
if ((getProtocolVersion(player) >= 47) && isSpigot()) {
// Send timings first
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = this.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = this.packetTitle.getConstructor(this.packetActions).newInstance(actions[4]);
Object packet =
this.packetTitle.getConstructor(this.packetActions).newInstance(actions[4]);
sendPacket.invoke(connection, packet);
}
}
@ -102,7 +109,8 @@ public class HackTitleManager extends TitleManager {
* @throws ReflectiveOperationException
* @throws SecurityException
*/
private int getProtocolVersion(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
private int getProtocolVersion(Player player)
throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object networkManager = getValue("networkManager", connection);
@ -127,15 +135,18 @@ public class HackTitleManager extends TitleManager {
private Class<?> getClass(String namespace) {
try {
return Class.forName(namespace);
} catch (ClassNotFoundException ignored) {}
} catch (ClassNotFoundException ignored) {
}
return null;
}
private Field getField(String name, Class<?> clazz) throws NoSuchFieldException, SecurityException {
private Field getField(String name, Class<?> clazz)
throws NoSuchFieldException, SecurityException {
return clazz.getDeclaredField(name);
}
private Object getValue(String name, Object obj) throws ReflectiveOperationException, SecurityException, IllegalArgumentException {
private Object getValue(String name, Object obj)
throws ReflectiveOperationException, SecurityException, IllegalArgumentException {
Field f = getField(name, obj.getClass());
f.setAccessible(true);
return f.get(obj);
@ -154,7 +165,8 @@ public class HackTitleManager extends TitleManager {
private Method getMethod(Class<?> clazz, String name, Class<?>... args) {
for (Method m : clazz.getMethods()) {
if (m.getName().equals(name) && ((args.length == 0) || classListEqual(args, m.getParameterTypes()))) {
if (m.getName().equals(name) && ((args.length == 0) || classListEqual(args,
m.getParameterTypes()))) {
m.setAccessible(true);
return m;
}

View File

@ -12,17 +12,13 @@ import java.util.Map;
public abstract class TitleManager {
private static final Map<Class<?>, Class<?>> CORRESPONDING_TYPES = new HashMap<>();
/* Title packet */
Class<?> packetTitle;
/* Title packet actions ENUM */
Class<?> packetActions;
/* Chat serializer */
Class<?> nmsChatSerializer;
/* Title packet */ Class<?> packetTitle;
/* Title packet actions ENUM */ Class<?> packetActions;
/* Chat serializer */ Class<?> nmsChatSerializer;
Class<?> chatBaseComponent;
ChatColor titleColor = ChatColor.WHITE;
ChatColor subtitleColor = ChatColor.WHITE;
/* Title timings */
int fadeInTime = -1;
/* Title timings */ int fadeInTime = -1;
int stayTime = -1;
int fadeOutTime = -1;
boolean ticks = false;
@ -154,7 +150,8 @@ public abstract class TitleManager {
* @throws ReflectiveOperationException
* @throws SecurityException
*/
public abstract void send(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException;
public abstract void send(Player player)
throws IllegalArgumentException, ReflectiveOperationException, SecurityException;
/**
* Broadcasts the title to all players.
@ -175,7 +172,8 @@ public abstract class TitleManager {
* @throws ReflectiveOperationException
* @throws SecurityException
*/
public abstract void clearTitle(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException;
public abstract void clearTitle(Player player)
throws IllegalArgumentException, ReflectiveOperationException, SecurityException;
/**
* Resets the title settings.
@ -185,7 +183,8 @@ public abstract class TitleManager {
* @throws ReflectiveOperationException
* @throws SecurityException
*/
public abstract void resetTitle(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException;
public abstract void resetTitle(Player player)
throws IllegalArgumentException, ReflectiveOperationException, SecurityException;
private Class<?> getPrimitiveType(Class<?> clazz) {
if (CORRESPONDING_TYPES.containsKey(clazz)) {

View File

@ -1,14 +1,14 @@
package com.plotsquared.bukkit.titles;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
/**
* Minecraft 1.8 Title
* For 1.11
@ -17,6 +17,8 @@ import org.bukkit.entity.Player;
* @version 1.1.0
*/
public class TitleManager_1_11 {
private static final Map<Class<?>, Class<?>> CORRESPONDING_TYPES =
new HashMap<Class<?>, Class<?>>();
/* Title packet */
private static Class<?> packetTitle;
/* Title packet actions ENUM */
@ -43,8 +45,6 @@ public class TitleManager_1_11 {
private int fadeOutTime = -1;
private boolean ticks = false;
private static final Map<Class<?>, Class<?>> CORRESPONDING_TYPES = new HashMap<Class<?>, Class<?>>();
public TitleManager_1_11() {
loadClasses();
}
@ -98,7 +98,8 @@ public class TitleManager_1_11 {
* @param stayTime Stay on screen time
* @param fadeOutTime Fade out time
*/
public TitleManager_1_11(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) {
public TitleManager_1_11(String title, String subtitle, int fadeInTime, int stayTime,
int fadeOutTime) {
this.title = title;
this.subtitle = subtitle;
this.fadeInTime = fadeInTime;
@ -107,6 +108,15 @@ public class TitleManager_1_11 {
loadClasses();
}
private static boolean equalsTypeArray(Class<?>[] a, Class<?>[] o) {
if (a.length != o.length)
return false;
for (int i = 0; i < a.length; i++)
if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i]))
return false;
return true;
}
/**
* Load spigot and NMS classes
*/
@ -118,23 +128,13 @@ public class TitleManager_1_11 {
nmsChatSerializer = getNMSClass("ChatComponentText");
nmsPlayer = getNMSClass("EntityPlayer");
nmsPlayerConnection = getNMSClass("PlayerConnection");
playerConnection = getField(nmsPlayer,
"playerConnection");
playerConnection = getField(nmsPlayer, "playerConnection");
sendPacket = getMethod(nmsPlayerConnection, "sendPacket");
obcPlayer = getOBCClass("entity.CraftPlayer");
methodPlayerGetHandle = getMethod("getHandle", obcPlayer);
}
}
/**
* Set title text
*
* @param title Title
*/
public void setTitle(String title) {
this.title = title;
}
/**
* Get title text
*
@ -145,12 +145,12 @@ public class TitleManager_1_11 {
}
/**
* Set subtitle text
* Set title text
*
* @param subtitle Subtitle text
* @param title Title
*/
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
public void setTitle(String title) {
this.title = title;
}
/**
@ -163,48 +163,12 @@ public class TitleManager_1_11 {
}
/**
* Set the title color
* Set subtitle text
*
* @param color Chat color
* @param subtitle Subtitle text
*/
public void setTitleColor(ChatColor color) {
this.titleColor = color;
}
/**
* Set the subtitle color
*
* @param color Chat color
*/
public void setSubtitleColor(ChatColor color) {
this.subtitleColor = color;
}
/**
* Set title fade in time
*
* @param time Time
*/
public void setFadeInTime(int time) {
this.fadeInTime = time;
}
/**
* Set title fade out time
*
* @param time Time
*/
public void setFadeOutTime(int time) {
this.fadeOutTime = time;
}
/**
* Set title stay time
*
* @param time Time
*/
public void setStayTime(int time) {
this.stayTime = time;
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
/**
@ -235,12 +199,10 @@ public class TitleManager_1_11 {
Object handle = getHandle(player);
Object connection = playerConnection.get(handle);
Object[] actions = packetActions.getEnumConstants();
Object packet = packetTitle.getConstructor(packetActions,
chatBaseComponent, Integer.TYPE, Integer.TYPE,
Integer.TYPE).newInstance(actions[3], null,
fadeInTime * (ticks ? 1 : 20),
stayTime * (ticks ? 1 : 20),
fadeOutTime * (ticks ? 1 : 20));
Object packet = packetTitle
.getConstructor(packetActions, chatBaseComponent, Integer.TYPE, Integer.TYPE,
Integer.TYPE).newInstance(actions[3], null, fadeInTime * (ticks ? 1 : 20),
stayTime * (ticks ? 1 : 20), fadeOutTime * (ticks ? 1 : 20));
// Send if set
if (fadeInTime != -1 && fadeOutTime != -1 && stayTime != -1)
sendPacket.invoke(connection, packet);
@ -248,22 +210,18 @@ public class TitleManager_1_11 {
Object serialized;
if (!subtitle.equals("")) {
// Send subtitle if present
serialized = nmsChatSerializer.getConstructor(String.class)
.newInstance(subtitleColor +
ChatColor.translateAlternateColorCodes('&',
subtitle));
packet = packetTitle.getConstructor(packetActions,
chatBaseComponent).newInstance(actions[1],
serialized);
serialized = nmsChatSerializer.getConstructor(String.class).newInstance(
subtitleColor + ChatColor.translateAlternateColorCodes('&', subtitle));
packet = packetTitle.getConstructor(packetActions, chatBaseComponent)
.newInstance(actions[1], serialized);
sendPacket.invoke(connection, packet);
}
// Send title
serialized = nmsChatSerializer.getConstructor(
String.class).newInstance(titleColor +
ChatColor.translateAlternateColorCodes('&', title));
packet = packetTitle.getConstructor(packetActions,
chatBaseComponent).newInstance(actions[0], serialized);
serialized = nmsChatSerializer.getConstructor(String.class)
.newInstance(titleColor + ChatColor.translateAlternateColorCodes('&', title));
packet = packetTitle.getConstructor(packetActions, chatBaseComponent)
.newInstance(actions[0], serialized);
sendPacket.invoke(connection, packet);
} catch (Exception e) {
e.printStackTrace();
@ -278,19 +236,12 @@ public class TitleManager_1_11 {
Object connection = playerConnection.get(handle);
Object[] actions = TitleManager_1_11.packetActions.getEnumConstants();
Object packet = TitleManager_1_11.packetTitle.getConstructor(
new Class[]{TitleManager_1_11.packetActions, chatBaseComponent,
Integer.TYPE, Integer.TYPE, Integer.TYPE})
.newInstance(
actions[3],
null,
this.fadeInTime
* (this.ticks ? 1 : 20),
this.stayTime
* (this.ticks ? 1 : 20),
this.fadeOutTime
* (this.ticks ? 1 : 20));
if ((this.fadeInTime != -1) && (this.fadeOutTime != -1)
&& (this.stayTime != -1)) {
new Class[] {TitleManager_1_11.packetActions, chatBaseComponent, Integer.TYPE,
Integer.TYPE, Integer.TYPE})
.newInstance(actions[3], null, this.fadeInTime * (this.ticks ? 1 : 20),
this.stayTime * (this.ticks ? 1 : 20),
this.fadeOutTime * (this.ticks ? 1 : 20));
if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) && (this.stayTime != -1)) {
sendPacket.invoke(connection, packet);
}
} catch (Exception e) {
@ -303,21 +254,14 @@ public class TitleManager_1_11 {
if (TitleManager_1_11.packetTitle != null) {
try {
Object handle = getHandle(player);
Object connection = getField(handle.getClass(),
"playerConnection").get(handle);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = TitleManager_1_11.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(),
"sendPacket");
Object serialized = nmsChatSerializer.getConstructor(
String.class)
.newInstance(titleColor +
ChatColor.translateAlternateColorCodes('&',
this.title));
Object packet = TitleManager_1_11.packetTitle
.getConstructor(
new Class[]{TitleManager_1_11.packetActions,
chatBaseComponent}).newInstance(
actions[0], serialized);
Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object serialized = nmsChatSerializer.getConstructor(String.class).newInstance(
titleColor + ChatColor.translateAlternateColorCodes('&', this.title));
Object packet = TitleManager_1_11.packetTitle.getConstructor(
new Class[] {TitleManager_1_11.packetActions, chatBaseComponent})
.newInstance(actions[0], serialized);
sendPacket.invoke(connection, packet);
} catch (Exception e) {
e.printStackTrace();
@ -331,16 +275,11 @@ public class TitleManager_1_11 {
Object handle = getHandle(player);
Object connection = playerConnection.get(handle);
Object[] actions = TitleManager_1_11.packetActions.getEnumConstants();
Object serialized = nmsChatSerializer.getConstructor(
String.class)
.newInstance(subtitleColor +
ChatColor.translateAlternateColorCodes('&',
this.subtitle));
Object packet = TitleManager_1_11.packetTitle
.getConstructor(
new Class[]{TitleManager_1_11.packetActions,
chatBaseComponent}).newInstance(
actions[1], serialized);
Object serialized = nmsChatSerializer.getConstructor(String.class).newInstance(
subtitleColor + ChatColor.translateAlternateColorCodes('&', this.subtitle));
Object packet = TitleManager_1_11.packetTitle.getConstructor(
new Class[] {TitleManager_1_11.packetActions, chatBaseComponent})
.newInstance(actions[1], serialized);
sendPacket.invoke(connection, packet);
} catch (Exception e) {
e.printStackTrace();
@ -368,8 +307,8 @@ public class TitleManager_1_11 {
Object handle = getHandle(player);
Object connection = playerConnection.get(handle);
Object[] actions = packetActions.getEnumConstants();
Object packet = packetTitle.getConstructor(packetActions,
chatBaseComponent).newInstance(actions[4], null);
Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent)
.newInstance(actions[4], null);
sendPacket.invoke(connection, packet);
} catch (Exception e) {
e.printStackTrace();
@ -387,8 +326,8 @@ public class TitleManager_1_11 {
Object handle = getHandle(player);
Object connection = playerConnection.get(handle);
Object[] actions = packetActions.getEnumConstants();
Object packet = packetTitle.getConstructor(packetActions,
chatBaseComponent).newInstance(actions[5], null);
Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent)
.newInstance(actions[5], null);
sendPacket.invoke(connection, packet);
} catch (Exception e) {
e.printStackTrace();
@ -396,8 +335,7 @@ public class TitleManager_1_11 {
}
private Class<?> getPrimitiveType(Class<?> clazz) {
return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES
.get(clazz) : clazz;
return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz;
}
private Class<?>[] toPrimitiveTypeArray(Class<?>[] classes) {
@ -408,15 +346,6 @@ public class TitleManager_1_11 {
return types;
}
private static boolean equalsTypeArray(Class<?>[] a, Class<?>[] o) {
if (a.length != o.length)
return false;
for (int i = 0; i < a.length; i++)
if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i]))
return false;
return true;
}
private Object getHandle(Player player) {
try {
return methodPlayerGetHandle.invoke(player);
@ -426,8 +355,7 @@ public class TitleManager_1_11 {
}
}
private Method getMethod(String name, Class<?> clazz,
Class<?>... paramTypes) {
private Method getMethod(String name, Class<?> clazz, Class<?>... paramTypes) {
Class<?>[] t = toPrimitiveTypeArray(paramTypes);
for (Method m : clazz.getMethods()) {
Class<?>[] types = toPrimitiveTypeArray(m.getParameterTypes());
@ -465,7 +393,6 @@ public class TitleManager_1_11 {
return clazz;
}
private Field getField(Class<?> clazz, String name) {
try {
Field field = clazz.getDeclaredField(name);
@ -479,8 +406,7 @@ public class TitleManager_1_11 {
private Method getMethod(Class<?> clazz, String name, Class<?>... args) {
for (Method m : clazz.getMethods())
if (m.getName().equals(name)
&& (args.length == 0 || ClassListEqual(args,
if (m.getName().equals(name) && (args.length == 0 || ClassListEqual(args,
m.getParameterTypes()))) {
m.setAccessible(true);
return m;
@ -504,22 +430,67 @@ public class TitleManager_1_11 {
return titleColor;
}
/**
* Set the title color
*
* @param color Chat color
*/
public void setTitleColor(ChatColor color) {
this.titleColor = color;
}
public ChatColor getSubtitleColor() {
return subtitleColor;
}
/**
* Set the subtitle color
*
* @param color Chat color
*/
public void setSubtitleColor(ChatColor color) {
this.subtitleColor = color;
}
public int getFadeInTime() {
return fadeInTime;
}
/**
* Set title fade in time
*
* @param time Time
*/
public void setFadeInTime(int time) {
this.fadeInTime = time;
}
public int getFadeOutTime() {
return fadeOutTime;
}
/**
* Set title fade out time
*
* @param time Time
*/
public void setFadeOutTime(int time) {
this.fadeOutTime = time;
}
public int getStayTime() {
return stayTime;
}
/**
* Set title stay time
*
* @param time Time
*/
public void setStayTime(int time) {
this.stayTime = time;
}
public boolean isTicks() {
return ticks;
}

View File

@ -15,18 +15,15 @@ import java.util.List;
public class BukkitChatManager extends ChatManager<FancyMessage> {
@Override
public FancyMessage builder() {
@Override public FancyMessage builder() {
return new FancyMessage("");
}
@Override
public void color(PlotMessage message, String color) {
@Override public void color(PlotMessage message, String color) {
message.$(this).color(ChatColor.getByChar(C.color(color).substring(1)));
}
@Override
public void tooltip(PlotMessage message, PlotMessage... tooltips) {
@Override public void tooltip(PlotMessage message, PlotMessage... tooltips) {
List<FancyMessage> lines = new ArrayList<>();
for (PlotMessage tooltip : tooltips) {
lines.add(tooltip.$(this));
@ -34,18 +31,15 @@ public class BukkitChatManager extends ChatManager<FancyMessage> {
message.$(this).formattedTooltip(lines);
}
@Override
public void command(PlotMessage message, String command) {
@Override public void command(PlotMessage message, String command) {
message.$(this).command(command);
}
@Override
public void text(PlotMessage message, String text) {
@Override public void text(PlotMessage message, String text) {
message.$(this).then(ChatColor.stripColor(text));
}
@Override
public void send(PlotMessage plotMessage, PlotPlayer player) {
@Override public void send(PlotMessage plotMessage, PlotPlayer player) {
if (player instanceof ConsolePlayer || !Settings.Chat.INTERACTIVE) {
player.sendMessage(plotMessage.$(this).toOldMessageFormat());
} else {
@ -53,8 +47,7 @@ public class BukkitChatManager extends ChatManager<FancyMessage> {
}
}
@Override
public void suggest(PlotMessage plotMessage, String command) {
@Override public void suggest(PlotMessage plotMessage, String command) {
plotMessage.$(this).suggest(command);
}

View File

@ -2,61 +2,23 @@ package com.plotsquared.bukkit.util;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.generator.AugmentedUtils;
import com.intellectualcrafters.plot.object.BlockLoc;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.object.*;
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.PlotLoc;
import com.intellectualcrafters.plot.object.RegionWrapper;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.block.GlobalBlockQueue;
import com.intellectualcrafters.plot.util.block.LocalBlockQueue;
import com.intellectualcrafters.plot.util.block.ScopedLocalBlockQueue;
import com.plotsquared.bukkit.object.entity.EntityWrapper;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.DyeColor;
import org.bukkit.Material;
import org.bukkit.Note;
import org.bukkit.SkullType;
import org.bukkit.World;
import org.bukkit.block.Banner;
import org.bukkit.block.Beacon;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.block.BrewingStand;
import org.bukkit.block.CommandBlock;
import org.bukkit.block.CreatureSpawner;
import org.bukkit.block.Dispenser;
import org.bukkit.block.Dropper;
import org.bukkit.block.Furnace;
import org.bukkit.block.Hopper;
import org.bukkit.block.Jukebox;
import org.bukkit.block.NoteBlock;
import org.bukkit.block.Sign;
import org.bukkit.block.Skull;
import org.bukkit.*;
import org.bukkit.block.*;
import org.bukkit.block.banner.Pattern;
import org.bukkit.entity.Animals;
import org.bukkit.entity.Creature;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.entity.*;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.Map.Entry;
import java.util.Set;
public class BukkitChunkManager extends ChunkManager {
@ -73,7 +35,8 @@ public class BukkitChunkManager extends ChunkManager {
return 0;
}
public static ContentMap swapChunk(World world1, World world2, Chunk pos1, Chunk pos2, RegionWrapper r1, RegionWrapper r2) {
public static ContentMap swapChunk(World world1, World world2, Chunk pos1, Chunk pos2,
RegionWrapper r1, RegionWrapper r2) {
ContentMap map = new ContentMap();
int relX = r2.minX - r1.minX;
int relZ = r2.minZ - r1.minZ;
@ -127,8 +90,7 @@ public class BukkitChunkManager extends ChunkManager {
return map;
}
@Override
public Set<ChunkLoc> getChunkChunks(String world) {
@Override public Set<ChunkLoc> getChunkChunks(String world) {
Set<ChunkLoc> chunks = super.getChunkChunks(world);
for (Chunk chunk : Bukkit.getWorld(world).getLoadedChunks()) {
ChunkLoc loc = new ChunkLoc(chunk.getX() >> 5, chunk.getZ() >> 5);
@ -139,13 +101,15 @@ public class BukkitChunkManager extends ChunkManager {
return chunks;
}
@Override
public boolean copyRegion(Location pos1, Location pos2, Location newPos, final Runnable whenDone) {
@Override public boolean copyRegion(Location pos1, Location pos2, Location newPos,
final Runnable whenDone) {
final int relX = newPos.getX() - pos1.getX();
final int relZ = newPos.getZ() - pos1.getZ();
Location pos4 = new Location(newPos.getWorld(), newPos.getX() + relX, 256, newPos.getZ() + relZ);
Location pos4 =
new Location(newPos.getWorld(), newPos.getX() + relX, 256, newPos.getZ() + relZ);
final RegionWrapper region = new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ());
final RegionWrapper region =
new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ());
final World oldWorld = Bukkit.getWorld(pos1.getWorld());
final World newWorld = Bukkit.getWorld(newPos.getWorld());
final String newWorldName = newWorld.getName();
@ -153,8 +117,7 @@ public class BukkitChunkManager extends ChunkManager {
final ContentMap map = new ContentMap();
final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(newWorldName, false);
ChunkManager.chunkTask(pos1, pos2, new RunnableVal<int[]>() {
@Override
public void run(int[] value) {
@Override public void run(int[] value) {
int bx = value[2];
int bz = value[3];
int tx = value[4];
@ -171,8 +134,7 @@ public class BukkitChunkManager extends ChunkManager {
}
}
}, new Runnable() {
@Override
public void run() {
@Override public void run() {
for (Entry<PlotLoc, PlotBlock[]> entry : map.allBlocks.entrySet()) {
PlotLoc loc = entry.getKey();
PlotBlock[] blocks = entry.getValue();
@ -185,8 +147,7 @@ public class BukkitChunkManager extends ChunkManager {
}
queue.enqueue();
GlobalBlockQueue.IMP.addTask(new Runnable() {
@Override
public void run() {
@Override public void run() {
map.restoreBlocks(newWorld, 0, 0);
map.restoreEntities(newWorld, relX, relZ);
TaskManager.runTask(whenDone);
@ -197,8 +158,8 @@ public class BukkitChunkManager extends ChunkManager {
return true;
}
@Override
public boolean regenerateRegion(final Location pos1, final Location pos2, final boolean ignoreAugment, final Runnable whenDone) {
@Override public boolean regenerateRegion(final Location pos1, final Location pos2,
final boolean ignoreAugment, final Runnable whenDone) {
final String world = pos1.getWorld();
final int p1x = pos1.getX();
@ -219,8 +180,7 @@ public class BukkitChunkManager extends ChunkManager {
}
final World worldObj = Bukkit.getWorld(world);
TaskManager.runTask(new Runnable() {
@Override
public void run() {
@Override public void run() {
long start = System.currentTimeMillis();
while (!chunks.isEmpty() && System.currentTimeMillis() - start < 5) {
final ChunkLoc chunk = chunks.remove(0);
@ -235,11 +195,11 @@ public class BukkitChunkManager extends ChunkManager {
continue;
}
final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(world, false);
RegionWrapper currentPlotClear = new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ());
RegionWrapper currentPlotClear =
new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ());
if (xxb >= p1x && xxt <= p2x && zzb >= p1z && zzt <= p2z) {
AugmentedUtils.bypass(ignoreAugment, new Runnable() {
@Override
public void run() {
@Override public void run() {
queue.regenChunkSafe(chunk.x, chunk.z);
}
});
@ -306,11 +266,9 @@ public class BukkitChunkManager extends ChunkManager {
}
map.saveEntitiesOut(chunkObj, currentPlotClear);
AugmentedUtils.bypass(ignoreAugment, new Runnable() {
@Override
public void run() {
@Override public void run() {
setChunkInPlotArea(null, new RunnableVal<ScopedLocalBlockQueue>() {
@Override
public void run(ScopedLocalBlockQueue value) {
@Override public void run(ScopedLocalBlockQueue value) {
Location min = value.getMin();
int bx = min.getX();
int bz = min.getZ();
@ -319,7 +277,8 @@ public class BukkitChunkManager extends ChunkManager {
PlotLoc loc = new PlotLoc(bx + x, bz + z);
PlotBlock[] ids = map.allBlocks.get(loc);
if (ids != null) {
for (int y = 0; y < Math.min(128, ids.length); y++) {
for (int y = 0;
y < Math.min(128, ids.length); y++) {
PlotBlock id = ids[y];
if (id != null) {
value.setBlock(x, y, z, id);
@ -327,7 +286,8 @@ public class BukkitChunkManager extends ChunkManager {
value.setBlock(x, y, z, 0, (byte) 0);
}
}
for (int y = Math.min(128, ids.length); y < ids.length; y++) {
for (int y = Math.min(128, ids.length);
y < ids.length; y++) {
PlotBlock id = ids[y];
if (id != null) {
value.setBlock(x, y, z, id);
@ -353,8 +313,7 @@ public class BukkitChunkManager extends ChunkManager {
return true;
}
@Override
public void clearAllEntities(Location pos1, Location pos2) {
@Override public void clearAllEntities(Location pos1, Location pos2) {
String world = pos1.getWorld();
List<Entity> entities = BukkitUtil.getEntities(world);
int bx = pos1.getX();
@ -364,26 +323,24 @@ public class BukkitChunkManager extends ChunkManager {
for (Entity entity : entities) {
if (!(entity instanceof Player)) {
org.bukkit.Location location = entity.getLocation();
if (location.getX() >= bx && location.getX() <= tx && location.getZ() >= bz && location.getZ() <= tz) {
if (location.getX() >= bx && location.getX() <= tx && location.getZ() >= bz
&& location.getZ() <= tz) {
entity.remove();
}
}
}
}
@Override
public boolean loadChunk(String world, ChunkLoc loc, boolean force) {
@Override public boolean loadChunk(String world, ChunkLoc loc, boolean force) {
return BukkitUtil.getWorld(world).getChunkAt(loc.x, loc.z).load(force);
}
@SuppressWarnings("deprecation")
@Override
public void unloadChunk(final String world, final ChunkLoc loc, final boolean save, final boolean safe) {
@SuppressWarnings("deprecation") @Override
public void unloadChunk(final String world, final ChunkLoc loc, final boolean save,
final boolean safe) {
if (!PS.get().isMainThread(Thread.currentThread())) {
TaskManager.runTask(new Runnable() {
@SuppressWarnings("deprecation")
@Override
public void run() {
@SuppressWarnings("deprecation") @Override public void run() {
BukkitUtil.getWorld(world).unloadChunk(loc.x, loc.z, save, safe);
}
});
@ -392,10 +349,12 @@ public class BukkitChunkManager extends ChunkManager {
}
}
@Override
public void swap(Location bot1, Location top1, Location bot2, Location top2, final Runnable whenDone) {
RegionWrapper region1 = new RegionWrapper(bot1.getX(), top1.getX(), bot1.getZ(), top1.getZ());
RegionWrapper region2 = new RegionWrapper(bot2.getX(), top2.getX(), bot2.getZ(), top2.getZ());
@Override public void swap(Location bot1, Location top1, Location bot2, Location top2,
final Runnable whenDone) {
RegionWrapper region1 =
new RegionWrapper(bot1.getX(), top1.getX(), bot1.getZ(), top1.getZ());
RegionWrapper region2 =
new RegionWrapper(bot2.getX(), top2.getX(), bot2.getZ(), top2.getZ());
final World world1 = Bukkit.getWorld(bot1.getWorld());
World world2 = Bukkit.getWorld(bot2.getWorld());
@ -412,8 +371,7 @@ public class BukkitChunkManager extends ChunkManager {
}
}
GlobalBlockQueue.IMP.addTask(new Runnable() {
@Override
public void run() {
@Override public void run() {
for (ContentMap map : maps) {
map.restoreBlocks(world1, 0, 0);
map.restoreEntities(world1, 0, 0);
@ -423,10 +381,10 @@ public class BukkitChunkManager extends ChunkManager {
});
}
@Override
public int[] countEntities(Plot plot) {
@Override public int[] countEntities(Plot plot) {
int[] existing = (int[]) plot.getMeta("EntityCount");
if (existing != null && (System.currentTimeMillis() - (long) plot.getMeta("EntityCountTime") < 1000)) {
if (existing != null && (System.currentTimeMillis() - (long) plot.getMeta("EntityCountTime")
< 1000)) {
return existing;
}
PlotArea area = plot.getArea();
@ -705,7 +663,8 @@ public class BukkitChunkManager extends ChunkManager {
}
}
public void saveEntitiesIn(Chunk chunk, RegionWrapper region, int offsetX, int offsetZ, boolean delete) {
public void saveEntitiesIn(Chunk chunk, RegionWrapper region, int offsetX, int offsetZ,
boolean delete) {
for (Entity entity : chunk.getEntities()) {
Location loc = BukkitUtil.getLocation(entity);
int x = loc.getX();
@ -743,26 +702,30 @@ public class BukkitChunkManager extends ChunkManager {
public void restoreBlocks(World world, int xOffset, int zOffset) {
for (Entry<BlockLoc, ItemStack[]> blockLocEntry : this.chestContents.entrySet()) {
try {
Block block =
world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset);
Block block = world
.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y,
blockLocEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof InventoryHolder) {
InventoryHolder chest = (InventoryHolder) state;
chest.getInventory().setContents(blockLocEntry.getValue());
state.update(true);
} else {
PS.debug("&c[WARN] Plot clear failed to regenerate chest: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate chest: " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y
+ ',' + (blockLocEntry.getKey().z + zOffset));
}
} catch (IllegalArgumentException ignored) {
PS.debug("&c[WARN] Plot clear failed to regenerate chest (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate chest (e): " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ','
+ (blockLocEntry.getKey().z + zOffset));
}
}
for (Entry<BlockLoc, String[]> blockLocEntry : this.signContents.entrySet()) {
try {
Block block =
world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset);
Block block = world
.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y,
blockLocEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof Sign) {
Sign sign = (Sign) state;
@ -773,95 +736,105 @@ public class BukkitChunkManager extends ChunkManager {
}
state.update(true);
} else {
PS.debug(
"&c[WARN] Plot clear failed to regenerate sign: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y
+ ',' + (
blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate sign: " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y
+ ',' + (blockLocEntry.getKey().z + zOffset));
}
} catch (IndexOutOfBoundsException ignored) {
PS.debug("&c[WARN] Plot clear failed to regenerate sign: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y
+ ',' + (
blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate sign: " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ','
+ (blockLocEntry.getKey().z + zOffset));
}
}
for (Entry<BlockLoc, ItemStack[]> blockLocEntry : this.dispenserContents.entrySet()) {
try {
Block block =
world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset);
Block block = world
.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y,
blockLocEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof Dispenser) {
((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue());
((InventoryHolder) state).getInventory()
.setContents(blockLocEntry.getValue());
state.update(true);
} else {
PS.debug("&c[WARN] Plot clear failed to regenerate dispenser: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate dispenser: " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y
+ ',' + (blockLocEntry.getKey().z + zOffset));
}
} catch (IllegalArgumentException ignored) {
PS.debug("&c[WARN] Plot clear failed to regenerate dispenser (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate dispenser (e): " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ','
+ (blockLocEntry.getKey().z + zOffset));
}
}
for (Entry<BlockLoc, ItemStack[]> blockLocEntry : this.dropperContents.entrySet()) {
try {
Block block =
world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset);
Block block = world
.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y,
blockLocEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof Dropper) {
((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue());
((InventoryHolder) state).getInventory()
.setContents(blockLocEntry.getValue());
state.update(true);
} else {
PS.debug("&c[WARN] Plot clear failed to regenerate dispenser: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate dispenser: " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y
+ ',' + (blockLocEntry.getKey().z + zOffset));
}
} catch (IllegalArgumentException ignored) {
PS.debug("&c[WARN] Plot clear failed to regenerate dispenser (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate dispenser (e): " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ','
+ (blockLocEntry.getKey().z + zOffset));
}
}
for (Entry<BlockLoc, ItemStack[]> blockLocEntry : this.beaconContents.entrySet()) {
try {
Block block =
world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset);
Block block = world
.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y,
blockLocEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof Beacon) {
((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue());
((InventoryHolder) state).getInventory()
.setContents(blockLocEntry.getValue());
state.update(true);
} else {
PS.debug("&c[WARN] Plot clear failed to regenerate beacon: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate beacon: " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y
+ ',' + (blockLocEntry.getKey().z + zOffset));
}
} catch (IllegalArgumentException ignored) {
PS.debug("&c[WARN] Plot clear failed to regenerate beacon (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate beacon (e): " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ','
+ (blockLocEntry.getKey().z + zOffset));
}
}
for (Entry<BlockLoc, Material> blockLocMaterialEntry : this.jukeboxDisc.entrySet()) {
try {
Block block =
world.getBlockAt(blockLocMaterialEntry.getKey().x + xOffset, blockLocMaterialEntry.getKey().y, blockLocMaterialEntry
.getKey().z + zOffset);
Block block = world.getBlockAt(blockLocMaterialEntry.getKey().x + xOffset,
blockLocMaterialEntry.getKey().y,
blockLocMaterialEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof Jukebox) {
((Jukebox) state).setPlaying(blockLocMaterialEntry.getValue());
state.update(true);
} else {
PS.debug("&c[WARN] Plot clear failed to restore jukebox: " + (blockLocMaterialEntry.getKey().x + xOffset) + ','
+ blockLocMaterialEntry
.getKey().y + ',' + (
PS.debug("&c[WARN] Plot clear failed to restore jukebox: " + (
blockLocMaterialEntry.getKey().x + xOffset) + ','
+ blockLocMaterialEntry.getKey().y + ',' + (
blockLocMaterialEntry.getKey().z + zOffset));
}
} catch (Exception ignored) {
PS.debug("&c[WARN] Plot clear failed to regenerate jukebox (e): " + (blockLocMaterialEntry.getKey().x + xOffset) + ','
+ blockLocMaterialEntry
.getKey().y + ',' + (
blockLocMaterialEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate jukebox (e): " + (
blockLocMaterialEntry.getKey().x + xOffset) + ',' + blockLocMaterialEntry
.getKey().y + ',' + (blockLocMaterialEntry.getKey().z + zOffset));
}
}
for (Entry<BlockLoc, Object[]> blockLocEntry : this.skullData.entrySet()) {
try {
Block block =
world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset);
Block block = world
.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y,
blockLocEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof Skull) {
Object[] data = blockLocEntry.getValue();
@ -872,193 +845,210 @@ public class BukkitChunkManager extends ChunkManager {
((Skull) state).setSkullType((SkullType) data[3]);
state.update(true);
} else {
PS.debug("&c[WARN] Plot clear failed to restore skull: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to restore skull: " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y
+ ',' + (blockLocEntry.getKey().z + zOffset));
}
} catch (Exception e) {
PS.debug("&c[WARN] Plot clear failed to regenerate skull (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate skull (e): " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ','
+ (blockLocEntry.getKey().z + zOffset));
e.printStackTrace();
}
}
for (Entry<BlockLoc, ItemStack[]> blockLocEntry : this.hopperContents.entrySet()) {
try {
Block block =
world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset);
Block block = world
.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y,
blockLocEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof Hopper) {
((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue());
((InventoryHolder) state).getInventory()
.setContents(blockLocEntry.getValue());
state.update(true);
} else {
PS.debug("&c[WARN] Plot clear failed to regenerate hopper: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate hopper: " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y
+ ',' + (blockLocEntry.getKey().z + zOffset));
}
} catch (IllegalArgumentException ignored) {
PS.debug("&c[WARN] Plot clear failed to regenerate hopper (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate hopper (e): " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ','
+ (blockLocEntry.getKey().z + zOffset));
}
}
for (Entry<BlockLoc, Note> blockLocNoteEntry : this.noteBlockContents.entrySet()) {
try {
Block block = world.getBlockAt(
blockLocNoteEntry.getKey().x + xOffset, blockLocNoteEntry.getKey().y, blockLocNoteEntry.getKey().z + zOffset);
Block block = world.getBlockAt(blockLocNoteEntry.getKey().x + xOffset,
blockLocNoteEntry.getKey().y, blockLocNoteEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof NoteBlock) {
((NoteBlock) state).setNote(blockLocNoteEntry.getValue());
state.update(true);
} else {
PS.debug("&c[WARN] Plot clear failed to regenerate note block: " + (blockLocNoteEntry.getKey().x + xOffset) + ','
+ blockLocNoteEntry
.getKey().y + ',' + (
blockLocNoteEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate note block: " + (
blockLocNoteEntry.getKey().x + xOffset) + ',' + blockLocNoteEntry
.getKey().y + ',' + (blockLocNoteEntry.getKey().z + zOffset));
}
} catch (Exception ignored) {
PS.debug("&c[WARN] Plot clear failed to regenerate note block (e): " + (blockLocNoteEntry.getKey().x + xOffset) + ','
+ blockLocNoteEntry
.getKey().y + ',' + (
blockLocNoteEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate note block (e): " + (
blockLocNoteEntry.getKey().x + xOffset) + ',' + blockLocNoteEntry.getKey().y
+ ',' + (blockLocNoteEntry.getKey().z + zOffset));
}
}
for (Entry<BlockLoc, Short> blockLocShortEntry : this.brewTime.entrySet()) {
try {
Block block = world.getBlockAt(
blockLocShortEntry.getKey().x + xOffset, blockLocShortEntry.getKey().y, blockLocShortEntry.getKey().z + zOffset);
Block block = world.getBlockAt(blockLocShortEntry.getKey().x + xOffset,
blockLocShortEntry.getKey().y, blockLocShortEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof BrewingStand) {
((BrewingStand) state).setBrewingTime(blockLocShortEntry.getValue());
} else {
PS.debug("&c[WARN] Plot clear failed to restore brewing stand cooking: " + (blockLocShortEntry.getKey().x + xOffset) + ','
+ blockLocShortEntry
.getKey().y + ',' + (
blockLocShortEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to restore brewing stand cooking: " + (
blockLocShortEntry.getKey().x + xOffset) + ',' + blockLocShortEntry
.getKey().y + ',' + (blockLocShortEntry.getKey().z + zOffset));
}
} catch (Exception ignored) {
PS.debug("&c[WARN] Plot clear failed to restore brewing stand cooking (e): " + (blockLocShortEntry.getKey().x + xOffset) + ','
+ blockLocShortEntry.getKey().y + ',' + (blockLocShortEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to restore brewing stand cooking (e): " + (
blockLocShortEntry.getKey().x + xOffset) + ',' + blockLocShortEntry
.getKey().y + ',' + (blockLocShortEntry.getKey().z + zOffset));
}
}
for (Entry<BlockLoc, EntityType> blockLocEntityTypeEntry : this.spawnerData.entrySet()) {
for (Entry<BlockLoc, EntityType> blockLocEntityTypeEntry : this.spawnerData
.entrySet()) {
try {
Block block =
world.getBlockAt(blockLocEntityTypeEntry.getKey().x + xOffset, blockLocEntityTypeEntry.getKey().y, blockLocEntityTypeEntry
.getKey().z + zOffset);
Block block = world.getBlockAt(blockLocEntityTypeEntry.getKey().x + xOffset,
blockLocEntityTypeEntry.getKey().y,
blockLocEntityTypeEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof CreatureSpawner) {
((CreatureSpawner) state).setSpawnedType(blockLocEntityTypeEntry.getValue());
((CreatureSpawner) state)
.setSpawnedType(blockLocEntityTypeEntry.getValue());
state.update(true);
} else {
PS.debug("&c[WARN] Plot clear failed to restore spawner type: " + (blockLocEntityTypeEntry.getKey().x + xOffset) + ','
+ blockLocEntityTypeEntry
.getKey().y + ',' + (
PS.debug("&c[WARN] Plot clear failed to restore spawner type: " + (
blockLocEntityTypeEntry.getKey().x + xOffset) + ','
+ blockLocEntityTypeEntry.getKey().y + ',' + (
blockLocEntityTypeEntry.getKey().z + zOffset));
}
} catch (Exception ignored) {
PS.debug("&c[WARN] Plot clear failed to restore spawner type (e): " + (blockLocEntityTypeEntry.getKey().x + xOffset) + ','
+ blockLocEntityTypeEntry.getKey().y + ',' + (blockLocEntityTypeEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to restore spawner type (e): " + (
blockLocEntityTypeEntry.getKey().x + xOffset) + ','
+ blockLocEntityTypeEntry.getKey().y + ',' + (
blockLocEntityTypeEntry.getKey().z + zOffset));
}
}
for (Entry<BlockLoc, String> blockLocStringEntry : this.cmdData.entrySet()) {
try {
Block block = world.getBlockAt(
blockLocStringEntry.getKey().x + xOffset, blockLocStringEntry.getKey().y, blockLocStringEntry.getKey().z + zOffset);
Block block = world.getBlockAt(blockLocStringEntry.getKey().x + xOffset,
blockLocStringEntry.getKey().y, blockLocStringEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof CommandBlock) {
((CommandBlock) state).setCommand(blockLocStringEntry.getValue());
state.update(true);
} else {
PS.debug("&c[WARN] Plot clear failed to restore command block: " + (blockLocStringEntry.getKey().x + xOffset) + ','
+ blockLocStringEntry
.getKey().y + ',' + (
blockLocStringEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to restore command block: " + (
blockLocStringEntry.getKey().x + xOffset) + ',' + blockLocStringEntry
.getKey().y + ',' + (blockLocStringEntry.getKey().z + zOffset));
}
} catch (Exception ignored) {
PS.debug("&c[WARN] Plot clear failed to restore command block (e): " + (blockLocStringEntry.getKey().x + xOffset) + ','
+ blockLocStringEntry
.getKey().y + ',' + (
blockLocStringEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to restore command block (e): " + (
blockLocStringEntry.getKey().x + xOffset) + ',' + blockLocStringEntry
.getKey().y + ',' + (blockLocStringEntry.getKey().z + zOffset));
}
}
for (Entry<BlockLoc, ItemStack[]> blockLocEntry : this.brewingStandContents.entrySet()) {
for (Entry<BlockLoc, ItemStack[]> blockLocEntry : this.brewingStandContents
.entrySet()) {
try {
Block block =
world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset);
Block block = world
.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y,
blockLocEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof BrewingStand) {
((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue());
((InventoryHolder) state).getInventory()
.setContents(blockLocEntry.getValue());
state.update(true);
} else {
PS.debug("&c[WARN] Plot clear failed to regenerate brewing stand: " + (blockLocEntry.getKey().x + xOffset) + ','
+ blockLocEntry
.getKey().y + ',' + (
blockLocEntry.getKey().z
+ zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate brewing stand: " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y
+ ',' + (blockLocEntry.getKey().z + zOffset));
}
} catch (IllegalArgumentException ignored) {
PS.debug("&c[WARN] Plot clear failed to regenerate brewing stand (e): " + (blockLocEntry.getKey().x + xOffset) + ','
+ blockLocEntry.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate brewing stand (e): " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ','
+ (blockLocEntry.getKey().z + zOffset));
}
}
for (Entry<BlockLoc, Short[]> blockLocEntry : this.furnaceTime.entrySet()) {
try {
Block block =
world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset);
Block block = world
.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y,
blockLocEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof Furnace) {
Short[] time = blockLocEntry.getValue();
((Furnace) state).setBurnTime(time[0]);
((Furnace) state).setCookTime(time[1]);
} else {
PS.debug(
"&c[WARN] Plot clear failed to restore furnace cooking: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to restore furnace cooking: " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y
+ ',' + (blockLocEntry.getKey().z + zOffset));
}
} catch (Exception ignored) {
PS.debug(
"&c[WARN] Plot clear failed to restore furnace cooking (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to restore furnace cooking (e): " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ','
+ (blockLocEntry.getKey().z + zOffset));
}
}
for (Entry<BlockLoc, ItemStack[]> blockLocEntry : this.furnaceContents.entrySet()) {
try {
Block block =
world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset);
Block block = world
.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y,
blockLocEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof Furnace) {
((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue());
((InventoryHolder) state).getInventory()
.setContents(blockLocEntry.getValue());
state.update(true);
} else {
PS.debug("&c[WARN] Plot clear failed to regenerate furnace: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate furnace: " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y
+ ',' + (blockLocEntry.getKey().z + zOffset));
}
} catch (IllegalArgumentException ignored) {
PS.debug("&c[WARN] Plot clear failed to regenerate furnace (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry
.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate furnace (e): " + (
blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ','
+ (blockLocEntry.getKey().z + zOffset));
}
}
for (Entry<BlockLoc, DyeColor> blockLocByteEntry : this.bannerBase.entrySet()) {
try {
Block block = world.getBlockAt(
blockLocByteEntry.getKey().x + xOffset, blockLocByteEntry.getKey().y, blockLocByteEntry.getKey().z + zOffset);
Block block = world.getBlockAt(blockLocByteEntry.getKey().x + xOffset,
blockLocByteEntry.getKey().y, blockLocByteEntry.getKey().z + zOffset);
BlockState state = block.getState();
if (state instanceof Banner) {
Banner banner = (Banner) state;
DyeColor base = blockLocByteEntry.getValue();
List<Pattern> patterns = this.bannerPatterns.get(blockLocByteEntry.getKey());
List<Pattern> patterns =
this.bannerPatterns.get(blockLocByteEntry.getKey());
banner.setBaseColor(base);
banner.setPatterns(patterns);
state.update(true);
} else {
PS.debug("&c[WARN] Plot clear failed to regenerate banner: " + (blockLocByteEntry.getKey().x + xOffset) + ','
+ blockLocByteEntry.getKey().y + ',' + (blockLocByteEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate banner: " + (
blockLocByteEntry.getKey().x + xOffset) + ',' + blockLocByteEntry
.getKey().y + ',' + (blockLocByteEntry.getKey().z + zOffset));
}
} catch (Exception ignored) {
PS.debug("&c[WARN] Plot clear failed to regenerate banner (e): " + (blockLocByteEntry.getKey().x + xOffset) + ','
+ blockLocByteEntry.getKey().y + ',' + (blockLocByteEntry.getKey().z + zOffset));
PS.debug("&c[WARN] Plot clear failed to regenerate banner (e): " + (
blockLocByteEntry.getKey().x + xOffset) + ',' + blockLocByteEntry.getKey().y
+ ',' + (blockLocByteEntry.getKey().z + zOffset));
}
}
}
public void saveBlocks(World world, int maxY, int x, int z, int offsetX, int offsetZ, boolean storeNormal) {
public void saveBlocks(World world, int maxY, int x, int z, int offsetX, int offsetZ,
boolean storeNormal) {
maxY = Math.min(255, maxY);
PlotBlock[] ids;
if (storeNormal) {
@ -1082,7 +1072,8 @@ public class BukkitChunkManager extends ChunkManager {
BlockLoc bl = new BlockLoc(x + offsetX, y, z + offsetZ);
if (block.getState() instanceof InventoryHolder) {
InventoryHolder inventoryHolder = (InventoryHolder) block.getState();
ItemStack[] inventory = inventoryHolder.getInventory().getContents().clone();
ItemStack[] inventory =
inventoryHolder.getInventory().getContents().clone();
switch (id) {
case CHEST:
this.chestContents.put(bl, inventory);
@ -1105,7 +1096,8 @@ public class BukkitChunkManager extends ChunkManager {
if (time > 0) {
this.brewTime.put(bl, time);
}
ItemStack[] invBre = brewingStand.getInventory().getContents().clone();
ItemStack[] invBre =
brewingStand.getInventory().getContents().clone();
this.brewingStandContents.put(bl, invBre);
break;
case FURNACE:
@ -1113,10 +1105,11 @@ public class BukkitChunkManager extends ChunkManager {
Furnace furnace = (Furnace) inventoryHolder;
short burn = furnace.getBurnTime();
short cook = furnace.getCookTime();
ItemStack[] invFur = furnace.getInventory().getContents().clone();
ItemStack[] invFur =
furnace.getInventory().getContents().clone();
this.furnaceContents.put(bl, invFur);
if (cook != 0) {
this.furnaceTime.put(bl, new Short[]{burn, cook});
this.furnaceTime.put(bl, new Short[] {burn, cook});
}
break;
}
@ -1144,7 +1137,8 @@ public class BukkitChunkManager extends ChunkManager {
}
} else if (block.getState() instanceof Skull) {
Skull skull = (Skull) block.getState();
this.skullData.put(bl, new Object[]{skull.hasOwner(), skull.getOwner(), skull.getRotation(), skull.getSkullType()});
this.skullData.put(bl, new Object[] {skull.hasOwner(), skull.getOwner(),
skull.getRotation(), skull.getSkullType()});
} else if (block.getState() instanceof Banner) {
Banner banner = (Banner) block.getState();
DyeColor base = banner.getBaseColor();

View File

@ -4,13 +4,7 @@ import com.intellectualcrafters.plot.commands.MainCommand;
import com.intellectualcrafters.plot.object.ConsolePlayer;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.plotsquared.bukkit.commands.DebugUUID;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.command.ProxiedCommandSender;
import org.bukkit.command.RemoteConsoleCommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.command.*;
import org.bukkit.entity.Player;
import java.util.ArrayList;
@ -25,11 +19,13 @@ public class BukkitCommand implements CommandExecutor, TabCompleter {
}
@Override
public boolean onCommand(CommandSender commandSender, Command command, String commandLabel, String[] args) {
public boolean onCommand(CommandSender commandSender, Command command, String commandLabel,
String[] args) {
if (commandSender instanceof Player) {
return MainCommand.onCommand(BukkitUtil.getPlayer((Player) commandSender), args);
}
if (commandSender instanceof ConsoleCommandSender || commandSender instanceof ProxiedCommandSender
if (commandSender instanceof ConsoleCommandSender
|| commandSender instanceof ProxiedCommandSender
|| commandSender instanceof RemoteConsoleCommandSender) {
return MainCommand.onCommand(ConsolePlayer.getConsole(), args);
}
@ -37,7 +33,8 @@ public class BukkitCommand implements CommandExecutor, TabCompleter {
}
@Override
public List<String> onTabComplete(CommandSender commandSender, Command command, String s, String[] args) {
public List<String> onTabComplete(CommandSender commandSender, Command command, String s,
String[] args) {
if (!(commandSender instanceof Player)) {
return null;
}

View File

@ -24,7 +24,8 @@ public class BukkitEconHandler extends EconHandler {
}
private boolean setupPermissions() {
RegisteredServiceProvider<Permission> permissionProvider = Bukkit.getServer().getServicesManager().getRegistration(Permission.class);
RegisteredServiceProvider<Permission> permissionProvider =
Bukkit.getServer().getServicesManager().getRegistration(Permission.class);
if (permissionProvider != null) {
this.perms = permissionProvider.getProvider();
}
@ -35,15 +36,15 @@ public class BukkitEconHandler extends EconHandler {
if (Bukkit.getServer().getPluginManager().getPlugin("Vault") == null) {
return false;
}
RegisteredServiceProvider<Economy> economyProvider = Bukkit.getServer().getServicesManager().getRegistration(Economy.class);
RegisteredServiceProvider<Economy> economyProvider =
Bukkit.getServer().getServicesManager().getRegistration(Economy.class);
if (economyProvider != null) {
this.econ = economyProvider.getProvider();
}
return this.econ != null;
}
@Override
public double getMoney(PlotPlayer player) {
@Override public double getMoney(PlotPlayer player) {
double bal = super.getMoney(player);
if (Double.isNaN(bal)) {
return this.econ.getBalance(((BukkitPlayer) player).player);
@ -51,28 +52,23 @@ public class BukkitEconHandler extends EconHandler {
return bal;
}
@Override
public void withdrawMoney(PlotPlayer player, double amount) {
@Override public void withdrawMoney(PlotPlayer player, double amount) {
this.econ.withdrawPlayer(((BukkitPlayer) player).player, amount);
}
@Override
public void depositMoney(PlotPlayer player, double amount) {
@Override public void depositMoney(PlotPlayer player, double amount) {
this.econ.depositPlayer(((BukkitPlayer) player).player, amount);
}
@Override
public void depositMoney(OfflinePlotPlayer player, double amount) {
@Override public void depositMoney(OfflinePlotPlayer player, double amount) {
this.econ.depositPlayer(((BukkitOfflinePlayer) player).player, amount);
}
@Override
public boolean hasPermission(String world, String player, String perm) {
@Override public boolean hasPermission(String world, String player, String perm) {
return this.perms.playerHas(world, Bukkit.getOfflinePlayer(player), perm);
}
@Override
public double getBalance(PlotPlayer player) {
@Override public double getBalance(PlotPlayer player) {
return this.econ.getBalance(player.getName());
}

View File

@ -1,30 +1,9 @@
package com.plotsquared.bukkit.util;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.object.Location;
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.PlotPlayer;
import com.intellectualcrafters.plot.object.Rating;
import com.intellectualcrafters.plot.object.*;
import com.intellectualcrafters.plot.util.EventUtil;
import com.plotsquared.bukkit.events.ClusterFlagRemoveEvent;
import com.plotsquared.bukkit.events.PlayerClaimPlotEvent;
import com.plotsquared.bukkit.events.PlayerEnterPlotEvent;
import com.plotsquared.bukkit.events.PlayerLeavePlotEvent;
import com.plotsquared.bukkit.events.PlayerPlotDeniedEvent;
import com.plotsquared.bukkit.events.PlayerPlotHelperEvent;
import com.plotsquared.bukkit.events.PlayerPlotTrustedEvent;
import com.plotsquared.bukkit.events.PlayerTeleportToPlotEvent;
import com.plotsquared.bukkit.events.PlotClearEvent;
import com.plotsquared.bukkit.events.PlotComponentSetEvent;
import com.plotsquared.bukkit.events.PlotDeleteEvent;
import com.plotsquared.bukkit.events.PlotFlagAddEvent;
import com.plotsquared.bukkit.events.PlotFlagRemoveEvent;
import com.plotsquared.bukkit.events.PlotMergeEvent;
import com.plotsquared.bukkit.events.PlotRateEvent;
import com.plotsquared.bukkit.events.PlotUnlinkEvent;
import com.plotsquared.bukkit.events.*;
import com.plotsquared.bukkit.object.BukkitPlayer;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
@ -48,83 +27,67 @@ public class BukkitEventUtil extends EventUtil {
return !(event instanceof Cancellable) || !((Cancellable) event).isCancelled();
}
@Override
public boolean callClaim(PlotPlayer player, Plot plot, boolean auto) {
@Override public boolean callClaim(PlotPlayer player, Plot plot, boolean auto) {
return callEvent(new PlayerClaimPlotEvent(getPlayer(player), plot, auto));
}
@Override
public boolean callTeleport(PlotPlayer player, Location from, Plot plot) {
@Override public boolean callTeleport(PlotPlayer player, Location from, Plot plot) {
return callEvent(new PlayerTeleportToPlotEvent(getPlayer(player), from, plot));
}
@Override
public boolean callComponentSet(Plot plot, String component) {
@Override public boolean callComponentSet(Plot plot, String component) {
return callEvent(new PlotComponentSetEvent(plot, component));
}
@Override
public boolean callClear(Plot plot) {
@Override public boolean callClear(Plot plot) {
return callEvent(new PlotClearEvent(plot));
}
@Override
public void callDelete(Plot plot) {
@Override public void callDelete(Plot plot) {
callEvent(new PlotDeleteEvent(plot));
}
@Override
public boolean callFlagAdd(Flag flag, Plot plot) {
@Override public boolean callFlagAdd(Flag flag, Plot plot) {
return callEvent(new PlotFlagAddEvent(flag, plot));
}
@Override
public boolean callFlagRemove(Flag<?> flag, Plot plot, Object value) {
@Override public boolean callFlagRemove(Flag<?> flag, Plot plot, Object value) {
return callEvent(new PlotFlagRemoveEvent(flag, plot));
}
@Override
public boolean callMerge(Plot plot, ArrayList<PlotId> plots) {
@Override public boolean callMerge(Plot plot, ArrayList<PlotId> plots) {
return callEvent(new PlotMergeEvent(BukkitUtil.getWorld(plot.getWorldName()), plot, plots));
}
@Override
public boolean callUnlink(PlotArea area, ArrayList<PlotId> plots) {
@Override public boolean callUnlink(PlotArea area, ArrayList<PlotId> plots) {
return callEvent(new PlotUnlinkEvent(BukkitUtil.getWorld(area.worldname), area, plots));
}
@Override
public void callEntry(PlotPlayer player, Plot plot) {
@Override public void callEntry(PlotPlayer player, Plot plot) {
callEvent(new PlayerEnterPlotEvent(getPlayer(player), plot));
}
@Override
public void callLeave(PlotPlayer player, Plot plot) {
@Override public void callLeave(PlotPlayer player, Plot plot) {
callEvent(new PlayerLeavePlotEvent(getPlayer(player), plot));
}
@Override
public void callDenied(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
@Override public void callDenied(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
callEvent(new PlayerPlotDeniedEvent(getPlayer(initiator), plot, player, added));
}
@Override
public void callTrusted(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
@Override public void callTrusted(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
callEvent(new PlayerPlotTrustedEvent(getPlayer(initiator), plot, player, added));
}
@Override
public void callMember(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
@Override public void callMember(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
callEvent(new PlayerPlotHelperEvent(getPlayer(initiator), plot, player, added));
}
@Override
public boolean callFlagRemove(Flag flag, Object object, PlotCluster cluster) {
@Override public boolean callFlagRemove(Flag flag, Object object, PlotCluster cluster) {
return callEvent(new ClusterFlagRemoveEvent(flag, cluster));
}
@Override
public Rating callRating(PlotPlayer player, Plot plot, Rating rating) {
@Override public Rating callRating(PlotPlayer player, Plot plot, Rating rating) {
PlotRateEvent event = new PlotRateEvent(player, rating, plot);
Bukkit.getServer().getPluginManager().callEvent(event);
return event.getRating();

View File

@ -26,8 +26,8 @@ import java.util.Random;
public class BukkitHybridUtils extends HybridUtils {
@Override
public void analyzeRegion(final String world, final RegionWrapper region, final RunnableVal<PlotAnalysis> whenDone) {
@Override public void analyzeRegion(final String world, final RegionWrapper region,
final RunnableVal<PlotAnalysis> whenDone) {
// int diff, int variety, int vertices, int rotation, int height_sd
/*
* diff: compare to base by looping through all blocks
@ -41,8 +41,7 @@ public class BukkitHybridUtils extends HybridUtils {
*
*/
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
@Override public void run() {
final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(world, false);
final World worldObj = Bukkit.getWorld(world);
final ChunkGenerator gen = worldObj.getGenerator();
@ -50,12 +49,10 @@ public class BukkitHybridUtils extends HybridUtils {
return;
}
final BiomeGrid nullBiomeGrid = new BiomeGrid() {
@Override
public void setBiome(int a, int b, Biome c) {
@Override public void setBiome(int a, int b, Biome c) {
}
@Override
public Biome getBiome(int a, int b) {
@Override public Biome getBiome(int a, int b) {
return null;
}
};
@ -82,15 +79,14 @@ public class BukkitHybridUtils extends HybridUtils {
final short[][][] newBlocks = new short[256][width][length];
final Runnable run = new Runnable() {
@Override
public void run() {
@Override public void run() {
ChunkManager.chunkTask(bot, top, new RunnableVal<int[]>() {
@Override
public void run(int[] value) {
@Override public void run(int[] value) {
// [chunkx, chunkz, pos1x, pos1z, pos2x, pos2z, isedge]
int X = value[0];
int Z = value[1];
short[][] result = gen.generateExtBlockSections(worldObj, r, X, Z, nullBiomeGrid);
short[][] result =
gen.generateExtBlockSections(worldObj, r, X, Z, nullBiomeGrid);
int xb = (X << 4) - bx;
int zb = (Z << 4) - bz;
for (int i = 0; i < result.length; i++) {
@ -125,11 +121,9 @@ public class BukkitHybridUtils extends HybridUtils {
}
}, new Runnable() {
@Override
public void run() {
@Override public void run() {
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
@Override public void run() {
int size = width * length;
int[] changes = new int[size];
int[] faces = new int[size];
@ -151,7 +145,8 @@ public class BukkitHybridUtils extends HybridUtils {
} else {
// check vertices
// modifications_adjacent
if (x > 0 && z > 0 && y > 0 && x < width - 1 && z < length - 1 && y < 255) {
if (x > 0 && z > 0 && y > 0 && x < width - 1
&& z < length - 1 && y < 255) {
if (newBlocks[y - 1][x][z] == 0) {
faces[i]++;
}
@ -172,12 +167,15 @@ public class BukkitHybridUtils extends HybridUtils {
}
}
Material material = Material.getMaterial(now);
Material material =
Material.getMaterial(now);
if (material != null) {
Class<? extends MaterialData> md = material.getData();
Class<? extends MaterialData> md =
material.getData();
if (md.equals(Directional.class)) {
data[i] += 8;
} else if (!md.equals(MaterialData.class)) {
} else if (!md
.equals(MaterialData.class)) {
data[i]++;
}
}
@ -199,11 +197,14 @@ public class BukkitHybridUtils extends HybridUtils {
analysis.air = (int) (MathMan.getMean(air) * 100);
analysis.variety = (int) (MathMan.getMean(variety) * 100);
analysis.changes_sd = (int) MathMan.getSD(changes, analysis.changes);
analysis.faces_sd = (int) MathMan.getSD(faces, analysis.faces);
analysis.changes_sd =
(int) MathMan.getSD(changes, analysis.changes);
analysis.faces_sd =
(int) MathMan.getSD(faces, analysis.faces);
analysis.data_sd = (int) MathMan.getSD(data, analysis.data);
analysis.air_sd = (int) MathMan.getSD(air, analysis.air);
analysis.variety_sd = (int) MathMan.getSD(variety, analysis.variety);
analysis.variety_sd =
(int) MathMan.getSD(variety, analysis.variety);
System.gc();
System.gc();
whenDone.value = analysis;
@ -219,8 +220,7 @@ public class BukkitHybridUtils extends HybridUtils {
MainUtil.initCache();
ChunkManager.chunkTask(bot, top, new RunnableVal<int[]>() {
@Override
public void run(int[] value) {
@Override public void run(int[] value) {
int X = value[0];
int Z = value[1];
worldObj.loadChunk(X, Z);
@ -269,8 +269,7 @@ public class BukkitHybridUtils extends HybridUtils {
worldObj.unloadChunkRequest(X, Z, true);
}
}, new Runnable() {
@Override
public void run() {
@Override public void run() {
TaskManager.runTaskAsync(run);
}
}, 5);

View File

@ -45,8 +45,7 @@ public class BukkitInventoryUtil extends InventoryUtil {
return stack;
}
@Override
public void open(PlotInventory inv) {
@Override public void open(PlotInventory inv) {
BukkitPlayer bp = (BukkitPlayer) inv.player;
Inventory inventory = Bukkit.createInventory(null, inv.size * 9, inv.getTitle());
PlotItemStack[] items = inv.getItems();
@ -60,8 +59,7 @@ public class BukkitInventoryUtil extends InventoryUtil {
bp.player.openInventory(inventory);
}
@Override
public void close(PlotInventory inv) {
@Override public void close(PlotInventory inv) {
if (!inv.isOpen()) {
return;
}
@ -70,8 +68,7 @@ public class BukkitInventoryUtil extends InventoryUtil {
bp.player.closeInventory();
}
@Override
public void setItem(PlotInventory inv, int index, PlotItemStack item) {
@Override public void setItem(PlotInventory inv, int index, PlotItemStack item) {
BukkitPlayer bp = (BukkitPlayer) inv.player;
InventoryView opened = bp.player.getOpenInventory();
if (!inv.isOpen()) {
@ -103,8 +100,7 @@ public class BukkitInventoryUtil extends InventoryUtil {
return new PlotItemStack(id, data, amount, name, lore);
}
@Override
public PlotItemStack[] getItems(PlotPlayer player) {
@Override public PlotItemStack[] getItems(PlotPlayer player) {
BukkitPlayer bp = (BukkitPlayer) player;
PlayerInventory inv = bp.player.getInventory();
PlotItemStack[] items = new PlotItemStack[36];
@ -114,13 +110,13 @@ public class BukkitInventoryUtil extends InventoryUtil {
return items;
}
@Override
public boolean isOpen(PlotInventory inv) {
@Override public boolean isOpen(PlotInventory inv) {
if (!inv.isOpen()) {
return false;
}
BukkitPlayer bp = (BukkitPlayer) inv.player;
InventoryView opened = bp.player.getOpenInventory();
return inv.isOpen() && opened.getType() == InventoryType.CRAFTING && opened.getTitle() == null;
return inv.isOpen() && opened.getType() == InventoryType.CRAFTING
&& opened.getTitle() == null;
}
}

View File

@ -1,12 +1,6 @@
package com.plotsquared.bukkit.util;
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.jnbt.*;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.RegionWrapper;
@ -22,24 +16,18 @@ import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.*;
/**
* Schematic Handler.
*/
public class BukkitSchematicHandler extends SchematicHandler {
@Override
public void getCompoundTag(final String world, final Set<RegionWrapper> regions, final RunnableVal<CompoundTag> whenDone) {
@Override public void getCompoundTag(final String world, final Set<RegionWrapper> regions,
final RunnableVal<CompoundTag> whenDone) {
// async
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
@Override public void run() {
// Main positions
Location[] corners = MainUtil.getCorners(world, regions);
final Location bot = corners[0];
@ -67,16 +55,18 @@ public class BukkitSchematicHandler extends SchematicHandler {
// Queue
final ArrayDeque<RegionWrapper> queue = new ArrayDeque<>(regions);
TaskManager.runTask(new Runnable() {
@Override
public void run() {
@Override public void run() {
if (queue.isEmpty()) {
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
@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<Tag>()));
schematic.put("TileEntities", new ListTag("TileEntities", CompoundTag.class, tileEntities));
schematic.put("Entities",
new ListTag("Entities", CompoundTag.class,
new ArrayList<Tag>()));
schematic.put("TileEntities",
new ListTag("TileEntities", CompoundTag.class,
tileEntities));
whenDone.value = new CompoundTag("Schematic", schematic);
TaskManager.runTask(whenDone);
System.gc();
@ -111,10 +101,10 @@ public class BukkitSchematicHandler extends SchematicHandler {
final World worldObj = Bukkit.getWorld(world);
// Main thread
TaskManager.runTask(new Runnable() {
@Override
public void run() {
@Override public void run() {
long start = System.currentTimeMillis();
while (!chunks.isEmpty() && System.currentTimeMillis() - start < 20) {
while (!chunks.isEmpty()
&& System.currentTimeMillis() - start < 20) {
// save schematics
ChunkLoc chunk = chunks.remove(0);
Chunk bc = worldObj.getChunkAt(chunk.x, chunk.z);
@ -259,15 +249,20 @@ public class BukkitSchematicHandler extends SchematicHandler {
// TODO implement fully
BlockState state = block.getState();
if (state != null) {
StateWrapper wrapper = new StateWrapper(state);
StateWrapper wrapper =
new StateWrapper(state);
CompoundTag rawTag = wrapper.getTag();
if (rawTag != null) {
Map<String, Tag> values = new HashMap<>(rawTag.getValue());
values.put("id", new StringTag("id", wrapper.getId()));
Map<String, Tag> values =
new HashMap<>(
rawTag.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));
CompoundTag tileEntityTag = new CompoundTag(values);
CompoundTag tileEntityTag =
new CompoundTag(values);
tileEntities.add(tileEntityTag);
}
}

View File

@ -9,25 +9,21 @@ import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.SetupObject;
import com.intellectualcrafters.plot.util.SetupUtils;
import com.plotsquared.bukkit.generator.BukkitPlotGenerator;
import org.bukkit.*;
import org.bukkit.World.Environment;
import org.bukkit.entity.Player;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.plugin.Plugin;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Objects;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.WorldCreator;
import org.bukkit.WorldType;
import org.bukkit.entity.Player;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.plugin.Plugin;
public class BukkitSetupUtils extends SetupUtils {
@Override
public void updateGenerators() {
@Override public void updateGenerators() {
if (!SetupUtils.generators.isEmpty()) {
return;
}
@ -54,8 +50,7 @@ public class BukkitSetupUtils extends SetupUtils {
}
}
@Override
public void unload(String worldName, boolean save) {
@Override public void unload(String worldName, boolean save) {
World world = Bukkit.getWorld(worldName);
if (world == null) {
return;
@ -76,8 +71,7 @@ public class BukkitSetupUtils extends SetupUtils {
Bukkit.unloadWorld(world, false);
}
@Override
public String setupWorld(SetupObject object) {
@Override public String setupWorld(SetupObject object) {
SetupUtils.manager.updateGenerators();
ConfigurationNode[] steps = object.step == null ? new ConfigurationNode[0] : object.step;
String world = object.world;
@ -89,13 +83,15 @@ public class BukkitSetupUtils extends SetupUtils {
if (!PS.get().worlds.contains(worldPath)) {
PS.get().worlds.createSection(worldPath);
}
ConfigurationSection worldSection = PS.get().worlds.getConfigurationSection(worldPath);
ConfigurationSection worldSection =
PS.get().worlds.getConfigurationSection(worldPath);
String areaName = object.id + "-" + object.min + "-" + object.max;
String areaPath = "areas." + areaName;
if (!worldSection.contains(areaPath)) {
worldSection.createSection(areaPath);
}
ConfigurationSection areaSection = worldSection.getConfigurationSection(areaPath);
ConfigurationSection areaSection =
worldSection.getConfigurationSection(areaPath);
HashMap<String, Object> options = new HashMap<>();
for (ConfigurationNode step : steps) {
options.put(step.getConstant(), step.getValue());
@ -103,7 +99,8 @@ public class BukkitSetupUtils extends SetupUtils {
options.put("generator.type", object.type);
options.put("generator.terrain", object.terrain);
options.put("generator.plugin", object.plotManager);
if (object.setupGenerator != null && !object.setupGenerator.equals(object.plotManager)) {
if (object.setupGenerator != null && !object.setupGenerator
.equals(object.plotManager)) {
options.put("generator.init", object.setupGenerator);
}
for (Entry<String, Object> entry : options.entrySet()) {
@ -129,15 +126,18 @@ public class BukkitSetupUtils extends SetupUtils {
if (!PS.get().worlds.contains(worldPath)) {
PS.get().worlds.createSection(worldPath);
}
ConfigurationSection worldSection = PS.get().worlds.getConfigurationSection(worldPath);
ConfigurationSection worldSection =
PS.get().worlds.getConfigurationSection(worldPath);
for (ConfigurationNode step : steps) {
worldSection.set(step.getConstant(), step.getValue());
}
PS.get().worlds.set("worlds." + world + ".generator.type", object.type);
PS.get().worlds.set("worlds." + world + ".generator.terrain", object.terrain);
PS.get().worlds.set("worlds." + world + ".generator.plugin", object.plotManager);
if (object.setupGenerator != null && !object.setupGenerator.equals(object.plotManager)) {
PS.get().worlds.set("worlds." + world + ".generator.init", object.setupGenerator);
if (object.setupGenerator != null && !object.setupGenerator
.equals(object.plotManager)) {
PS.get().worlds
.set("worlds." + world + ".generator.init", object.setupGenerator);
}
GeneratorWrapper<?> gen = SetupUtils.generators.get(object.setupGenerator);
if (gen != null && gen.isFull()) {
@ -150,7 +150,8 @@ public class BukkitSetupUtils extends SetupUtils {
if (!PS.get().worlds.contains(worldPath)) {
PS.get().worlds.createSection(worldPath);
}
ConfigurationSection worldSection = PS.get().worlds.getConfigurationSection(worldPath);
ConfigurationSection worldSection =
PS.get().worlds.getConfigurationSection(worldPath);
for (ConfigurationNode step : steps) {
worldSection.set(step.getConstant(), step.getValue());
}
@ -164,17 +165,19 @@ public class BukkitSetupUtils extends SetupUtils {
e.printStackTrace();
}
if (object.setupGenerator != null) {
if (Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null && Bukkit.getPluginManager().getPlugin("Multiverse-Core")
.isEnabled()) {
Bukkit.getServer()
.dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv create " + world + " normal -g " + object.setupGenerator);
if (Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null && Bukkit
.getPluginManager().getPlugin("Multiverse-Core").isEnabled()) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mv create " + world + " normal -g " + object.setupGenerator);
setGenerator(world, object.setupGenerator);
if (Bukkit.getWorld(world) != null) {
return world;
}
}
if (Bukkit.getPluginManager().getPlugin("MultiWorld") != null && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled()) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + world + " plugin:" + object.setupGenerator);
if (Bukkit.getPluginManager().getPlugin("MultiWorld") != null && Bukkit
.getPluginManager().getPlugin("MultiWorld").isEnabled()) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mw create " + world + " plugin:" + object.setupGenerator);
setGenerator(world, object.setupGenerator);
if (Bukkit.getWorld(world) != null) {
return world;
@ -187,20 +190,24 @@ public class BukkitSetupUtils extends SetupUtils {
Bukkit.createWorld(wc);
setGenerator(world, object.setupGenerator);
} else {
if (Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null && Bukkit.getPluginManager().getPlugin("Multiverse-Core")
.isEnabled()) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv create " + world + " normal");
if (Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null && Bukkit
.getPluginManager().getPlugin("Multiverse-Core").isEnabled()) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mv create " + world + " normal");
if (Bukkit.getWorld(world) != null) {
return world;
}
}
if (Bukkit.getPluginManager().getPlugin("MultiWorld") != null && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled()) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + world);
if (Bukkit.getPluginManager().getPlugin("MultiWorld") != null && Bukkit
.getPluginManager().getPlugin("MultiWorld").isEnabled()) {
Bukkit.getServer()
.dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + world);
if (Bukkit.getWorld(world) != null) {
return world;
}
}
World bw = Bukkit.createWorld(new WorldCreator(object.world).environment(Environment.NORMAL));
World bw =
Bukkit.createWorld(new WorldCreator(object.world).environment(Environment.NORMAL));
}
return object.world;
}
@ -219,8 +226,7 @@ public class BukkitSetupUtils extends SetupUtils {
}
}
@Override
public String getGenerator(PlotArea plotArea) {
@Override public String getGenerator(PlotArea plotArea) {
if (SetupUtils.generators.isEmpty()) {
updateGenerators();
}

View File

@ -12,39 +12,37 @@ public class BukkitTaskManager extends TaskManager {
this.bukkitMain = bukkitMain;
}
@Override
public int taskRepeat(Runnable runnable, int interval) {
return this.bukkitMain.getServer().getScheduler().scheduleSyncRepeatingTask(this.bukkitMain, runnable, interval, interval);
@Override public int taskRepeat(Runnable runnable, int interval) {
return this.bukkitMain.getServer().getScheduler()
.scheduleSyncRepeatingTask(this.bukkitMain, runnable, interval, interval);
}
@SuppressWarnings("deprecation")
@Override
@SuppressWarnings("deprecation") @Override
public int taskRepeatAsync(Runnable runnable, int interval) {
return this.bukkitMain.getServer().getScheduler().scheduleAsyncRepeatingTask(this.bukkitMain, runnable, interval, interval);
return this.bukkitMain.getServer().getScheduler()
.scheduleAsyncRepeatingTask(this.bukkitMain, runnable, interval, interval);
}
@Override
public void taskAsync(Runnable runnable) {
this.bukkitMain.getServer().getScheduler().runTaskAsynchronously(this.bukkitMain, runnable).getTaskId();
@Override public void taskAsync(Runnable runnable) {
this.bukkitMain.getServer().getScheduler().runTaskAsynchronously(this.bukkitMain, runnable)
.getTaskId();
}
@Override
public void task(Runnable runnable) {
@Override public void task(Runnable runnable) {
this.bukkitMain.getServer().getScheduler().runTask(this.bukkitMain, runnable).getTaskId();
}
@Override
public void taskLater(Runnable runnable, int delay) {
this.bukkitMain.getServer().getScheduler().runTaskLater(this.bukkitMain, runnable, delay).getTaskId();
@Override public void taskLater(Runnable runnable, int delay) {
this.bukkitMain.getServer().getScheduler().runTaskLater(this.bukkitMain, runnable, delay)
.getTaskId();
}
@Override
public void taskLaterAsync(Runnable runnable, int delay) {
this.bukkitMain.getServer().getScheduler().runTaskLaterAsynchronously(this.bukkitMain, runnable, delay);
@Override public void taskLaterAsync(Runnable runnable, int delay) {
this.bukkitMain.getServer().getScheduler()
.runTaskLaterAsynchronously(this.bukkitMain, runnable, delay);
}
@Override
public void cancelTask(int task) {
@Override public void cancelTask(int task) {
if (task != -1) {
Bukkit.getScheduler().cancelTask(task);
}

View File

@ -10,9 +10,6 @@ import com.intellectualcrafters.plot.util.StringComparison;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.util.WorldUtil;
import com.plotsquared.bukkit.object.BukkitPlayer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
@ -26,12 +23,11 @@ import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.MaterialData;
import org.bukkit.material.Sandstone;
import org.bukkit.material.Step;
import org.bukkit.material.Tree;
import org.bukkit.material.WoodenStep;
import org.bukkit.material.Wool;
import org.bukkit.material.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class BukkitUtil extends WorldUtil {
@ -71,12 +67,13 @@ public class BukkitUtil extends WorldUtil {
}
public static Location getLocation(org.bukkit.Location location) {
return new Location(location.getWorld().getName(), MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()),
MathMan.roundInt(location.getZ()));
return new Location(location.getWorld().getName(), MathMan.roundInt(location.getX()),
MathMan.roundInt(location.getY()), MathMan.roundInt(location.getZ()));
}
public static org.bukkit.Location getLocation(Location location) {
return new org.bukkit.Location(getWorld(location.getWorld()), location.getX(), location.getY(), location.getZ());
return new org.bukkit.Location(getWorld(location.getWorld()), location.getX(),
location.getY(), location.getZ());
}
public static World getWorld(String string) {
@ -95,37 +92,40 @@ public class BukkitUtil extends WorldUtil {
public static Location getLocation(Entity entity) {
org.bukkit.Location location = entity.getLocation();
String world = location.getWorld().getName();
return new Location(world, location.getBlockX(), location.getBlockY(), location.getBlockZ());
return new Location(world, location.getBlockX(), location.getBlockY(),
location.getBlockZ());
}
public static Location getLocationFull(Entity entity) {
org.bukkit.Location location = entity.getLocation();
return new Location(location.getWorld().getName(), MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()), MathMan.roundInt(location.getZ()),
location.getYaw(), location.getPitch());
return new Location(location.getWorld().getName(), MathMan.roundInt(location.getX()),
MathMan.roundInt(location.getY()), MathMan.roundInt(location.getZ()), location.getYaw(),
location.getPitch());
}
@Override
public boolean isWorld(String worldName) {
@Override public boolean isWorld(String worldName) {
return getWorld(worldName) != null;
}
@Override
public String getBiome(String world, int x, int z) {
@Override public String getBiome(String world, int x, int z) {
return getWorld(world).getBiome(x, z).name();
}
@Override
public void setSign(String worldName, int x, int y, int z, String[] lines) {
@Override public void setSign(String worldName, int x, int y, int z, String[] lines) {
World world = getWorld(worldName);
Block block = world.getBlockAt(x, y, z);
// block.setType(Material.AIR);
Material type = block.getType();
if (type != Material.SIGN && type != Material.SIGN_POST) {
int data = 2;
if (world.getBlockAt(x, y, z + 1).getType().isSolid()) data = 2;
else if (world.getBlockAt(x + 1, y, z).getType().isSolid()) data = 4;
else if (world.getBlockAt(x, y, z - 1).getType().isSolid()) data = 3;
else if (world.getBlockAt(x - 1, y, z).getType().isSolid()) data = 5;
if (world.getBlockAt(x, y, z + 1).getType().isSolid())
data = 2;
else if (world.getBlockAt(x + 1, y, z).getType().isSolid())
data = 4;
else if (world.getBlockAt(x, y, z - 1).getType().isSolid())
data = 3;
else if (world.getBlockAt(x - 1, y, z).getType().isSolid())
data = 5;
block.setTypeIdAndData(Material.WALL_SIGN.getId(), (byte) data, false);
}
BlockState blockstate = block.getState();
@ -138,9 +138,9 @@ public class BukkitUtil extends WorldUtil {
}
}
@Override
public String[] getSign(Location location) {
Block block = getWorld(location.getWorld()).getBlockAt(location.getX(), location.getY(), location.getZ());
@Override public String[] getSign(Location location) {
Block block = getWorld(location.getWorld())
.getBlockAt(location.getX(), location.getY(), location.getZ());
if (block != null) {
if (block.getState() instanceof Sign) {
Sign sign = (Sign) block.getState();
@ -150,35 +150,31 @@ public class BukkitUtil extends WorldUtil {
return null;
}
@Override
public Location getSpawn(PlotPlayer player) {
@Override public Location getSpawn(PlotPlayer player) {
return getLocation(((BukkitPlayer) player).player.getBedSpawnLocation());
}
@Override
public Location getSpawn(String world) {
@Override public Location getSpawn(String world) {
org.bukkit.Location temp = getWorld(world).getSpawnLocation();
return new Location(world, temp.getBlockX(), temp.getBlockY(), temp.getBlockZ(), temp.getYaw(), temp.getPitch());
return new Location(world, temp.getBlockX(), temp.getBlockY(), temp.getBlockZ(),
temp.getYaw(), temp.getPitch());
}
@Override
public void setSpawn(Location location) {
@Override public void setSpawn(Location location) {
World world = getWorld(location.getWorld());
if (world != null) {
world.setSpawnLocation(location.getX(), location.getY(), location.getZ());
}
}
@Override
public void saveWorld(String worldName) {
@Override public void saveWorld(String worldName) {
World world = getWorld(worldName);
if (world != null) {
world.save();
}
}
@Override
public int getHighestBlock(String world, int x, int z) {
@Override public int getHighestBlock(String world, int x, int z) {
World bukkitWorld = getWorld(world);
// Skip top and bottom block
int air = 1;
@ -187,7 +183,8 @@ public class BukkitUtil extends WorldUtil {
if (block != null) {
Material type = block.getType();
if (type.isSolid()) {
if (air > 1) return y;
if (air > 1)
return y;
air = 0;
} else {
switch (type) {
@ -204,8 +201,7 @@ public class BukkitUtil extends WorldUtil {
return bukkitWorld.getMaxHeight() - 1;
}
@Override
public int getBiomeFromString(String biomeString) {
@Override public int getBiomeFromString(String biomeString) {
try {
Biome biome = Biome.valueOf(biomeString.toUpperCase());
return Arrays.asList(Biome.values()).indexOf(biome);
@ -214,8 +210,7 @@ public class BukkitUtil extends WorldUtil {
}
}
@Override
public String[] getBiomeList() {
@Override public String[] getBiomeList() {
Biome[] biomes = Biome.values();
String[] list = new String[biomes.length];
for (int i = 0; i < biomes.length; i++) {
@ -224,8 +219,7 @@ public class BukkitUtil extends WorldUtil {
return list;
}
@Override
public boolean addItems(String worldName, PlotItem items) {
@Override public boolean addItems(String worldName, PlotItem items) {
World world = getWorld(worldName);
Block block = world.getBlockAt(items.x, items.y, items.z);
if (block == null) {
@ -245,18 +239,15 @@ public class BukkitUtil extends WorldUtil {
return false;
}
@Override
public boolean isBlockSolid(PlotBlock block) {
@Override public boolean isBlockSolid(PlotBlock block) {
try {
Material material = Material.getMaterial(block.id);
if (material.isBlock() && material.isSolid() && !material.hasGravity()) {
Class<? extends MaterialData> data = material.getData();
if (data.equals(MaterialData.class) && !material.isTransparent() && material.isOccluding()
|| data.equals(Tree.class)
|| data.equals(Sandstone.class)
|| data.equals(Wool.class)
|| data.equals(Step.class)
|| data.equals(WoodenStep.class)) {
if (data.equals(MaterialData.class) && !material.isTransparent() && material
.isOccluding() || data.equals(Tree.class) || data.equals(Sandstone.class)
|| data.equals(Wool.class) || data.equals(Step.class) || data
.equals(WoodenStep.class)) {
switch (material) {
case NOTE_BLOCK:
case MOB_SPAWNER:
@ -272,8 +263,7 @@ public class BukkitUtil extends WorldUtil {
}
}
@Override
public String getClosestMatchingName(PlotBlock block) {
@Override public String getClosestMatchingName(PlotBlock block) {
try {
return Material.getMaterial(block.id).name();
} catch (Exception ignored) {
@ -281,12 +271,13 @@ public class BukkitUtil extends WorldUtil {
}
}
@Override
public StringComparison<PlotBlock>.ComparisonResult getClosestBlock(String name) {
@Override public StringComparison<PlotBlock>.ComparisonResult getClosestBlock(String name) {
try {
Material material = Material.valueOf(name.toUpperCase());
return new StringComparison<PlotBlock>().new ComparisonResult(0, PlotBlock.get((short) material.getId(), (byte) 0));
} catch (IllegalArgumentException ignored) {}
return new StringComparison<PlotBlock>().new ComparisonResult(0,
PlotBlock.get((short) material.getId(), (byte) 0));
} catch (IllegalArgumentException ignored) {
}
try {
byte data;
String[] split = name.split(":");
@ -302,7 +293,8 @@ public class BukkitUtil extends WorldUtil {
id = Short.parseShort(split[0]);
match = 0;
} else {
StringComparison<Material>.ComparisonResult comparison = new StringComparison<>(name, Material.values()).getBestMatchAdvanced();
StringComparison<Material>.ComparisonResult comparison =
new StringComparison<>(name, Material.values()).getBestMatchAdvanced();
match = comparison.match;
id = (short) comparison.best.getId();
}
@ -310,12 +302,12 @@ public class BukkitUtil extends WorldUtil {
StringComparison<PlotBlock> outer = new StringComparison<>();
return outer.new ComparisonResult(match, block);
} catch (NumberFormatException ignored) {}
} catch (NumberFormatException ignored) {
}
return null;
}
@Override
public void setBiomes(String worldName, RegionWrapper region, String biomeString) {
@Override public void setBiomes(String worldName, RegionWrapper region, String biomeString) {
World world = getWorld(worldName);
Biome biome = Biome.valueOf(biomeString.toUpperCase());
for (int x = region.minX; x <= region.maxX; x++) {
@ -325,8 +317,7 @@ public class BukkitUtil extends WorldUtil {
}
}
@Override
public PlotBlock getBlock(Location location) {
@Override public PlotBlock getBlock(Location location) {
World world = getWorld(location.getWorld());
Block block = world.getBlockAt(location.getX(), location.getY(), location.getZ());
if (block == null) {
@ -335,8 +326,7 @@ public class BukkitUtil extends WorldUtil {
return PlotBlock.get((short) block.getTypeId(), block.getData());
}
@Override
public String getMainWorld() {
@Override public String getMainWorld() {
return Bukkit.getWorlds().get(0).getName();
}
}

View File

@ -6,12 +6,7 @@ import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.scheduler.BukkitTask;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.net.URLConnection;
@ -22,19 +17,33 @@ import java.util.zip.GZIPOutputStream;
public class Metrics {
/** The current revision number. */
/**
* The current revision number.
*/
private static final int REVISION = 7;
/** The base url of the metrics domain.*/
/**
* The base url of the metrics domain.
*/
private static final String BASE_URL = "http://report.mcstats.org";
/** The url used to report a server's status. */
/**
* The url used to report a server's status.
*/
private static final String REPORT_URL = "/plugin/%s";
/** Interval of time to ping (in minutes). */
/**
* Interval of time to ping (in minutes).
*/
private static final int PING_INTERVAL = 15;
/** The plugin this metrics submits for. */
/**
* The plugin this metrics submits for.
*/
private final Plugin plugin;
/** Unique server id. */
/**
* Unique server id.
*/
private final String guid;
/** The scheduled task. */
/**
* The scheduled task.
*/
private volatile BukkitTask task = null;
public Metrics(Plugin plugin) {
@ -46,7 +55,6 @@ public class Metrics {
* GZip compress a string of bytes.
*
* @param input
*
* @return byte[] the file as a byte array
*/
public static byte[] gzip(String input) {
@ -61,7 +69,8 @@ public class Metrics {
if (gzos != null) {
try {
gzos.close();
} catch (IOException ignore) {}
} catch (IOException ignore) {
}
}
}
return baos.toByteArray();
@ -73,7 +82,6 @@ public class Metrics {
* @param json
* @param key
* @param value
*
*/
private static void appendJSONPair(StringBuilder json, String key, String value) {
boolean isValueNumeric = false;
@ -101,7 +109,6 @@ public class Metrics {
* Escape a string to create a valid JSON string
*
* @param text
*
* @return String
*/
private static String escapeJSON(String text) {
@ -145,7 +152,6 @@ public class Metrics {
* Encode text as UTF-8
*
* @param text the text to encode
*
* @return the encoded text, as UTF-8
*/
private static String urlEncode(String text) throws UnsupportedEncodingException {
@ -165,11 +171,11 @@ public class Metrics {
return true;
}
// Begin hitting the server with glorious data
this.task = this.plugin.getServer().getScheduler().runTaskTimerAsynchronously(this.plugin, new Runnable() {
this.task = this.plugin.getServer().getScheduler()
.runTaskTimerAsynchronously(this.plugin, new Runnable() {
private boolean firstPost = true;
@Override
public void run() {
@Override public void run() {
try {
postPlugin(!this.firstPost);
// After the first post we set firstPost to
@ -196,10 +202,15 @@ public class Metrics {
String serverVersion = Bukkit.getVersion();
int playersOnline = 0;
try {
if (Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).getReturnType() == Collection.class) {
playersOnline = ((Collection<?>) Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).invoke(null)).size();
if (Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).getReturnType()
== Collection.class) {
playersOnline =
((Collection<?>) Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0])
.invoke(null)).size();
} else {
playersOnline = ((Player[]) Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).invoke(null)).length;
playersOnline =
((Player[]) Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0])
.invoke(null)).length;
}
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
ex.printStackTrace();
@ -256,7 +267,8 @@ public class Metrics {
os.flush();
}
String response;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()))) {
response = reader.readLine();
}
if (response == null || response.startsWith("ERR") || response.startsWith("7")) {
@ -267,6 +279,7 @@ public class Metrics {
}
throw new IOException(response);
}
} catch (IOException ignored) {}
} catch (IOException ignored) {
}
}
}

View File

@ -8,36 +8,18 @@ import com.google.common.collect.MapMaker;
import com.google.common.io.ByteSink;
import com.google.common.io.Closeables;
import com.google.common.primitives.Primitives;
import java.io.BufferedInputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.AbstractList;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.inventory.ItemStack;
import java.io.*;
import java.lang.reflect.*;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class NbtFactory {
// Convert between NBT type and the equivalent class in java
@ -77,10 +59,12 @@ public class NbtFactory {
Class<?> offlinePlayer = loader.loadClass(packageName + ".CraftOfflinePlayer");
// Prepare NBT
this.COMPOUND_CLASS = getMethod(0, Modifier.STATIC, offlinePlayer, "getData").getReturnType();
this.COMPOUND_CLASS =
getMethod(0, Modifier.STATIC, offlinePlayer, "getData").getReturnType();
this.BASE_CLASS = loader.loadClass(craftpackageName + ".NBTBase");
this.NBT_GET_TYPE = getMethod(0, Modifier.STATIC, this.BASE_CLASS, "getTypeId");
this.NBT_CREATE_TAG = getMethod(Modifier.STATIC, 0, this.BASE_CLASS, "createTag", byte.class);
this.NBT_CREATE_TAG =
getMethod(Modifier.STATIC, 0, this.BASE_CLASS, "createTag", byte.class);
// Prepare CraftItemStack
this.CRAFT_STACK = loader.loadClass(packageName + ".inventory.CraftItemStack");
@ -92,11 +76,14 @@ public class NbtFactory {
initializeNMS(loader, nmsPackage);
if (this.READ_LIMITER_CLASS != null) {
this.LOAD_COMPOUND = new LoadMethodSkinUpdate(this.STREAM_TOOLS, this.READ_LIMITER_CLASS);
this.LOAD_COMPOUND =
new LoadMethodSkinUpdate(this.STREAM_TOOLS, this.READ_LIMITER_CLASS);
} else {
this.LOAD_COMPOUND = new LoadMethodWorldUpdate(this.STREAM_TOOLS);
}
this.SAVE_COMPOUND = getMethod(Modifier.STATIC, 0, this.STREAM_TOOLS, null, this.BASE_CLASS, DataOutput.class);
this.SAVE_COMPOUND =
getMethod(Modifier.STATIC, 0, this.STREAM_TOOLS, null, this.BASE_CLASS,
DataOutput.class);
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Unable to find offline player.", e);
@ -106,6 +93,7 @@ public class NbtFactory {
/**
* Retrieve or construct a shared NBT factory.
*
* @return The factory.
*/
private static NbtFactory get() {
@ -117,6 +105,7 @@ public class NbtFactory {
/**
* Construct a new NBT list of an unspecified type.
*
* @return The NBT list.
*/
public static NbtList createList(Object... content) {
@ -125,6 +114,7 @@ public class NbtFactory {
/**
* Construct a new NBT list of an unspecified type.
*
* @return The NBT list.
*/
public static NbtList createList(Iterable<? extends Object> iterable) {
@ -148,6 +138,7 @@ public class NbtFactory {
/**
* Construct a new NBT wrapper from a list.
*
* @param nmsList - the NBT list.
* @return The wrapper.
*/
@ -163,7 +154,8 @@ public class NbtFactory {
* @return The decoded NBT compound.
* @throws IOException If anything went wrong.
*/
public static NbtCompound fromStream(InputStream input, StreamOptions option) throws IOException {
public static NbtCompound fromStream(InputStream input, StreamOptions option)
throws IOException {
DataInputStream data = null;
boolean suppress = true;
@ -195,14 +187,16 @@ public class NbtFactory {
* @param option - whether or not to compress the output.
* @throws IOException If anything went wrong.
*/
public static void saveStream(NbtCompound source, ByteSink stream, StreamOptions option) throws IOException {
public static void saveStream(NbtCompound source, ByteSink stream, StreamOptions option)
throws IOException {
OutputStream output = null;
DataOutputStream data = null;
boolean suppress = true;
try {
output = stream.openStream();
data = new DataOutputStream(option == StreamOptions.GZIP_COMPRESSION ? new GZIPOutputStream(output) : output);
data = new DataOutputStream(
option == StreamOptions.GZIP_COMPRESSION ? new GZIPOutputStream(output) : output);
invokeMethod(get().SAVE_COMPOUND, null, source.getHandle(), data);
suppress = false;
@ -218,6 +212,7 @@ public class NbtFactory {
/**
* Construct a new NBT wrapper from a compound.
*
* @param nmsCompound - the NBT compound.
* @return The wrapper.
*/
@ -228,6 +223,7 @@ public class NbtFactory {
/**
* Set the NBT compound tag of a given item stack.
* <p>
*
* @param stack - the item stack, cannot be air.
* @param compound - the new NBT compound, or NULL to remove it.
* @throws IllegalArgumentException If the stack is not a CraftItemStack, or it represents air.
@ -246,6 +242,7 @@ public class NbtFactory {
* material, damage value or count.
* <p>
* The item stack must be a wrapper for a CraftItemStack.
*
* @param stack - the item stack.
* @return A wrapper for its NBT tag.
*/
@ -265,6 +262,7 @@ public class NbtFactory {
/**
* Retrieve a CraftItemStack version of the stack.
*
* @param stack - the stack to convert.
* @return The CraftItemStack version.
*/
@ -279,12 +277,14 @@ public class NbtFactory {
caller.setAccessible(true);
return (ItemStack) caller.newInstance(stack);
} catch (Exception ignored) {
throw new IllegalStateException("Unable to convert " + stack + " + to a CraftItemStack.");
throw new IllegalStateException(
"Unable to convert " + stack + " + to a CraftItemStack.");
}
}
/**
* Ensure that the given stack can store arbitrary NBT information.
*
* @param stack - the stack to check.
*/
private static void checkItemStack(ItemStack stack) {
@ -295,12 +295,14 @@ public class NbtFactory {
throw new IllegalArgumentException("Stack must be a CraftItemStack.");
}
if (stack.getType() == Material.AIR) {
throw new IllegalArgumentException("ItemStacks representing air cannot store NMS information.");
throw new IllegalArgumentException(
"ItemStacks representing air cannot store NMS information.");
}
}
/**
* Invoke a method on the given target instance using the provided parameters.
*
* @param method - the method to invoke.
* @param target - the target.
* @param params - the parameters to supply.
@ -332,6 +334,7 @@ public class NbtFactory {
/**
* Search for the first publicly and privately defined method of the given name and parameter count.
*
* @param requireMod - modifiers that are required.
* @param bannedMod - modifiers that are banned.
* @param clazz - a class to start with.
@ -340,14 +343,14 @@ public class NbtFactory {
* @return The first method by this name.
* @throws IllegalStateException If we cannot find this method.
*/
private static Method getMethod(int requireMod, int bannedMod, Class<?> clazz, String methodName,
Class<?>... params) {
private static Method getMethod(int requireMod, int bannedMod, Class<?> clazz,
String methodName, Class<?>... params) {
for (Method method : clazz.getDeclaredMethods()) {
// Limitation: Doesn't handle overloads
if (((method.getModifiers() & requireMod) == requireMod)
&& ((method.getModifiers() & bannedMod) == 0)
&& ((methodName == null) || method.getName().equals(methodName))
&& Arrays.equals(method.getParameterTypes(), params)) {
if (((method.getModifiers() & requireMod) == requireMod) && (
(method.getModifiers() & bannedMod) == 0) && ((methodName == null) || method
.getName().equals(methodName)) && Arrays
.equals(method.getParameterTypes(), params)) {
method.setAccessible(true);
return method;
@ -357,11 +360,13 @@ public class NbtFactory {
if (clazz.getSuperclass() != null) {
return getMethod(requireMod, bannedMod, clazz.getSuperclass(), methodName, params);
}
throw new IllegalStateException(String.format("Unable to find method %s (%s).", methodName, Arrays.asList(params)));
throw new IllegalStateException(
String.format("Unable to find method %s (%s).", methodName, Arrays.asList(params)));
}
/**
* Search for the first publicly and privately defined field of the given name.
*
* @param instance - an instance of the class with the field.
* @param clazz - an optional class to start with, or NULL to deduce it from instance.
* @param fieldName - the field name.
@ -390,7 +395,8 @@ public class NbtFactory {
try {
this.STREAM_TOOLS = loader.loadClass(nmsPackage + ".NBTCompressedStreamTools");
this.READ_LIMITER_CLASS = loader.loadClass(nmsPackage + ".NBTReadLimiter");
} catch (ClassNotFoundException ignored) {}
} catch (ClassNotFoundException ignored) {
}
}
private String getPackageName() {
@ -406,22 +412,23 @@ public class NbtFactory {
}
private String getCraftPackageName() {
String version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
String version =
Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
return "net.minecraft.server." + version;
}
@SuppressWarnings("unchecked")
private Map<String, Object> getDataMap(Object handle) {
return (Map<String, Object>) getFieldValue(getDataField(NbtType.TAG_COMPOUND, handle), handle);
@SuppressWarnings("unchecked") private Map<String, Object> getDataMap(Object handle) {
return (Map<String, Object>) getFieldValue(getDataField(NbtType.TAG_COMPOUND, handle),
handle);
}
@SuppressWarnings("unchecked")
private List<Object> getDataList(Object handle) {
@SuppressWarnings("unchecked") private List<Object> getDataList(Object handle) {
return (List<Object>) getFieldValue(getDataField(NbtType.TAG_LIST, handle), handle);
}
/**
* Convert wrapped List and Map objects into their respective NBT counterparts.
*
* @param value - the value of the element to create. Can be a List or a Map.
* @return The NBT element.
*/
@ -444,6 +451,7 @@ public class NbtFactory {
/**
* Convert a given NBT element to a primitive wrapper or List/Map equivalent.
* <p> All changes to any mutable objects will be reflected in the underlying NBT element(s).
*
* @param nms - the NBT element.
* @return The wrapper equivalent.
*/
@ -470,6 +478,7 @@ public class NbtFactory {
/**
* Construct a new NMS NBT tag initialized with the given value.
*
* @param type - the NBT type.
* @param value - the value, or NULL to keep the original value.
* @return The created tag.
@ -485,6 +494,7 @@ public class NbtFactory {
/**
* Retrieve the field where the NBT class stores its value.
*
* @param type - the NBT type.
* @param nms - the NBT class instance.
* @return The corresponding field.
@ -498,6 +508,7 @@ public class NbtFactory {
/**
* Retrieve the NBT type from a given NMS NBT tag.
*
* @param nms - the native NBT tag.
* @return The corresponding type.
*/
@ -508,40 +519,38 @@ public class NbtFactory {
/**
* Retrieve the nearest NBT type for a given primitive type.
*
* @param primitive - the primitive type.
* @return The corresponding type.
*/
private NbtType getPrimitiveType(Object primitive) {
NbtType type = NBT_ENUM.get(NBT_CLASS.inverse().get(Primitives.unwrap(primitive.getClass())));
NbtType type =
NBT_ENUM.get(NBT_CLASS.inverse().get(Primitives.unwrap(primitive.getClass())));
// Display the illegal value at least
if (type == null) {
throw new IllegalArgumentException(String.format("Illegal type: %s (%s)", primitive.getClass(), primitive));
throw new IllegalArgumentException(
String.format("Illegal type: %s (%s)", primitive.getClass(), primitive));
}
return type;
}
/**
* Whether or not to enable stream compression.
*
* @author Kristian
*/
public enum StreamOptions {
NO_COMPRESSION, GZIP_COMPRESSION,
}
private enum NbtType {
TAG_END(0, Void.class),
TAG_BYTE(1, byte.class),
TAG_SHORT(2, short.class),
TAG_INT(3, int.class),
TAG_LONG(4, long.class),
TAG_FLOAT(5, float.class),
TAG_DOUBLE(6, double.class),
TAG_BYTE_ARRAY(7, byte[].class),
TAG_INT_ARRAY(11, int[].class),
TAG_STRING(8, String.class),
TAG_LIST(9, List.class),
TAG_COMPOUND(10, Map.class);
TAG_END(0, Void.class), TAG_BYTE(1, byte.class), TAG_SHORT(2, short.class), TAG_INT(3,
int.class), TAG_LONG(4, long.class), TAG_FLOAT(5, float.class), TAG_DOUBLE(6,
double.class), TAG_BYTE_ARRAY(7, byte[].class), TAG_INT_ARRAY(11,
int[].class), TAG_STRING(8, String.class), TAG_LIST(9, List.class), TAG_COMPOUND(10,
Map.class);
// Unique NBT type
public final int id;
@ -563,21 +572,26 @@ public class NbtFactory {
}
}
/**
* Represents an object that provides a view of a native NMS class.
*
* @author Kristian
*/
public interface Wrapper {
/**
* Retrieve the underlying native NBT tag.
*
* @return The underlying NBT.
*/
Object getHandle();
}
/**
* Represents a method for loading an NBT compound.
*
* @author Kristian
*/
private static abstract class LoadCompoundMethod {
@ -591,12 +605,14 @@ public class NbtFactory {
/**
* Load an NBT compound from a given stream.
*
* @param input - the input stream.
* @return The loaded NBT compound.
*/
public abstract Object loadNbt(DataInput input);
}
/**
* Load an NBT compound from the NBTCompressedStreamTools static method in 1.7.2 - 1.7.5
*/
@ -606,12 +622,12 @@ public class NbtFactory {
setMethod(getMethod(Modifier.STATIC, 0, streamClass, null, DataInput.class));
}
@Override
public Object loadNbt(DataInput input) {
@Override public Object loadNbt(DataInput input) {
return invokeMethod(this.staticMethod, null, input);
}
}
/**
* Load an NBT compound from the NBTCompressedStreamTools static method in 1.7.8
*/
@ -620,7 +636,8 @@ public class NbtFactory {
private Object readLimiter;
LoadMethodSkinUpdate(Class<?> streamClass, Class<?> readLimiterClass) {
setMethod(getMethod(Modifier.STATIC, 0, streamClass, null, DataInput.class, readLimiterClass));
setMethod(getMethod(Modifier.STATIC, 0, streamClass, null, DataInput.class,
readLimiterClass));
// Find the unlimited read limiter
for (Field field : readLimiterClass.getDeclaredFields()) {
@ -634,12 +651,12 @@ public class NbtFactory {
}
}
@Override
public Object loadNbt(DataInput input) {
@Override public Object loadNbt(DataInput input) {
return invokeMethod(this.staticMethod, null, input, this.readLimiter);
}
}
/**
* Represents a root NBT compound.
* <p> All changes to this map will be reflected in the underlying NBT compound. Values may only be one of the following:
@ -655,6 +672,7 @@ public class NbtFactory {
* <li>{@link NbtFactory#createCompound()}</li>
* <li>{@link NbtFactory#fromCompound(Object)}</li>
* </ul>
*
* @author Kristian
*/
public final class NbtCompound extends ConvertedMap {
@ -702,6 +720,7 @@ public class NbtFactory {
/**
* Retrieve the list by the given name.
*
* @param key - the name of the list.
* @param createNew - whether or not to create a new list if its missing.
* @return An existing list, a new list or NULL.
@ -717,6 +736,7 @@ public class NbtFactory {
/**
* Retrieve the map by the given name.
*
* @param key - the name of the map.
* @param createNew - whether or not to create a new map if its missing.
* @return An existing map, a new map or NULL.
@ -732,6 +752,7 @@ public class NbtFactory {
* <p>
* Every element of the path (except the end) are assumed to be compounds, and will
* be created if they are missing.
*
* @param path - the path to the entry.
* @param value - the new value of this entry.
* @return This compound, for chaining.
@ -749,11 +770,11 @@ public class NbtFactory {
* <p>
* Every element of the path (except the end) are assumed to be compounds. The
* retrieval operation will be cancelled if any of them are missing.
*
* @param path - path to the entry.
* @return The value, or NULL if not found.
*/
@SuppressWarnings("unchecked")
public <T> T getPath(String path) {
@SuppressWarnings("unchecked") public <T> T getPath(String path) {
List<String> entries = getPathElements(path);
NbtCompound map = getMap(entries.subList(0, entries.size() - 1), false);
@ -765,6 +786,7 @@ public class NbtFactory {
/**
* Save the content of a NBT compound to a stream.
*
* @param stream - the output stream.
* @param option - whether or not to compress the output.
* @throws IOException If anything went wrong.
@ -775,6 +797,7 @@ public class NbtFactory {
/**
* Retrieve a map from a given path.
*
* @param path - path of compounds to look up.
* @param createNew - whether or not to create new compounds on the way.
* @return The map at this location.
@ -798,6 +821,7 @@ public class NbtFactory {
/**
* Split the path into separate elements.
*
* @param path - the path to split.
* @return The elements.
*/
@ -806,6 +830,7 @@ public class NbtFactory {
}
}
/**
* Represents a root NBT list.
* See also:
@ -813,6 +838,7 @@ public class NbtFactory {
* <li>{@link NbtFactory#createList(Iterable)}}</li>
* <li>{@link NbtFactory#fromList(Object)}</li>
* </ul>
*
* @author Kristian
*/
public final class NbtList extends ConvertedList {
@ -822,8 +848,10 @@ public class NbtFactory {
}
}
/**
* Represents a class for caching wrappers.
*
* @author Kristian
*/
private final class CachedNativeWrapper {
@ -846,9 +874,11 @@ public class NbtFactory {
}
}
/**
* Represents a map that wraps another map and automatically
* converts entries of its type and another exposed type.
*
* @author Kristian
*/
private class ConvertedMap extends AbstractMap<String, Object> implements Wrapper {
@ -873,32 +903,26 @@ public class NbtFactory {
}
// Modification
@Override
public Object put(String key, Object value) {
@Override public Object put(String key, Object value) {
return wrapOutgoing(this.original.put(key, unwrapIncoming(value)));
}
// Performance
@Override
public Object get(Object key) {
@Override public Object get(Object key) {
return wrapOutgoing(this.original.get(key));
}
@Override
public Object remove(Object key) {
@Override public Object remove(Object key) {
return wrapOutgoing(this.original.remove(key));
}
@Override
public boolean containsKey(Object key) {
@Override public boolean containsKey(Object key) {
return this.original.containsKey(key);
}
@Override
public Set<Entry<String, Object>> entrySet() {
@Override public Set<Entry<String, Object>> entrySet() {
return new AbstractSet<Entry<String, Object>>() {
@Override
public boolean add(Entry<String, Object> e) {
@Override public boolean add(Entry<String, Object> e) {
String key = e.getKey();
Object value = e.getValue();
@ -906,13 +930,11 @@ public class NbtFactory {
return true;
}
@Override
public int size() {
@Override public int size() {
return ConvertedMap.this.original.size();
}
@Override
public Iterator<Entry<String, Object>> iterator() {
@Override public Iterator<Entry<String, Object>> iterator() {
return ConvertedMap.this.iterator();
}
};
@ -922,34 +944,33 @@ public class NbtFactory {
final Iterator<Entry<String, Object>> proxy = this.original.entrySet().iterator();
return new Iterator<Entry<String, Object>>() {
@Override
public boolean hasNext() {
@Override public boolean hasNext() {
return proxy.hasNext();
}
@Override
public Entry<String, Object> next() {
@Override public Entry<String, Object> next() {
Entry<String, Object> entry = proxy.next();
return new SimpleEntry<String, Object>(entry.getKey(), wrapOutgoing(entry.getValue()));
return new SimpleEntry<String, Object>(entry.getKey(),
wrapOutgoing(entry.getValue()));
}
@Override
public void remove() {
@Override public void remove() {
proxy.remove();
}
};
}
@Override
public Object getHandle() {
@Override public Object getHandle() {
return this.handle;
}
}
/**
* Represents a list that wraps another list and converts elements
* of its type and another exposed type.
*
* @author Kristian
*/
private class ConvertedList extends AbstractList<Object> implements Wrapper {
@ -975,44 +996,38 @@ public class NbtFactory {
return unwrapValue(wrapped);
}
@Override
public Object get(int index) {
@Override public Object get(int index) {
return wrapOutgoing(this.original.get(index));
}
@Override
public int size() {
@Override public int size() {
return this.original.size();
}
@Override
public Object set(int index, Object element) {
@Override public Object set(int index, Object element) {
return wrapOutgoing(this.original.set(index, unwrapIncoming(element)));
}
@Override
public void add(int index, Object element) {
@Override public void add(int index, Object element) {
Object nbt = unwrapIncoming(element);
// Set the list type if its the first element
if (size() == 0) {
setFieldValue(NbtFactory.this.NBT_LIST_TYPE, this.handle, (byte) getNbtType(nbt).id);
setFieldValue(NbtFactory.this.NBT_LIST_TYPE, this.handle,
(byte) getNbtType(nbt).id);
}
this.original.add(index, nbt);
}
@Override
public Object remove(int index) {
@Override public Object remove(int index) {
return wrapOutgoing(this.original.remove(index));
}
@Override
public boolean remove(Object o) {
@Override public boolean remove(Object o) {
return this.original.remove(unwrapIncoming(o));
}
@Override
public Object getHandle() {
@Override public Object getHandle() {
return this.handle;
}
}

View File

@ -1,13 +1,5 @@
package com.plotsquared.bukkit.util;
import static com.intellectualcrafters.plot.util.ReflectionUtils.callConstructor;
import static com.intellectualcrafters.plot.util.ReflectionUtils.callMethod;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getCbClass;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getNmsClass;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getUtilClass;
import static com.intellectualcrafters.plot.util.ReflectionUtils.makeConstructor;
import static com.intellectualcrafters.plot.util.ReflectionUtils.makeMethod;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Entity;
@ -17,6 +9,8 @@ import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.UUID;
import static com.intellectualcrafters.plot.util.ReflectionUtils.*;
public class OfflinePlayerUtil {
public static Player loadPlayer(String name) {
@ -43,10 +37,12 @@ public class OfflinePlayerUtil {
Object worldServer = getWorldServer();
Object profile = newGameProfile(id, name);
Class<?> entityPlayerClass = getNmsClass("EntityPlayer");
Constructor entityPlayerConstructor = makeConstructor(entityPlayerClass, getNmsClass("MinecraftServer"), getNmsClass("WorldServer"),
getUtilClass("com.mojang.authlib.GameProfile"),
Constructor entityPlayerConstructor =
makeConstructor(entityPlayerClass, getNmsClass("MinecraftServer"),
getNmsClass("WorldServer"), getUtilClass("com.mojang.authlib.GameProfile"),
getNmsClass("PlayerInteractManager"));
Object entityPlayer = callConstructor(entityPlayerConstructor, server, worldServer, profile, interactManager);
Object entityPlayer =
callConstructor(entityPlayerConstructor, server, worldServer, profile, interactManager);
return (Player) getBukkitEntity(entityPlayer);
}
@ -55,7 +51,8 @@ public class OfflinePlayerUtil {
if (gameProfileClass == null) { //Before uuids
return name;
}
Constructor gameProfileConstructor = makeConstructor(gameProfileClass, UUID.class, String.class);
Constructor gameProfileConstructor =
makeConstructor(gameProfileClass, UUID.class, String.class);
if (gameProfileConstructor == null) { //Version has string constructor
gameProfileConstructor = makeConstructor(gameProfileClass, String.class, String.class);
return callConstructor(gameProfileConstructor, id.toString(), name);

View File

@ -1,7 +1,5 @@
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;
@ -25,6 +23,8 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
/**
* An utility that can be used to send chunks, rather than using bukkit code
* to do so (uses heavy NMS).
@ -52,12 +52,14 @@ public class SendChunk {
RefClass classMapChunk = getRefClass("{nms}.PacketPlayOutMapChunk");
if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_9_4)) {
//this works for 1.9.4 and 1.10
tempMapChunk = classMapChunk.getConstructor(classChunk.getRealClass(),int.class);
tempMapChunk = classMapChunk.getConstructor(classChunk.getRealClass(), int.class);
} else {
try {
tempMapChunk = classMapChunk.getConstructor(classChunk.getRealClass(), boolean.class, int.class);
tempMapChunk = classMapChunk
.getConstructor(classChunk.getRealClass(), boolean.class, int.class);
} catch (NoSuchMethodException ignored) {
tempMapChunk = classMapChunk.getConstructor(classChunk.getRealClass(),boolean.class, int.class, int.class);
tempMapChunk = classMapChunk
.getConstructor(classChunk.getRealClass(), boolean.class, int.class, int.class);
}
}
this.mapChunk = tempMapChunk;
@ -118,8 +120,9 @@ public class SendChunk {
Object packet = null;
if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_9_4)) {
try {
packet = this.mapChunk.create(c,65535);
} catch (Exception ignored) {}
packet = this.mapChunk.create(c, 65535);
} catch (Exception ignored) {
}
} else {
try {
packet = this.mapChunk.create(c, true, 65535);
@ -139,13 +142,13 @@ public class SendChunk {
}
for (final Chunk chunk : chunks) {
TaskManager.runTask(new Runnable() {
@Override
public void run() {
@Override public void run() {
try {
chunk.unload(true, false);
} catch (Throwable ignored) {
String worldName = chunk.getWorld().getName();
PS.debug("$4Could not save chunk: " + worldName + ';' + chunk.getX() + ";" + chunk.getZ());
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)");

View File

@ -4,34 +4,35 @@ import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.block.BasicLocalBlockQueue;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.block.Block;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class BukkitLocalQueue<T> extends BasicLocalBlockQueue<T> {
private Field fieldNeighbors;
private Method chunkGetHandle;
public BukkitLocalQueue(String world) {
super(world);
}
@Override
public LocalChunk<T> getLocalChunk(int x, int z) {
@Override public LocalChunk<T> getLocalChunk(int x, int z) {
return (LocalChunk<T>) new BasicLocalChunk(this, x, z) {
// Custom stuff?
};
}
@Override
public void optimize() {
@Override public void optimize() {
}
@Override
public PlotBlock getBlock(int x, int y, int z) {
@Override public PlotBlock getBlock(int x, int y, int z) {
World worldObj = Bukkit.getWorld(getWorld());
Block block = worldObj.getBlockAt(x, y, z);
if (block == null) {
@ -44,25 +45,21 @@ public class BukkitLocalQueue<T> extends BasicLocalBlockQueue<T> {
return PlotBlock.get(id, block.getData());
}
@Override
public void refreshChunk(int x, int z) {
@Override public void refreshChunk(int x, int z) {
World worldObj = Bukkit.getWorld(getWorld());
worldObj.refreshChunk(x, z);
}
@Override
public void fixChunkLighting(int x, int z) {
@Override public void fixChunkLighting(int x, int z) {
// Do nothing
}
@Override
public final void regenChunk(int x, int z) {
@Override public final void regenChunk(int x, int z) {
World worldObj = Bukkit.getWorld(getWorld());
worldObj.regenerateChunk(x, z);
}
@Override
public final void setComponents(LocalChunk<T> lc) {
@Override public final void setComponents(LocalChunk<T> lc) {
setBlocks(lc);
setBiomes(lc);
}
@ -129,13 +126,11 @@ public class BukkitLocalQueue<T> extends BasicLocalBlockQueue<T> {
}
}
private Field fieldNeighbors;
private Method chunkGetHandle;
/**
* Exploiting a bug in the vanilla lighting algorithm for faster block placement
* - Could have been achieved without reflection by force unloading specific chunks
* - Much faster just setting the variable manually though
*
* @param chunk
* @return
*/
@ -153,7 +148,8 @@ public class BukkitLocalQueue<T> extends BasicLocalBlockQueue<T> {
Object value = fieldNeighbors.get(nmsChunk);
fieldNeighbors.set(nmsChunk, 0);
return new Object[] {nmsChunk, value};
} catch (Throwable ignore) {}
} catch (Throwable ignore) {
}
return null;
}
@ -181,7 +177,8 @@ public class BukkitLocalQueue<T> extends BasicLocalBlockQueue<T> {
if (disableResult != null) {
try {
fieldNeighbors.set(disableResult[0], 0x739C0);
} catch (Throwable ignore) {}
} catch (Throwable ignore) {
}
}
}
}

View File

@ -6,16 +6,11 @@ import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.ReflectionUtils;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.bukkit.util.SendChunk;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.World;
import java.util.*;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
@ -36,24 +31,26 @@ public class BukkitLocalQueue_1_7 extends BukkitLocalQueue<PlotBlock[]> {
private final HashMap<ChunkWrapper, Chunk> toUpdate = new HashMap<>();
public BukkitLocalQueue_1_7(String world) throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException {
public BukkitLocalQueue_1_7(String world)
throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException {
super(world);
this.methodGetHandle = this.classCraftWorld.getMethod("getHandle");
this.methodGetChunkAt = this.classWorld.getMethod("getChunkAt", int.class, int.class);
this.methodA = this.classChunk.getMethod("a", int.class, int.class, int.class, this.classBlock, int.class);
this.methodA = this.classChunk
.getMethod("a", int.class, int.class, int.class, this.classBlock, int.class);
this.methodGetById = this.classBlock.getMethod("getById", int.class);
this.methodGetHandleChunk = this.classCraftChunk.getMethod("getHandle");
this.methodInitLighting = this.classChunk.getMethod("initLighting");
this.sendChunk = new SendChunk();
TaskManager.runTaskRepeat(new Runnable() {
@Override
public void run() {
@Override public void run() {
if (BukkitLocalQueue_1_7.this.toUpdate.isEmpty()) {
return;
}
int count = 0;
ArrayList<Chunk> chunks = new ArrayList<>();
Iterator<Map.Entry<ChunkWrapper, Chunk>> i = BukkitLocalQueue_1_7.this.toUpdate.entrySet().iterator();
Iterator<Map.Entry<ChunkWrapper, Chunk>> i =
BukkitLocalQueue_1_7.this.toUpdate.entrySet().iterator();
while (i.hasNext() && (count < 128)) {
chunks.add(i.next().getValue());
i.remove();
@ -88,14 +85,12 @@ public class BukkitLocalQueue_1_7 extends BukkitLocalQueue<PlotBlock[]> {
}
}
@Override
public void fixChunkLighting(int x, int z) {
@Override public void fixChunkLighting(int x, int z) {
Object c = this.methodGetHandleChunk.of(getChunk(x, z)).call();
this.methodInitLighting.of(c).call();
}
@Override
public void setBlocks(LocalChunk<PlotBlock[]> lc) {
@Override public void setBlocks(LocalChunk<PlotBlock[]> lc) {
Chunk chunk = getChunk(lc.getX(), lc.getZ());
chunk.load(true);
World world = chunk.getWorld();
@ -128,8 +123,7 @@ public class BukkitLocalQueue_1_7 extends BukkitLocalQueue<PlotBlock[]> {
fixChunkLighting(lc.getX(), lc.getZ());
}
@Override
public void refreshChunk(int x, int z) {
@Override public void refreshChunk(int x, int z) {
update(Arrays.asList(Bukkit.getWorld(getWorld()).getChunkAt(x, z)));
}
}

View File

@ -1,7 +1,5 @@
package com.plotsquared.bukkit.util.block;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
import com.intellectualcrafters.plot.object.ChunkWrapper;
import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.util.MainUtil;
@ -10,17 +8,15 @@ import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.bukkit.util.SendChunk;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Block;
import java.util.*;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
public class BukkitLocalQueue_1_8 extends BukkitLocalQueue<PlotBlock[]> {
private final ReflectionUtils.RefMethod methodInitLighting;
@ -39,26 +35,29 @@ public class BukkitLocalQueue_1_8 extends BukkitLocalQueue<PlotBlock[]> {
private final SendChunk sendChunk;
private final RefMethod methodGetHandleChunk;
public BukkitLocalQueue_1_8(String world) throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException {
public BukkitLocalQueue_1_8(String world)
throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException {
super(world);
this.methodInitLighting = this.classChunk.getMethod("initLighting");
this.constructorBlockPosition = this.classBlockPosition.getConstructor(int.class, int.class, int.class);
this.constructorBlockPosition =
this.classBlockPosition.getConstructor(int.class, int.class, int.class);
this.methodGetByCombinedId = this.classBlock.getMethod("getByCombinedId", int.class);
this.methodGetHandle = this.classCraftWorld.getMethod("getHandle");
RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle");
this.methodGetChunkAt = this.classWorld.getMethod("getChunkAt", int.class, int.class);
this.methodA = this.classChunk.getMethod("a", this.classBlockPosition, this.classIBlockData);
this.methodA =
this.classChunk.getMethod("a", this.classBlockPosition, this.classIBlockData);
this.sendChunk = new SendChunk();
TaskManager.runTaskRepeat(new Runnable() {
@Override
public void run() {
@Override public void run() {
if (BukkitLocalQueue_1_8.this.toUpdate.isEmpty()) {
return;
}
int count = 0;
ArrayList<Chunk> chunks = new ArrayList<>();
Iterator<Map.Entry<ChunkWrapper, Chunk>> i = BukkitLocalQueue_1_8.this.toUpdate.entrySet().iterator();
Iterator<Map.Entry<ChunkWrapper, Chunk>> i =
BukkitLocalQueue_1_8.this.toUpdate.entrySet().iterator();
while (i.hasNext() && count < 128) {
chunks.add(i.next().getValue());
i.remove();
@ -73,14 +72,12 @@ public class BukkitLocalQueue_1_8 extends BukkitLocalQueue<PlotBlock[]> {
MainUtil.initCache();
}
@Override
public void fixChunkLighting(int x, int z) {
@Override public void fixChunkLighting(int x, int z) {
Object c = this.methodGetHandleChunk.of(getChunk(x, z)).call();
this.methodInitLighting.of(c).call();
}
@Override
public void setBlocks(LocalChunk<PlotBlock[]> lc) {
@Override public void setBlocks(LocalChunk<PlotBlock[]> lc) {
Chunk chunk = getChunk(lc.getX(), lc.getZ());
chunk.load(true);
World world = chunk.getWorld();
@ -100,7 +97,8 @@ public class BukkitLocalQueue_1_8 extends BukkitLocalQueue<PlotBlock[]> {
int y = MainUtil.y_loc[i][j];
int z = MainUtil.z_loc[i][j];
PlotBlock newBlock = result2[j];
if (newBlock == null) continue;
if (newBlock == null)
continue;
if (newBlock.id == -1) {
chunk.getBlock(x, y, z).setData(newBlock.data, false);
@ -309,7 +307,8 @@ public class BukkitLocalQueue_1_8 extends BukkitLocalQueue<PlotBlock[]> {
} catch (ReflectiveOperationException e) {
e.printStackTrace();
}
Object combined = this.methodGetByCombinedId.call(newBlock.id + (newBlock.data << 12));
Object combined =
this.methodGetByCombinedId.call(newBlock.id + (newBlock.data << 12));
this.methodA.of(c).call(pos, combined);
}
}
@ -336,8 +335,7 @@ public class BukkitLocalQueue_1_8 extends BukkitLocalQueue<PlotBlock[]> {
}
}
@Override
public void refreshChunk(int x, int z) {
@Override public void refreshChunk(int x, int z) {
update(Arrays.asList(Bukkit.getWorld(getWorld()).getChunkAt(x, z)));
}
}

View File

@ -9,20 +9,14 @@ import com.intellectualcrafters.plot.util.ReflectionUtils;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.block.BasicLocalBlockQueue;
import com.plotsquared.bukkit.util.SendChunk;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Material;
import org.bukkit.World;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
@ -43,7 +37,8 @@ public class BukkitLocalQueue_1_8_3 extends BukkitLocalQueue<char[]> {
private final ReflectionUtils.RefMethod methodGetWorld;
private final ReflectionUtils.RefField tileEntityListTick;
public BukkitLocalQueue_1_8_3(String world) throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException {
public BukkitLocalQueue_1_8_3(String world)
throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException {
super(world);
ReflectionUtils.RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
ReflectionUtils.RefClass classCraftWorld = getRefClass("{cb}.CraftWorld");
@ -51,7 +46,8 @@ public class BukkitLocalQueue_1_8_3 extends BukkitLocalQueue<char[]> {
ReflectionUtils.RefClass classChunk = getRefClass("{nms}.Chunk");
this.methodInitLighting = classChunk.getMethod("initLighting");
ReflectionUtils.RefClass classBlockPosition = getRefClass("{nms}.BlockPosition");
this.classBlockPositionConstructor = classBlockPosition.getConstructor(int.class, int.class, int.class);
this.classBlockPositionConstructor =
classBlockPosition.getConstructor(int.class, int.class, int.class);
ReflectionUtils.RefClass classWorld = getRefClass("{nms}.World");
this.methodX = classWorld.getMethod("x", classBlockPosition.getRealClass());
this.fieldSections = classChunk.getField("sections");
@ -59,20 +55,21 @@ public class BukkitLocalQueue_1_8_3 extends BukkitLocalQueue<char[]> {
ReflectionUtils.RefClass classChunkSection = getRefClass("{nms}.ChunkSection");
this.methodGetIdArray = classChunkSection.getMethod("getIdArray");
this.methodAreNeighborsLoaded = classChunk.getMethod("areNeighborsLoaded", int.class);
this.classChunkSectionConstructor = classChunkSection.getConstructor(int.class, boolean.class, char[].class);
this.classChunkSectionConstructor =
classChunkSection.getConstructor(int.class, boolean.class, char[].class);
this.tileEntityListTick = classWorld.getField("tileEntityList");
this.methodGetHandleWorld = classCraftWorld.getMethod("getHandle");
this.methodGetWorld = classChunk.getMethod("getWorld");
this.sendChunk = new SendChunk();
TaskManager.runTaskRepeat(new Runnable() {
@Override
public void run() {
@Override public void run() {
if (BukkitLocalQueue_1_8_3.this.toUpdate.isEmpty()) {
return;
}
int count = 0;
ArrayList<Chunk> chunks = new ArrayList<>();
Iterator<Map.Entry<ChunkWrapper, Chunk>> i = BukkitLocalQueue_1_8_3.this.toUpdate.entrySet().iterator();
Iterator<Map.Entry<ChunkWrapper, Chunk>> i =
BukkitLocalQueue_1_8_3.this.toUpdate.entrySet().iterator();
while (i.hasNext() && count < 128) {
chunks.add(i.next().getValue());
i.remove();
@ -87,11 +84,290 @@ public class BukkitLocalQueue_1_8_3 extends BukkitLocalQueue<char[]> {
MainUtil.initCache();
}
@Override
public LocalChunk<char[]> getLocalChunk(int x, int z) {
@Override public LocalChunk<char[]> getLocalChunk(int x, int z) {
return new CharLocalChunk_1_8_3(this, x, z);
}
@Override public void setBlocks(LocalChunk lc) {
CharLocalChunk_1_8_3 fs = (CharLocalChunk_1_8_3) lc;
Chunk chunk = getChunk(lc.getX(), lc.getZ());
chunk.load(true);
World world = chunk.getWorld();
ChunkWrapper wrapper = new ChunkWrapper(getWorld(), lc.getX(), lc.getZ());
if (!this.toUpdate.containsKey(wrapper)) {
this.toUpdate.put(wrapper, chunk);
}
try {
boolean flag = world.getEnvironment() == World.Environment.NORMAL;
// Sections
Method getHandle = chunk.getClass().getDeclaredMethod("getHandle");
Object c = getHandle.invoke(chunk);
Object w = this.methodGetWorld.of(c).call();
Class<?> clazz = c.getClass();
Field sections1 = clazz.getDeclaredField("sections");
sections1.setAccessible(true);
Field tileEntities = clazz.getDeclaredField("tileEntities");
Field entitySlices = clazz.getDeclaredField("entitySlices");
Object[] sections = (Object[]) sections1.get(c);
Map<?, ?> tiles = (Map<?, ?>) tileEntities.get(c);
Collection<?>[] entities = (Collection<?>[]) entitySlices.get(c);
Method getX = null;
Method getY = null;
Method getZ = null;
// Trim tiles
boolean removed = false;
Set<Map.Entry<?, ?>> entrySet = (Set<Map.Entry<?, ?>>) (Set<?>) tiles.entrySet();
Iterator<Map.Entry<?, ?>> iterator = entrySet.iterator();
while (iterator.hasNext()) {
Map.Entry<?, ?> tile = iterator.next();
Object pos = tile.getKey();
if (getX == null) {
Class<? extends Object> clazz2 = pos.getClass().getSuperclass();
getX = clazz2.getDeclaredMethod("getX");
getY = clazz2.getDeclaredMethod("getY");
getZ = clazz2.getDeclaredMethod("getZ");
}
int lx = (int) getX.invoke(pos) & 15;
int ly = (int) getY.invoke(pos);
int lz = (int) getZ.invoke(pos) & 15;
int j = MainUtil.CACHE_I[ly][lx][lz];
int k = MainUtil.CACHE_J[ly][lx][lz];
char[] array = fs.getIdArray(j);
if (array == null) {
continue;
}
if (array[k] != 0) {
removed = true;
iterator.remove();
}
}
if (removed) {
((Collection) this.tileEntityListTick.of(w).get()).clear();
}
// Trim entities
for (int i = 0; i < 16; i++) {
if ((entities[i] != null) && (fs.getCount(i) >= 4096)) {
entities[i].clear();
}
}
// Efficiently merge sections
for (int j = 0; j < sections.length; j++) {
if (fs.getCount(j) == 0) {
continue;
}
char[] newArray = fs.getIdArray(j);
if (newArray == null) {
continue;
}
Object section = sections[j];
if ((section == null) || (fs.getCount(j) >= 4096)) {
section = sections[j] = newChunkSection(j << 4, flag, newArray);
continue;
}
char[] currentArray = getIdArray(section);
boolean fill = true;
for (int k = 0; k < newArray.length; k++) {
char n = newArray[k];
switch (n) {
case 0:
fill = false;
continue;
case 1:
fill = false;
currentArray[k] = 0;
continue;
default:
currentArray[k] = n;
continue;
}
}
if (fill) {
fs.setCount(j, Short.MAX_VALUE);
}
}
// Clear
} catch (IllegalArgumentException | SecurityException | ReflectiveOperationException e) {
e.printStackTrace();
}
fixLighting(chunk, fs, true);
}
public Object newChunkSection(int i, boolean flag, char[] ids)
throws ReflectiveOperationException {
return this.classChunkSectionConstructor.create(i, flag, ids);
}
public char[] getIdArray(Object obj) {
return (char[]) this.methodGetIdArray.of(obj).call();
}
@Override public void fixChunkLighting(int x, int z) {
Object c = this.methodGetHandleChunk.of(getChunk(x, z)).call();
this.methodInitLighting.of(c).call();
}
public boolean fixLighting(Chunk chunk, CharLocalChunk_1_8_3 bc, boolean fixAll) {
try {
if (!chunk.isLoaded()) {
chunk.load(false);
} else {
chunk.unload(true, false);
chunk.load(false);
}
// Initialize lighting
Object c = this.methodGetHandleChunk.of(chunk).call();
if (fixAll && !(boolean) this.methodAreNeighborsLoaded.of(c).call(1)) {
World world = chunk.getWorld();
ChunkWrapper wrapper = new ChunkWrapper(getWorld(), chunk.getX(), chunk.getZ());
for (int x = wrapper.x - 1; x <= wrapper.x + 1; x++) {
for (int z = wrapper.z - 1; z <= wrapper.z + 1; z++) {
if (x != 0 && z != 0) {
Chunk other = world.getChunkAt(x, z);
while (!other.isLoaded()) {
other.load(true);
}
ChunkManager.manager.loadChunk(wrapper.world, new ChunkLoc(x, z), true);
}
}
}
/*
if (!(boolean) methodAreNeighborsLoaded.of(c).call(1)) {
return false;
}
*/
}
this.methodInitLighting.of(c).call();
if (bc.getTotalRelight() == 0 && !fixAll) {
return true;
}
Object[] sections = (Object[]) this.fieldSections.of(c).get();
Object w = this.fieldWorld.of(c).get();
int X = chunk.getX() << 4;
int Z = chunk.getZ() << 4;
ReflectionUtils.RefMethod.RefExecutor relight = this.methodX.of(w);
for (int j = 0; j < sections.length; j++) {
Object section = sections[j];
if (section == null) {
continue;
}
if ((bc.getRelight(j) == 0 && !fixAll) || bc.getCount(j) == 0 || (
bc.getCount(j) >= 4096 && bc.getAir(j) == 0)) {
continue;
}
char[] array = getIdArray(section);
int l = PseudoRandom.random.random(2);
for (int k = 0; k < array.length; k++) {
int i = array[k];
if (i < 16) {
continue;
}
short id = (short) (i >> 4);
switch (id) { // Lighting
default:
if (!fixAll) {
continue;
}
if ((k & 1) == l) {
l = 1 - l;
continue;
}
case 10:
case 11:
case 39:
case 40:
case 50:
case 51:
case 62:
case 74:
case 76:
case 89:
case 122:
case 124:
case 130:
case 138:
case 169:
int x = MainUtil.x_loc[j][k];
int y = MainUtil.y_loc[j][k];
int z = MainUtil.z_loc[j][k];
if (isSurrounded(sections, x, y, z)) {
continue;
}
Object pos = this.classBlockPositionConstructor.create(X + x, y, Z + z);
relight.call(pos);
}
}
}
return true;
} catch (Throwable e) {
e.printStackTrace();
}
return false;
}
public boolean isSurrounded(Object[] sections, int x, int y, int z) {
return isSolid(getId(sections, x, y + 1, z)) && isSolid(getId(sections, x + 1, y - 1, z))
&& isSolid(getId(sections, x - 1, y, z)) && isSolid(getId(sections, x, y, z + 1))
&& isSolid(getId(sections, x, y, z - 1));
}
public boolean isSolid(int i) {
return i != 0 && Material.getMaterial(i).isOccluding();
}
public int getId(Object[] sections, int x, int y, int z) {
if (x < 0 || x > 15 || z < 0 || z > 15) {
return 1;
}
if (y < 0 || y > 255) {
return 1;
}
int i = MainUtil.CACHE_I[y][x][z];
Object section = sections[i];
if (section == null) {
return 0;
}
char[] array = getIdArray(section);
int j = MainUtil.CACHE_J[y][x][z];
return array[j] >> 4;
}
public void update(Collection<Chunk> chunks) {
if (chunks.isEmpty()) {
return;
}
if (!MainUtil.canSendChunk) {
for (Chunk chunk : chunks) {
chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ());
chunk.unload(true, false);
chunk.load();
}
return;
}
try {
this.sendChunk.sendChunk(chunks);
} catch (Throwable e) {
e.printStackTrace();
MainUtil.canSendChunk = false;
}
}
@Override public void refreshChunk(int x, int z) {
update(Arrays.asList(Bukkit.getWorld(getWorld()).getChunkAt(x, z)));
}
public class CharLocalChunk_1_8_3 extends CharLocalChunk {
public short[] count;
public short[] air;
@ -104,8 +380,7 @@ public class BukkitLocalQueue_1_8_3 extends BukkitLocalQueue<char[]> {
this.relight = new short[16];
}
@Override
public void setBlock(int x, int y, int z, int id, int data) {
@Override public void setBlock(int x, int y, int z, int id, int data) {
int i = MainUtil.CACHE_I[y][x][z];
int j = MainUtil.CACHE_J[y][x][z];
char[] vs = this.blocks[i];
@ -252,286 +527,4 @@ public class BukkitLocalQueue_1_8_3 extends BukkitLocalQueue<char[]> {
return total;
}
}
@Override
public void setBlocks(LocalChunk lc) {
CharLocalChunk_1_8_3 fs = (CharLocalChunk_1_8_3) lc;
Chunk chunk = getChunk(lc.getX(), lc.getZ());
chunk.load(true);
World world = chunk.getWorld();
ChunkWrapper wrapper = new ChunkWrapper(getWorld(), lc.getX(), lc.getZ());
if (!this.toUpdate.containsKey(wrapper)) {
this.toUpdate.put(wrapper, chunk);
}
try {
boolean flag = world.getEnvironment() == World.Environment.NORMAL;
// Sections
Method getHandle = chunk.getClass().getDeclaredMethod("getHandle");
Object c = getHandle.invoke(chunk);
Object w = this.methodGetWorld.of(c).call();
Class<?> clazz = c.getClass();
Field sections1 = clazz.getDeclaredField("sections");
sections1.setAccessible(true);
Field tileEntities = clazz.getDeclaredField("tileEntities");
Field entitySlices = clazz.getDeclaredField("entitySlices");
Object[] sections = (Object[]) sections1.get(c);
Map<?, ?> tiles = (Map<?, ?>) tileEntities.get(c);
Collection<?>[] entities = (Collection<?>[]) entitySlices.get(c);
Method getX = null;
Method getY = null;
Method getZ = null;
// Trim tiles
boolean removed = false;
Set<Map.Entry<?, ?>> entrySet = (Set<Map.Entry<?, ?>>) (Set<?>) tiles.entrySet();
Iterator<Map.Entry<?, ?>> iterator = entrySet.iterator();
while (iterator.hasNext()) {
Map.Entry<?, ?> tile = iterator.next();
Object pos = tile.getKey();
if (getX == null) {
Class<? extends Object> clazz2 = pos.getClass().getSuperclass();
getX = clazz2.getDeclaredMethod("getX");
getY = clazz2.getDeclaredMethod("getY");
getZ = clazz2.getDeclaredMethod("getZ");
}
int lx = (int) getX.invoke(pos) & 15;
int ly = (int) getY.invoke(pos);
int lz = (int) getZ.invoke(pos) & 15;
int j = MainUtil.CACHE_I[ly][lx][lz];
int k = MainUtil.CACHE_J[ly][lx][lz];
char[] array = fs.getIdArray(j);
if (array == null) {
continue;
}
if (array[k] != 0) {
removed = true;
iterator.remove();
}
}
if (removed) {
((Collection) this.tileEntityListTick.of(w).get()).clear();
}
// Trim entities
for (int i = 0; i < 16; i++) {
if ((entities[i] != null) && (fs.getCount(i) >= 4096)) {
entities[i].clear();
}
}
// Efficiently merge sections
for (int j = 0; j < sections.length; j++) {
if (fs.getCount(j) == 0) {
continue;
}
char[] newArray = fs.getIdArray(j);
if (newArray == null) {
continue;
}
Object section = sections[j];
if ((section == null) || (fs.getCount(j) >= 4096)) {
section = sections[j] = newChunkSection(j << 4, flag, newArray);
continue;
}
char[] currentArray = getIdArray(section);
boolean fill = true;
for (int k = 0; k < newArray.length; k++) {
char n = newArray[k];
switch (n) {
case 0:
fill = false;
continue;
case 1:
fill = false;
currentArray[k] = 0;
continue;
default:
currentArray[k] = n;
continue;
}
}
if (fill) {
fs.setCount(j, Short.MAX_VALUE);
}
}
// Clear
} catch (IllegalArgumentException | SecurityException | ReflectiveOperationException e) {
e.printStackTrace();
}
fixLighting(chunk, fs, true);
}
public Object newChunkSection(int i, boolean flag, char[] ids) throws ReflectiveOperationException {
return this.classChunkSectionConstructor.create(i, flag, ids);
}
public char[] getIdArray(Object obj) {
return (char[]) this.methodGetIdArray.of(obj).call();
}
@Override
public void fixChunkLighting(int x, int z) {
Object c = this.methodGetHandleChunk.of(getChunk(x, z)).call();
this.methodInitLighting.of(c).call();
}
public boolean fixLighting(Chunk chunk, CharLocalChunk_1_8_3 bc, boolean fixAll) {
try {
if (!chunk.isLoaded()) {
chunk.load(false);
} else {
chunk.unload(true, false);
chunk.load(false);
}
// Initialize lighting
Object c = this.methodGetHandleChunk.of(chunk).call();
if (fixAll && !(boolean) this.methodAreNeighborsLoaded.of(c).call(1)) {
World world = chunk.getWorld();
ChunkWrapper wrapper = new ChunkWrapper(getWorld(), chunk.getX(), chunk.getZ());
for (int x = wrapper.x - 1; x <= wrapper.x + 1; x++) {
for (int z = wrapper.z - 1; z <= wrapper.z + 1; z++) {
if (x != 0 && z != 0) {
Chunk other = world.getChunkAt(x, z);
while (!other.isLoaded()) {
other.load(true);
}
ChunkManager.manager.loadChunk(wrapper.world, new ChunkLoc(x, z), true);
}
}
}
/*
if (!(boolean) methodAreNeighborsLoaded.of(c).call(1)) {
return false;
}
*/
}
this.methodInitLighting.of(c).call();
if (bc.getTotalRelight() == 0 && !fixAll) {
return true;
}
Object[] sections = (Object[]) this.fieldSections.of(c).get();
Object w = this.fieldWorld.of(c).get();
int X = chunk.getX() << 4;
int Z = chunk.getZ() << 4;
ReflectionUtils.RefMethod.RefExecutor relight = this.methodX.of(w);
for (int j = 0; j < sections.length; j++) {
Object section = sections[j];
if (section == null) {
continue;
}
if ((bc.getRelight(j) == 0 && !fixAll) || bc.getCount(j) == 0 || (bc.getCount(j) >= 4096 && bc.getAir(j) == 0)) {
continue;
}
char[] array = getIdArray(section);
int l = PseudoRandom.random.random(2);
for (int k = 0; k < array.length; k++) {
int i = array[k];
if (i < 16) {
continue;
}
short id = (short) (i >> 4);
switch (id) { // Lighting
default:
if (!fixAll) {
continue;
}
if ((k & 1) == l) {
l = 1 - l;
continue;
}
case 10:
case 11:
case 39:
case 40:
case 50:
case 51:
case 62:
case 74:
case 76:
case 89:
case 122:
case 124:
case 130:
case 138:
case 169:
int x = MainUtil.x_loc[j][k];
int y = MainUtil.y_loc[j][k];
int z = MainUtil.z_loc[j][k];
if (isSurrounded(sections, x, y, z)) {
continue;
}
Object pos = this.classBlockPositionConstructor.create(X + x, y, Z + z);
relight.call(pos);
}
}
}
return true;
} catch (Throwable e) {
e.printStackTrace();
}
return false;
}
public boolean isSurrounded(Object[] sections, int x, int y, int z) {
return isSolid(getId(sections, x, y + 1, z))
&& isSolid(getId(sections, x + 1, y - 1, z))
&& isSolid(getId(sections, x - 1, y, z))
&& isSolid(getId(sections, x, y, z + 1))
&& isSolid(getId(sections, x, y, z - 1));
}
public boolean isSolid(int i) {
return i != 0 && Material.getMaterial(i).isOccluding();
}
public int getId(Object[] sections, int x, int y, int z) {
if (x < 0 || x > 15 || z < 0 || z > 15) {
return 1;
}
if (y < 0 || y > 255) {
return 1;
}
int i = MainUtil.CACHE_I[y][x][z];
Object section = sections[i];
if (section == null) {
return 0;
}
char[] array = getIdArray(section);
int j = MainUtil.CACHE_J[y][x][z];
return array[j] >> 4;
}
public void update(Collection<Chunk> chunks) {
if (chunks.isEmpty()) {
return;
}
if (!MainUtil.canSendChunk) {
for (Chunk chunk : chunks) {
chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ());
chunk.unload(true, false);
chunk.load();
}
return;
}
try {
this.sendChunk.sendChunk(chunks);
} catch (Throwable e) {
e.printStackTrace();
MainUtil.canSendChunk = false;
}
}
@Override
public void refreshChunk(int x, int z) {
update(Arrays.asList(Bukkit.getWorld(getWorld()).getChunkAt(x, z)));
}
}

View File

@ -5,17 +5,13 @@ import com.intellectualcrafters.plot.object.PseudoRandom;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.ReflectionUtils;
import com.intellectualcrafters.plot.util.block.BasicLocalBlockQueue;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.bukkit.Chunk;
import org.bukkit.Material;
import org.bukkit.World;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
@ -40,14 +36,16 @@ public class BukkitLocalQueue_1_9 extends BukkitLocalQueue<char[]> {
private final ReflectionUtils.RefField tileEntityListTick;
public BukkitLocalQueue_1_9(String world) throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException {
public BukkitLocalQueue_1_9(String world)
throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException {
super(world);
ReflectionUtils.RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle");
ReflectionUtils.RefClass classChunk = getRefClass("{nms}.Chunk");
this.methodInitLighting = classChunk.getMethod("initLighting");
ReflectionUtils.RefClass classBlockPosition = getRefClass("{nms}.BlockPosition");
this.classBlockPositionConstructor = classBlockPosition.getConstructor(int.class, int.class, int.class);
this.classBlockPositionConstructor =
classBlockPosition.getConstructor(int.class, int.class, int.class);
ReflectionUtils.RefClass classWorld = getRefClass("{nms}.World");
this.tileEntityListTick = classWorld.getField("tileEntityListTick");
this.methodGetWorld = classChunk.getMethod("getWorld");
@ -56,23 +54,284 @@ public class BukkitLocalQueue_1_9 extends BukkitLocalQueue<char[]> {
this.fieldWorld = classChunk.getField("world");
ReflectionUtils.RefClass classBlock = getRefClass("{nms}.Block");
ReflectionUtils.RefClass classIBlockData = getRefClass("{nms}.IBlockData");
this.methodGetCombinedId = classBlock.getMethod("getCombinedId", classIBlockData.getRealClass());
this.methodGetCombinedId =
classBlock.getMethod("getCombinedId", classIBlockData.getRealClass());
this.methodGetByCombinedId = classBlock.getMethod("getByCombinedId", int.class);
ReflectionUtils.RefClass classChunkSection = getRefClass("{nms}.ChunkSection");
this.methodGetBlocks = classChunkSection.getMethod("getBlocks");
this.methodGetType = classChunkSection.getMethod("getType", int.class, int.class, int.class);
this.methodSetType = classChunkSection.getMethod("setType", int.class, int.class, int.class, classIBlockData.getRealClass());
this.methodGetType =
classChunkSection.getMethod("getType", int.class, int.class, int.class);
this.methodSetType = classChunkSection
.getMethod("setType", int.class, int.class, int.class, classIBlockData.getRealClass());
this.methodAreNeighborsLoaded = classChunk.getMethod("areNeighborsLoaded", int.class);
this.classChunkSectionConstructor = classChunkSection.getConstructor(int.class, boolean.class, char[].class);
this.classChunkSectionConstructor =
classChunkSection.getConstructor(int.class, boolean.class, char[].class);
this.air = this.methodGetByCombinedId.call(0);
MainUtil.initCache();
}
@Override
public LocalChunk<char[]> getLocalChunk(int x, int z) {
@Override public LocalChunk<char[]> getLocalChunk(int x, int z) {
return new CharLocalChunk_1_8_3(this, x, z);
}
@Override public void setBlocks(LocalChunk lc) {
CharLocalChunk_1_8_3 fs = (CharLocalChunk_1_8_3) lc;
Chunk chunk = getChunk(lc.getX(), lc.getZ());
chunk.load(true);
World world = chunk.getWorld();
try {
boolean flag = world.getEnvironment() == World.Environment.NORMAL;
// Sections
Method getHandle = chunk.getClass().getDeclaredMethod("getHandle");
Object c = getHandle.invoke(chunk);
Object w = this.methodGetWorld.of(c).call();
Class<? extends Object> clazz = c.getClass();
Field sf = clazz.getDeclaredField("sections");
sf.setAccessible(true);
Field tf = clazz.getDeclaredField("tileEntities");
Field entitySlices = clazz.getDeclaredField("entitySlices");
Object[] sections = (Object[]) sf.get(c);
Map<?, ?> tiles = (Map<?, ?>) tf.get(c);
Collection<?>[] entities = (Collection<?>[]) entitySlices.get(c);
Method xm = null;
Method ym = null;
Method zm = null;
// Trim tiles
Collection tickList = ((Collection) this.tileEntityListTick.of(w).get());
Set<Map.Entry<?, ?>> entrySet = (Set<Map.Entry<?, ?>>) (Set<?>) tiles.entrySet();
Iterator<Map.Entry<?, ?>> iterator = entrySet.iterator();
while (iterator.hasNext()) {
Map.Entry<?, ?> tile = iterator.next();
Object pos = tile.getKey();
if (xm == null) {
Class<?> clazz2 = pos.getClass().getSuperclass();
xm = clazz2.getDeclaredMethod("getX");
ym = clazz2.getDeclaredMethod("getY");
zm = clazz2.getDeclaredMethod("getZ");
}
int lx = (int) xm.invoke(pos) & 15;
int ly = (int) ym.invoke(pos);
int lz = (int) zm.invoke(pos) & 15;
int j = MainUtil.CACHE_I[ly][lx][lz];
int k = MainUtil.CACHE_J[ly][lx][lz];
char[] array = fs.getIdArray(j);
if (array == null) {
continue;
}
if (array[k] != 0) {
tickList.remove(tile.getValue());
iterator.remove();
}
}
// Trim entities
for (int i = 0; i < 16; i++) {
if (entities[i] != null && fs.getCount(i) >= 4096) {
entities[i].clear();
}
}
// Efficiently merge sections
for (int j = 0; j < sections.length; j++) {
if (fs.getCount(j) == 0) {
continue;
}
char[] newArray = fs.getIdArray(j);
if (newArray == null) {
continue;
}
Object section = sections[j];
if (section == null || fs.getCount(j) >= 4096) {
section = sections[j] = newChunkSection(j << 4, flag, fs.getIdArray(j));
continue;
}
Object currentArray = getBlocks(section);
ReflectionUtils.RefMethod.RefExecutor setType = this.methodSetType.of(section);
boolean fill = true;
for (int k = 0; k < newArray.length; k++) {
char n = newArray[k];
switch (n) {
case 0:
fill = false;
continue;
case 1: {
fill = false;
int x = MainUtil.x_loc[j][k];
int y = MainUtil.y_loc[j][k];
int z = MainUtil.z_loc[j][k];
setType.call(x, y & 15, z, this.air);
continue;
}
default:
int x = MainUtil.x_loc[j][k];
int y = MainUtil.y_loc[j][k];
int z = MainUtil.z_loc[j][k];
int id = n >> 4;
int data = n & 15;
Object iBlock =
this.methodGetByCombinedId.call((int) (id & 0xFFF) + (data << 12));
setType.call(x, y & 15, z, iBlock);
}
}
if (fill) {
fs.setCount(j, Short.MAX_VALUE);
}
}
// Clear
} catch (IllegalArgumentException | SecurityException | ReflectiveOperationException e) {
e.printStackTrace();
}
fixLighting(chunk, fs, true);
refreshChunk(fs.getX(), fs.getZ());
}
public Object newChunkSection(int i, boolean flag, char[] ids)
throws ReflectiveOperationException {
return this.classChunkSectionConstructor.create(i, flag, ids);
}
public Object getBlocks(Object obj) {
return this.methodGetBlocks.of(obj).call();
}
@Override public void fixChunkLighting(int x, int z) {
Object c = this.methodGetHandleChunk.of(getChunk(x, z)).call();
this.methodInitLighting.of(c).call();
}
public boolean fixLighting(Chunk chunk, CharLocalChunk_1_8_3 bc, boolean fixAll) {
try {
if (!chunk.isLoaded()) {
chunk.load(false);
} else {
chunk.unload(true, false);
chunk.load(false);
}
// Initialize lighting
Object c = this.methodGetHandleChunk.of(chunk).call();
ChunkWrapper wrapper = new ChunkWrapper(getWorld(), bc.getX(), bc.getZ());
Object[] result = disableLighting(chunk);
enableLighting(result);
this.methodInitLighting.of(c).call();
if (bc.getTotalRelight() != 0 || fixAll) {
Object[] sections = (Object[]) this.fieldSections.of(c).get();
Object w = this.fieldWorld.of(c).get();
int X = chunk.getX() << 4;
int Z = chunk.getZ() << 4;
ReflectionUtils.RefMethod.RefExecutor relight = this.methodW.of(w);
for (int j = 0; j < sections.length; j++) {
Object section = sections[j];
if (section == null) {
continue;
}
if (bc.getRelight(j) == 0 && !fixAll || bc.getCount(j) == 0
|| bc.getCount(j) >= 4096 && bc.getAir(j) == 0) {
continue;
}
char[] array = bc.getIdArray(j);
if (array != null) {
int l = PseudoRandom.random.random(2);
for (int k = 0; k < array.length; k++) {
int i = array[k];
if (i < 16) {
continue;
}
short id = (short) (i >> 4);
switch (id) { // Lighting
default:
if (!fixAll) {
continue;
}
if ((k & 1) == l) {
l = 1 - l;
continue;
}
case 10:
case 11:
case 39:
case 40:
case 50:
case 51:
case 62:
case 74:
case 76:
case 89:
case 122:
case 124:
case 130:
case 138:
case 169:
int x = MainUtil.x_loc[j][k];
int y = MainUtil.y_loc[j][k];
int z = MainUtil.z_loc[j][k];
if (isSurrounded(bc.blocks, x, y, z)) {
continue;
}
Object pos =
this.classBlockPositionConstructor.create(X + x, y, Z + z);
relight.call(pos);
}
}
}
}
}
resetLighting(result);
return true;
} catch (Throwable e) {
e.printStackTrace();
}
return false;
}
@Override public void refreshChunk(int x, int z) {
getBukkitWorld().refreshChunk(x, z);
}
public boolean isSurrounded(char[][] sections, int x, int y, int z) {
return isSolid(getId(sections, x, y + 1, z)) && isSolid(getId(sections, x + 1, y - 1, z))
&& isSolid(getId(sections, x - 1, y, z)) && isSolid(getId(sections, x, y, z + 1))
&& isSolid(getId(sections, x, y, z - 1));
}
public boolean isSolid(int i) {
if (i != 0) {
Material material = Material.getMaterial(i);
return material != null && Material.getMaterial(i).isOccluding();
}
return false;
}
public int getId(char[] section, int x, int y, int z) {
if (section == null) {
return 0;
}
int j = MainUtil.CACHE_J[y][x][z];
return section[j] >> 4;
}
public int getId(char[][] sections, int x, int y, int z) {
if (x < 0 || x > 15 || z < 0 || z > 15) {
return 1;
}
if (y < 0 || y > 255) {
return 1;
}
int i = MainUtil.CACHE_I[y][x][z];
char[] section = sections[i];
if (section == null) {
return 0;
}
return getId(section, x, y, z);
}
public class CharLocalChunk_1_8_3 extends CharLocalChunk {
public short[] count;
public short[] air;
@ -85,8 +344,7 @@ public class BukkitLocalQueue_1_9 extends BukkitLocalQueue<char[]> {
this.relight = new short[16];
}
@Override
public void setBlock(int x, int y, int z, int id, int data) {
@Override public void setBlock(int x, int y, int z, int id, int data) {
int i = MainUtil.CACHE_I[y][x][z];
int j = MainUtil.CACHE_J[y][x][z];
char[] vs = this.blocks[i];
@ -233,262 +491,4 @@ public class BukkitLocalQueue_1_9 extends BukkitLocalQueue<char[]> {
return total;
}
}
@Override
public void setBlocks(LocalChunk lc) {
CharLocalChunk_1_8_3 fs = (CharLocalChunk_1_8_3) lc;
Chunk chunk = getChunk(lc.getX(), lc.getZ());
chunk.load(true);
World world = chunk.getWorld();
try {
boolean flag = world.getEnvironment() == World.Environment.NORMAL;
// Sections
Method getHandle = chunk.getClass().getDeclaredMethod("getHandle");
Object c = getHandle.invoke(chunk);
Object w = this.methodGetWorld.of(c).call();
Class<? extends Object> clazz = c.getClass();
Field sf = clazz.getDeclaredField("sections");
sf.setAccessible(true);
Field tf = clazz.getDeclaredField("tileEntities");
Field entitySlices = clazz.getDeclaredField("entitySlices");
Object[] sections = (Object[]) sf.get(c);
Map<?, ?> tiles = (Map<?, ?>) tf.get(c);
Collection<?>[] entities = (Collection<?>[]) entitySlices.get(c);
Method xm = null;
Method ym = null;
Method zm = null;
// Trim tiles
Collection tickList = ((Collection) this.tileEntityListTick.of(w).get());
Set<Map.Entry<?, ?>> entrySet = (Set<Map.Entry<?, ?>>) (Set<?>) tiles.entrySet();
Iterator<Map.Entry<?, ?>> iterator = entrySet.iterator();
while (iterator.hasNext()) {
Map.Entry<?, ?> tile = iterator.next();
Object pos = tile.getKey();
if (xm == null) {
Class<?> clazz2 = pos.getClass().getSuperclass();
xm = clazz2.getDeclaredMethod("getX");
ym = clazz2.getDeclaredMethod("getY");
zm = clazz2.getDeclaredMethod("getZ");
}
int lx = (int) xm.invoke(pos) & 15;
int ly = (int) ym.invoke(pos);
int lz = (int) zm.invoke(pos) & 15;
int j = MainUtil.CACHE_I[ly][lx][lz];
int k = MainUtil.CACHE_J[ly][lx][lz];
char[] array = fs.getIdArray(j);
if (array == null) {
continue;
}
if (array[k] != 0) {
tickList.remove(tile.getValue());
iterator.remove();
}
}
// Trim entities
for (int i = 0; i < 16; i++) {
if (entities[i] != null && fs.getCount(i) >= 4096) {
entities[i].clear();
}
}
// Efficiently merge sections
for (int j = 0; j < sections.length; j++) {
if (fs.getCount(j) == 0) {
continue;
}
char[] newArray = fs.getIdArray(j);
if (newArray == null) {
continue;
}
Object section = sections[j];
if (section == null || fs.getCount(j) >= 4096) {
section = sections[j] = newChunkSection(j << 4, flag, fs.getIdArray(j));
continue;
}
Object currentArray = getBlocks(section);
ReflectionUtils.RefMethod.RefExecutor setType = this.methodSetType.of(section);
boolean fill = true;
for (int k = 0; k < newArray.length; k++) {
char n = newArray[k];
switch (n) {
case 0:
fill = false;
continue;
case 1: {
fill = false;
int x = MainUtil.x_loc[j][k];
int y = MainUtil.y_loc[j][k];
int z = MainUtil.z_loc[j][k];
setType.call(x, y & 15, z, this.air);
continue;
}
default:
int x = MainUtil.x_loc[j][k];
int y = MainUtil.y_loc[j][k];
int z = MainUtil.z_loc[j][k];
int id = n >> 4;
int data = n & 15;
Object iBlock = this.methodGetByCombinedId.call((int) (id & 0xFFF) + (data << 12));
setType.call(x, y & 15, z, iBlock);
}
}
if (fill) {
fs.setCount(j, Short.MAX_VALUE);
}
}
// Clear
} catch (IllegalArgumentException | SecurityException | ReflectiveOperationException e) {
e.printStackTrace();
}
fixLighting(chunk, fs, true);
refreshChunk(fs.getX(), fs.getZ());
}
public Object newChunkSection(int i, boolean flag, char[] ids) throws ReflectiveOperationException {
return this.classChunkSectionConstructor.create(i, flag, ids);
}
public Object getBlocks(Object obj) {
return this.methodGetBlocks.of(obj).call();
}
@Override
public void fixChunkLighting(int x, int z) {
Object c = this.methodGetHandleChunk.of(getChunk(x, z)).call();
this.methodInitLighting.of(c).call();
}
public boolean fixLighting(Chunk chunk, CharLocalChunk_1_8_3 bc, boolean fixAll) {
try {
if (!chunk.isLoaded()) {
chunk.load(false);
} else {
chunk.unload(true, false);
chunk.load(false);
}
// Initialize lighting
Object c = this.methodGetHandleChunk.of(chunk).call();
ChunkWrapper wrapper = new ChunkWrapper(getWorld(), bc.getX(), bc.getZ());
Object[] result = disableLighting(chunk);
enableLighting(result);
this.methodInitLighting.of(c).call();
if (bc.getTotalRelight() != 0 || fixAll) {
Object[] sections = (Object[]) this.fieldSections.of(c).get();
Object w = this.fieldWorld.of(c).get();
int X = chunk.getX() << 4;
int Z = chunk.getZ() << 4;
ReflectionUtils.RefMethod.RefExecutor relight = this.methodW.of(w);
for (int j = 0; j < sections.length; j++) {
Object section = sections[j];
if (section == null) {
continue;
}
if (bc.getRelight(j) == 0 && !fixAll || bc.getCount(j) == 0 || bc.getCount(j) >= 4096 && bc.getAir(j) == 0) {
continue;
}
char[] array = bc.getIdArray(j);
if (array != null) {
int l = PseudoRandom.random.random(2);
for (int k = 0; k < array.length; k++) {
int i = array[k];
if (i < 16) {
continue;
}
short id = (short) (i >> 4);
switch (id) { // Lighting
default:
if (!fixAll) {
continue;
}
if ((k & 1) == l) {
l = 1 - l;
continue;
}
case 10:
case 11:
case 39:
case 40:
case 50:
case 51:
case 62:
case 74:
case 76:
case 89:
case 122:
case 124:
case 130:
case 138:
case 169:
int x = MainUtil.x_loc[j][k];
int y = MainUtil.y_loc[j][k];
int z = MainUtil.z_loc[j][k];
if (isSurrounded(bc.blocks, x, y, z)) {
continue;
}
Object pos = this.classBlockPositionConstructor.create(X + x, y, Z + z);
relight.call(pos);
}
}
}
}
}
resetLighting(result);
return true;
} catch (Throwable e) {
e.printStackTrace();
}
return false;
}
@Override
public void refreshChunk(int x, int z) {
getBukkitWorld().refreshChunk(x, z);
}
public boolean isSurrounded(char[][] sections, int x, int y, int z) {
return isSolid(getId(sections, x, y + 1, z))
&& isSolid(getId(sections, x + 1, y - 1, z))
&& isSolid(getId(sections, x - 1, y, z))
&& isSolid(getId(sections, x, y, z + 1))
&& isSolid(getId(sections, x, y, z - 1));
}
public boolean isSolid(int i) {
if (i != 0) {
Material material = Material.getMaterial(i);
return material != null && Material.getMaterial(i).isOccluding();
}
return false;
}
public int getId(char[] section, int x, int y, int z) {
if (section == null) {
return 0;
}
int j = MainUtil.CACHE_J[y][x][z];
return section[j] >> 4;
}
public int getId(char[][] sections, int x, int y, int z) {
if (x < 0 || x > 15 || z < 0 || z > 15) {
return 1;
}
if (y < 0 || y > 255) {
return 1;
}
int i = MainUtil.CACHE_I[y][x][z];
char[] section = sections[i];
if (section == null) {
return 0;
}
return getId(section, x, y, z);
}
}

View File

@ -6,7 +6,6 @@ import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.block.ScopedLocalBlockQueue;
import com.plotsquared.bukkit.util.BukkitUtil;
import java.util.Arrays;
import org.bukkit.Chunk;
import org.bukkit.Material;
import org.bukkit.World;
@ -15,6 +14,8 @@ import org.bukkit.generator.ChunkGenerator.BiomeGrid;
import org.bukkit.generator.ChunkGenerator.ChunkData;
import org.bukkit.material.MaterialData;
import java.util.Arrays;
public class GenChunk extends ScopedLocalBlockQueue {
public final Biome[] biomes;
@ -37,13 +38,6 @@ public class GenChunk extends ScopedLocalBlockQueue {
this.chunk = chunk;
}
public void setChunk(ChunkWrapper wrap) {
chunk = null;
world = wrap.world;
cx = wrap.x;
cz = wrap.z;
}
public Chunk getChunk() {
if (chunk == null) {
World worldObj = BukkitUtil.getWorld(world);
@ -54,6 +48,13 @@ public class GenChunk extends ScopedLocalBlockQueue {
return chunk;
}
public void setChunk(ChunkWrapper wrap) {
chunk = null;
world = wrap.world;
cx = wrap.x;
cz = wrap.z;
}
public ChunkWrapper getChunkWrapper() {
if (chunk == null) {
return new ChunkWrapper(world, cx, cz);
@ -61,8 +62,7 @@ public class GenChunk extends ScopedLocalBlockQueue {
return new ChunkWrapper(chunk.getWorld().getName(), chunk.getX(), chunk.getZ());
}
@Override
public void fillBiome(String biomeName) {
@Override public void fillBiome(String biomeName) {
if (grid == null) {
return;
}
@ -74,9 +74,9 @@ public class GenChunk extends ScopedLocalBlockQueue {
}
}
@Override
public void setCuboid(Location pos1, Location pos2, PlotBlock block) {
if (block.data == 0 && result != null && pos1.getX() == 0 && pos1.getZ() == 0 && pos2.getX() == 15 && pos2.getZ() == 15) {
@Override public void setCuboid(Location pos1, Location pos2, PlotBlock block) {
if (block.data == 0 && result != null && pos1.getX() == 0 && pos1.getZ() == 0
&& pos2.getX() == 15 && pos2.getZ() == 15) {
for (int y = pos1.getY(); y <= pos2.getY(); y++) {
int layer = y >> 4;
short[] data = result[layer];
@ -92,8 +92,7 @@ public class GenChunk extends ScopedLocalBlockQueue {
}
}
@Override
public boolean setBiome(int x, int z, String biome) {
@Override public boolean setBiome(int x, int z, String biome) {
return setBiome(x, z, Biome.valueOf(biome.toUpperCase()));
}
@ -113,8 +112,7 @@ public class GenChunk extends ScopedLocalBlockQueue {
return false;
}
@Override
public boolean setBlock(int x, int y, int z, int id, int data) {
@Override public boolean setBlock(int x, int y, int z, int id, int data) {
if (this.result == null) {
this.cd.setBlock(x, y, z, new MaterialData(Material.getMaterial(id), (byte) data));
return true;
@ -136,8 +134,7 @@ public class GenChunk extends ScopedLocalBlockQueue {
return true;
}
@Override
public PlotBlock getBlock(int x, int y, int z) {
@Override public PlotBlock getBlock(int x, int y, int z) {
int i = MainUtil.CACHE_I[y][x][z];
if (result == null) {
MaterialData md = cd.getTypeAndData(x, y, z);
@ -167,23 +164,21 @@ public class GenChunk extends ScopedLocalBlockQueue {
return chunk == null ? cz : chunk.getZ();
}
@Override
public String getWorld() {
@Override public String getWorld() {
return chunk == null ? world : chunk.getWorld().getName();
}
@Override
public Location getMax() {
@Override public Location getMax() {
return new Location(getWorld(), 15 + (getX() << 4), 255, 15 + (getZ() << 4));
}
@Override
public Location getMin() {
@Override public Location getMin() {
return new Location(getWorld(), getX() << 4, 0, getZ() << 4);
}
public GenChunk clone() {
GenChunk toReturn = new GenChunk(chunk, new ChunkWrapper(getWorld(), chunk.getX(), chunk.getZ()));
GenChunk toReturn =
new GenChunk(chunk, new ChunkWrapper(getWorld(), chunk.getX(), chunk.getZ()));
if (this.result != null) {
for (int i = 0; i < this.result.length; i++) {
short[] matrix = this.result[i];

View File

@ -5,8 +5,7 @@ import java.io.FilenameFilter;
public class DatFileFilter implements FilenameFilter {
@Override
public boolean accept(File dir, String name) {
@Override public boolean accept(File dir, String name) {
return name.endsWith(".dat");
}
}

View File

@ -12,28 +12,23 @@ import java.util.UUID;
public class DefaultUUIDWrapper extends UUIDWrapper {
@Override
public UUID getUUID(PlotPlayer player) {
@Override public UUID getUUID(PlotPlayer player) {
return ((BukkitPlayer) player).player.getUniqueId();
}
@Override
public UUID getUUID(OfflinePlotPlayer player) {
@Override public UUID getUUID(OfflinePlotPlayer player) {
return player.getUUID();
}
@Override
public OfflinePlotPlayer getOfflinePlayer(UUID uuid) {
@Override public OfflinePlotPlayer getOfflinePlayer(UUID uuid) {
return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(uuid));
}
@Override
public UUID getUUID(String name) {
@Override public UUID getUUID(String name) {
return Bukkit.getOfflinePlayer(name).getUniqueId();
}
@Override
public OfflinePlotPlayer[] getOfflinePlayers() {
@Override public OfflinePlotPlayer[] getOfflinePlayers() {
OfflinePlayer[] ops = Bukkit.getOfflinePlayers();
BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length];
for (int i = 0; i < ops.length; i++) {
@ -42,8 +37,7 @@ public class DefaultUUIDWrapper extends UUIDWrapper {
return toReturn;
}
@Override
public OfflinePlotPlayer getOfflinePlayer(String name) {
@Override public OfflinePlotPlayer getOfflinePlayer(String name) {
return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(name));
}
}

View File

@ -15,6 +15,9 @@ import com.intellectualcrafters.plot.util.UUIDHandlerImplementation;
import com.intellectualcrafters.plot.util.expiry.ExpireManager;
import com.intellectualcrafters.plot.uuid.UUIDWrapper;
import com.plotsquared.bukkit.util.NbtFactory;
import org.bukkit.Bukkit;
import org.bukkit.World;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
@ -24,9 +27,6 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.entity.Player;
public class FileUUIDHandler extends UUIDHandlerImplementation {
@ -34,8 +34,7 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
super(wrapper);
}
@Override
public boolean startCaching(Runnable whenDone) {
@Override public boolean startCaching(Runnable whenDone) {
return super.startCaching(whenDone) && cache(whenDone);
}
@ -49,13 +48,13 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
world = worlds.get(0).getName();
}
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
@Override public void run() {
PS.debug(C.PREFIX + "&6Starting player data caching for: " + world);
File uuidFile = new File(PS.get().IMP.getDirectory(), "uuids.txt");
if (uuidFile.exists()) {
try {
List<String> lines = Files.readAllLines(uuidFile.toPath(), StandardCharsets.UTF_8);
List<String> lines =
Files.readAllLines(uuidFile.toPath(), StandardCharsets.UTF_8);
for (String line : lines) {
try {
line = line.trim();
@ -65,7 +64,8 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", "");
String[] split = line.split("\\|");
String name = split[0];
if (name.isEmpty() || (name.length() > 16) || !StringMan.isAlphanumericUnd(name)) {
if (name.isEmpty() || (name.length() > 16) || !StringMan
.isAlphanumericUnd(name)) {
continue;
}
UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name);
@ -81,11 +81,13 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
e.printStackTrace();
}
}
HashBiMap<StringWrapper, UUID> toAdd = HashBiMap.create(new HashMap<StringWrapper, UUID>());
HashBiMap<StringWrapper, UUID> toAdd =
HashBiMap.create(new HashMap<StringWrapper, UUID>());
if (Settings.UUID.NATIVE_UUID_PROVIDER) {
HashSet<UUID> all = UUIDHandler.getAllUUIDS();
PS.debug("&aFast mode UUID caching enabled!");
File playerDataFolder = new File(container, world + File.separator + "playerdata");
File playerDataFolder =
new File(container, world + File.separator + "playerdata");
String[] dat = playerDataFolder.list(new DatFileFilter());
boolean check = all.isEmpty();
if (dat != null) {
@ -95,11 +97,15 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
UUID uuid = UUID.fromString(s);
if (check || all.remove(uuid)) {
File file = new File(playerDataFolder, current);
NbtFactory.NbtCompound compound = NbtFactory.fromStream(new FileInputStream(file), NbtFactory.StreamOptions.GZIP_COMPRESSION);
NbtFactory.NbtCompound compound = NbtFactory
.fromStream(new FileInputStream(file),
NbtFactory.StreamOptions.GZIP_COMPRESSION);
if (!compound.containsKey("bukkit")) {
PS.debug("ERROR: Player data (" + uuid.toString() + ".dat) does not contain the the key \"bukkit\"");
PS.debug("ERROR: Player data (" + uuid.toString()
+ ".dat) does not contain the the key \"bukkit\"");
} else {
NbtFactory.NbtCompound bukkit = (NbtFactory.NbtCompound) compound.get("bukkit");
NbtFactory.NbtCompound bukkit =
(NbtFactory.NbtCompound) compound.get("bukkit");
String name = (String) bukkit.get("lastKnownName");
long last = (long) bukkit.get("lastPlayed");
long first = (long) bukkit.get("firstPlayed");
@ -123,7 +129,8 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
}
return;
} else {
PS.debug("Failed to cache: " + all.size() + " uuids - slowly processing all files");
PS.debug("Failed to cache: " + all.size()
+ " uuids - slowly processing all files");
}
}
HashSet<String> worlds = Sets.newHashSet(world, "world");
@ -132,7 +139,8 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
File playerDataFolder = null;
for (String worldName : worlds) {
// Getting UUIDs
playerDataFolder = new File(container, worldName + File.separator + "playerdata");
playerDataFolder =
new File(container, worldName + File.separator + "playerdata");
String[] dat = playerDataFolder.list(new DatFileFilter());
if ((dat != null) && (dat.length != 0)) {
for (String current : dat) {
@ -158,22 +166,28 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
}
for (UUID uuid : uuids) {
try {
File file = new File(playerDataFolder + File.separator + uuid.toString() + ".dat");
File file =
new File(playerDataFolder + File.separator + uuid.toString() + ".dat");
if (!file.exists()) {
continue;
}
NbtFactory.NbtCompound compound = NbtFactory.fromStream(new FileInputStream(file), NbtFactory.StreamOptions.GZIP_COMPRESSION);
NbtFactory.NbtCompound compound = NbtFactory
.fromStream(new FileInputStream(file),
NbtFactory.StreamOptions.GZIP_COMPRESSION);
if (!compound.containsKey("bukkit")) {
PS.debug("ERROR: Player data (" + uuid.toString() + ".dat) does not contain the the key \"bukkit\"");
PS.debug("ERROR: Player data (" + uuid.toString()
+ ".dat) does not contain the the key \"bukkit\"");
} else {
NbtFactory.NbtCompound bukkit = (NbtFactory.NbtCompound) compound.get("bukkit");
NbtFactory.NbtCompound bukkit =
(NbtFactory.NbtCompound) compound.get("bukkit");
String name = (String) bukkit.get("lastKnownName");
StringWrapper wrap = new StringWrapper(name);
if (!toAdd.containsKey(wrap)) {
long last = (long) bukkit.get("lastPlayed");
long first = (long) bukkit.get("firstPlayed");
if (Settings.UUID.OFFLINE) {
if (Settings.UUID.FORCE_LOWERCASE && !name.toLowerCase().equals(name)) {
if (Settings.UUID.FORCE_LOWERCASE && !name.toLowerCase()
.equals(name)) {
uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name);
} else {
long most = (long) compound.get("UUIDMost");
@ -199,7 +213,8 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
}
if (getUUIDMap().isEmpty()) {
for (OfflinePlotPlayer op : FileUUIDHandler.this.uuidWrapper.getOfflinePlayers()) {
for (OfflinePlotPlayer op : FileUUIDHandler.this.uuidWrapper
.getOfflinePlayers()) {
long last = op.getLastPlayed();
if (last != 0) {
String name = op.getName();
@ -223,11 +238,9 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
return true;
}
@Override
public void fetchUUID(final String name, final RunnableVal<UUID> ifFetch) {
@Override public void fetchUUID(final String name, final RunnableVal<UUID> ifFetch) {
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
@Override public void run() {
ifFetch.value = FileUUIDHandler.this.uuidWrapper.getUUID(name);
TaskManager.runTask(ifFetch);
}

View File

@ -9,24 +9,24 @@ import java.util.UUID;
public class LowerOfflineUUIDWrapper extends OfflineUUIDWrapper {
@Override
public UUID getUUID(PlotPlayer player) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8));
@Override public UUID getUUID(PlotPlayer player) {
return UUID.nameUUIDFromBytes(
("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8));
}
@Override
public UUID getUUID(OfflinePlotPlayer player) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8));
@Override public UUID getUUID(OfflinePlotPlayer player) {
return UUID.nameUUIDFromBytes(
("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8));
}
@Override
public UUID getUUID(OfflinePlayer player) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8));
@Override public UUID getUUID(OfflinePlayer player) {
return UUID.nameUUIDFromBytes(
("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8));
}
@Override
public UUID getUUID(String name) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + name.toLowerCase()).getBytes(Charsets.UTF_8));
@Override public UUID getUUID(String name) {
return UUID
.nameUUIDFromBytes(("OfflinePlayer:" + name.toLowerCase()).getBytes(Charsets.UTF_8));
}
}

View File

@ -32,22 +32,22 @@ public class OfflineUUIDWrapper extends UUIDWrapper {
}
}
@Override
public UUID getUUID(PlotPlayer player) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8));
@Override public UUID getUUID(PlotPlayer player) {
return UUID
.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8));
}
@Override
public UUID getUUID(OfflinePlotPlayer player) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8));
@Override public UUID getUUID(OfflinePlotPlayer player) {
return UUID
.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8));
}
public UUID getUUID(OfflinePlayer player) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8));
return UUID
.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8));
}
@Override
public OfflinePlotPlayer getOfflinePlayer(UUID uuid) {
@Override public OfflinePlotPlayer getOfflinePlayer(UUID uuid) {
BiMap<UUID, StringWrapper> map = UUIDHandler.getUuidMap().inverse();
String name = null;
if (map.containsKey(uuid)) {
@ -77,7 +77,8 @@ public class OfflineUUIDWrapper extends UUIDWrapper {
if (players instanceof Player[]) {
return (Player[]) players;
} else {
@SuppressWarnings("unchecked") Collection<? extends Player> p = (Collection<? extends Player>) players;
@SuppressWarnings("unchecked") Collection<? extends Player> p =
(Collection<? extends Player>) players;
return p.toArray(new Player[p.size()]);
}
} catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException ignored) {
@ -88,13 +89,11 @@ public class OfflineUUIDWrapper extends UUIDWrapper {
}
}
@Override
public UUID getUUID(String name) {
@Override public UUID getUUID(String name) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8));
}
@Override
public OfflinePlotPlayer[] getOfflinePlayers() {
@Override public OfflinePlotPlayer[] getOfflinePlayers() {
OfflinePlayer[] ops = Bukkit.getOfflinePlayers();
BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length];
for (int i = 0; i < ops.length; i++) {
@ -103,8 +102,7 @@ public class OfflineUUIDWrapper extends UUIDWrapper {
return toReturn;
}
@Override
public OfflinePlotPlayer getOfflinePlayer(String name) {
@Override public OfflinePlotPlayer getOfflinePlayer(String name) {
return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(name));
}
}

View File

@ -12,6 +12,11 @@ import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.util.UUIDHandlerImplementation;
import com.intellectualcrafters.plot.uuid.UUIDWrapper;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
@ -26,15 +31,12 @@ import java.util.ArrayDeque;
import java.util.Collections;
import java.util.HashMap;
import java.util.UUID;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class SQLUUIDHandler extends UUIDHandlerImplementation {
final int MAX_REQUESTS = 500;
private final String PROFILE_URL = "https://sessionserver.mojang.com/session/minecraft/profile/";
private final String PROFILE_URL =
"https://sessionserver.mojang.com/session/minecraft/profile/";
private final int INTERVAL = 12000;
private final JSONParser jsonParser = new JSONParser();
private final SQLite sqlite;
@ -64,20 +66,21 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
}
}
@Override
public boolean startCaching(final Runnable whenDone) {
@Override public boolean startCaching(final Runnable whenDone) {
if (!super.startCaching(whenDone)) {
return false;
}
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
@Override public void run() {
try {
HashBiMap<StringWrapper, UUID> toAdd = HashBiMap.create(new HashMap<StringWrapper, UUID>());
try (PreparedStatement statement = getConnection().prepareStatement("SELECT `uuid`, `username` FROM `usercache`");
HashBiMap<StringWrapper, UUID> toAdd =
HashBiMap.create(new HashMap<StringWrapper, UUID>());
try (PreparedStatement statement = getConnection()
.prepareStatement("SELECT `uuid`, `username` FROM `usercache`");
ResultSet resultSet = statement.executeQuery()) {
while (resultSet.next()) {
StringWrapper username = new StringWrapper(resultSet.getString("username"));
StringWrapper username =
new StringWrapper(resultSet.getString("username"));
UUID uuid = UUID.fromString(resultSet.getString("uuid"));
toAdd.put(new StringWrapper(username.value), uuid);
}
@ -96,10 +99,10 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
}
return;
}
FileUUIDHandler fileHandler = new FileUUIDHandler(SQLUUIDHandler.this.uuidWrapper);
FileUUIDHandler fileHandler =
new FileUUIDHandler(SQLUUIDHandler.this.uuidWrapper);
fileHandler.startCaching(new Runnable() {
@Override
public void run() {
@Override public void run() {
// If the file based UUID handler didn't cache it, then we can't cache offline mode
// Also, trying to cache based on files again, is useless as that's what the file based uuid cacher does
if (Settings.UUID.OFFLINE) {
@ -110,18 +113,24 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
}
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
@Override public void run() {
while (!toFetch.isEmpty()) {
try {
for (int i = 0; i < Math.min(500, toFetch.size()); i++) {
for (int i = 0;
i < Math.min(500, toFetch.size()); i++) {
UUID uuid = toFetch.pop();
HttpURLConnection connection =
(HttpURLConnection) new URL(SQLUUIDHandler.this.PROFILE_URL + uuid.toString().replace("-", ""))
(HttpURLConnection) new URL(
SQLUUIDHandler.this.PROFILE_URL + uuid
.toString().replace("-", ""))
.openConnection();
try (InputStream con = connection.getInputStream()) {
InputStreamReader reader = new InputStreamReader(con);
JSONObject response = (JSONObject) SQLUUIDHandler.this.jsonParser.parse(reader);
try (InputStream con = connection
.getInputStream()) {
InputStreamReader reader =
new InputStreamReader(con);
JSONObject response =
(JSONObject) SQLUUIDHandler.this.jsonParser
.parse(reader);
String name = (String) response.get("name");
if (name != null) {
add(new StringWrapper(name), uuid);
@ -129,8 +138,9 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
}
connection.disconnect();
}
}catch(IOException | ParseException e){
PS.debug("Invalid response from Mojang: Some UUIDs will be cached later. (`unknown` until then or player joins)");
} catch (IOException | ParseException e) {
PS.debug(
"Invalid response from Mojang: Some UUIDs will be cached later. (`unknown` until then or player joins)");
}
try {
Thread.sleep(INTERVAL * 50);
@ -155,15 +165,14 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
return true;
}
@Override
public void fetchUUID(final String name, final RunnableVal<UUID> ifFetch) {
PS.debug(C.PREFIX + "UUID for '" + name + "' was null. We'll cache this from the Mojang servers!");
@Override public void fetchUUID(final String name, final RunnableVal<UUID> ifFetch) {
PS.debug(C.PREFIX + "UUID for '" + name
+ "' was null. We'll cache this from the Mojang servers!");
if (ifFetch == null) {
return;
}
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
@Override public void run() {
try {
URL url = new URL(SQLUUIDHandler.this.PROFILE_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
@ -177,13 +186,14 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
stream.write(body.getBytes());
stream.flush();
stream.close();
JSONArray array = (JSONArray) SQLUUIDHandler.this.jsonParser.parse(new InputStreamReader(connection.getInputStream()));
JSONArray array = (JSONArray) SQLUUIDHandler.this.jsonParser
.parse(new InputStreamReader(connection.getInputStream()));
JSONObject jsonProfile = (JSONObject) array.get(0);
String id = (String) jsonProfile.get("id");
String name = (String) jsonProfile.get("name");
ifFetch.value = UUID.fromString(
id.substring(0, 8) + '-' + id.substring(8, 12) + '-' + id.substring(12, 16) + '-' + id.substring(16, 20) + '-' + id
.substring(20, 32));
id.substring(0, 8) + '-' + id.substring(8, 12) + '-' + id.substring(12, 16)
+ '-' + id.substring(16, 20) + '-' + id.substring(20, 32));
} catch (IOException | ParseException e) {
e.printStackTrace();
}
@ -192,8 +202,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
});
}
@Override
public void handleShutdown() {
@Override public void handleShutdown() {
super.handleShutdown();
try {
getConnection().close();
@ -202,14 +211,13 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
}
}
@Override
public boolean add(final StringWrapper name, final UUID uuid) {
@Override public boolean add(final StringWrapper name, final UUID uuid) {
// Ignoring duplicates
if (super.add(name, uuid)) {
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
try (PreparedStatement statement = getConnection().prepareStatement("REPLACE INTO usercache (`uuid`, `username`) VALUES(?, ?)")) {
@Override public void run() {
try (PreparedStatement statement = getConnection().prepareStatement(
"REPLACE INTO usercache (`uuid`, `username`) VALUES(?, ?)")) {
statement.setString(1, uuid.toString());
statement.setString(2, name.toString());
statement.execute();
@ -227,13 +235,12 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
/**
* This is useful for name changes
*/
@Override
public void rename(final UUID uuid, final StringWrapper name) {
@Override public void rename(final UUID uuid, final StringWrapper name) {
super.rename(uuid, name);
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
try (PreparedStatement statement = getConnection().prepareStatement("UPDATE usercache SET `username`=? WHERE `uuid`=?")) {
@Override public void run() {
try (PreparedStatement statement = getConnection()
.prepareStatement("UPDATE usercache SET `username`=? WHERE `uuid`=?")) {
statement.setString(1, name.value);
statement.setString(2, uuid.toString());
statement.execute();

View File

@ -18,7 +18,7 @@ processResources {
}
}
jar.archiveName="plotsquared-api-${project.parent.version}.jar"
jar.archiveName = "plotsquared-api-${project.parent.version}.jar"
jar.destinationDir = file '../mvn/com/plotsquared/plotsquared-api/' + project.parent.version
task createPom << {
pom {
@ -43,7 +43,7 @@ task copyFiles {
from "../mvn/com/plotsquared/plotsquared-api/${project.parent.version}/"
into '../mvn/com/plotsquared/plotsquared-api/latest/'
include('*.jar')
rename ("plotsquared-api-${project.parent.version}.jar", 'plotsquared-api-latest.jar')
rename("plotsquared-api-${project.parent.version}.jar", 'plotsquared-api-latest.jar')
}
}
}

View File

@ -8,11 +8,11 @@ import java.util.Map;
public interface Configuration extends ConfigurationSection {
/**
* Sets the default value of the given path as provided.
*
* <p>
* <p>If no source {@link Configuration} was provided as a default
* collection, then a new {@link MemoryConfiguration} will be created to
* hold the new default value.</p>
*
* <p>
* <p>If value is null, the value will be removed from the default
* Configuration source.</p>
*
@ -24,7 +24,7 @@ public interface Configuration extends ConfigurationSection {
/**
* Sets the default values of the given paths as provided.
*
* <p>
* <p>If no source {@link Configuration} was provided as a default
* collection, then a new {@link MemoryConfiguration} will be created to
* hold the new default values.</p>
@ -36,11 +36,11 @@ public interface Configuration extends ConfigurationSection {
/**
* Sets the default values of the given paths as provided.
*
* <p>
* <p>If no source {@link Configuration} was provided as a default
* collection, then a new {@link MemoryConfiguration} will be created to
* hold the new default value.</p>
*
* <p>
* <p>This method will not hold a reference to the specified Configuration,
* nor will it automatically update if that Configuration ever changes. If
* you check this, you should set the default source with {@link
@ -53,7 +53,7 @@ public interface Configuration extends ConfigurationSection {
/**
* Gets the source {@link Configuration} for this configuration.
*
* <p>
* <p>
* If no configuration source was set, but default values were added, then
* a {@link MemoryConfiguration} will be returned. If no source was set
@ -65,7 +65,7 @@ public interface Configuration extends ConfigurationSection {
/**
* Sets the source of all default values for this {@link Configuration}.
*
* <p>
* <p>
* If a previous source was set, or previous default values were defined,
* then they will not be copied to the new source.</p>
@ -77,7 +77,7 @@ public interface Configuration extends ConfigurationSection {
/**
* Gets the {@link ConfigurationOptions} for this {@link Configuration}.
*
* <p>
* <p>All setters through this method are chainable.</p>
*
* @return Options for this configuration

View File

@ -25,7 +25,7 @@ class ConfigurationOptions {
/**
* Gets the char that will be used to separate {@link
* ConfigurationSection}s.
*
* <p>
* <p>This value does not affect how the {@link Configuration} is stored,
* only in how you access the data. The default value is '.'.
*
@ -38,7 +38,7 @@ class ConfigurationOptions {
/**
* Sets the char that will be used to separate {@link
* ConfigurationSection}s.
*
* <p>
* <p>This value does not affect how the {@link Configuration} is stored,
* only in how you access the data. The default value is '.'.
*
@ -53,7 +53,7 @@ class ConfigurationOptions {
/**
* Checks if the {@link Configuration} should copy values from its default
* {@link Configuration} directly.
*
* <p>
* <p>If this is true, all values in the default Configuration will be
* directly copied, making it impossible to distinguish between values
* that were set and values that are provided by default. As a result,
@ -71,7 +71,7 @@ class ConfigurationOptions {
/**
* Sets if the {@link Configuration} should copy values from its default
* {@link Configuration} directly.
*
* <p>
* <p>If this is true, all values in the default Configuration will be
* directly copied, making it impossible to distinguish between values
* that were set and values that are provided by default. As a result,

View File

@ -11,11 +11,11 @@ public interface ConfigurationSection {
/**
* Gets a set containing all keys in this section.
*
* <p>
* <p>If deep is set to true, then this will contain all the keys within any
* child {@link ConfigurationSection}s (and their children, etc). These
* will be in a valid path notation for you to use.
*
* <p>
* <p>If deep is set to false, then this will contain only the keys of any
* direct children, and not their own children.
*
@ -27,11 +27,11 @@ public interface ConfigurationSection {
/**
* Gets a Map containing all keys and their values for this section.
*
* <p>
* <p>If deep is set to true, then this will contain all the keys and values
* within any child {@link ConfigurationSection}s (and their children,
* etc). These keys will be in a valid path notation for you to use.
*
* <p>
* <p>If deep is set to false, then this will contain only the keys and
* values of any direct children, and not their own children.
*
@ -43,7 +43,7 @@ public interface ConfigurationSection {
/**
* Checks if this {@link ConfigurationSection} contains the given path.
*
* <p>
* <p>If the value for the requested path does not exist but a default value
* has been specified, this will return true.
*
@ -57,7 +57,7 @@ public interface ConfigurationSection {
/**
* Checks if this {@link ConfigurationSection} has a value set for the
* given path.
*
* <p>
* <p>If the value for the requested path does not exist but a default value
* has been specified, this will still return false.
*
@ -71,14 +71,14 @@ public interface ConfigurationSection {
/**
* Gets the path of this {@link ConfigurationSection} from its root {@link
* Configuration}.
*
* <p>
* <p>For any {@link Configuration} themselves, this will return an empty
* string.
*
* <p>
* <p>If the section is no longer contained within its root for any reason,
* such as being replaced with a different value,
* this may return {@code null}.
*
* <p>
* <p>To retrieve the single name of this section, that is, the final part
* of the path returned by this method, you may use {@link #getName()}.
*
@ -89,7 +89,7 @@ public interface ConfigurationSection {
/**
* Gets the name of this individual {@link ConfigurationSection}, in the
* path.
*
* <p>
* <p>This will always be the final part of {@link #getCurrentPath()}, unless
* the section is orphaned.
*
@ -100,10 +100,10 @@ public interface ConfigurationSection {
/**
* Gets the root {@link Configuration} that contains this {@link
* ConfigurationSection}
*
* <p>
* <p>For any {@link Configuration} themselves, this will return its own
* object.
*
* <p>
* <p>If the section is no longer contained within its root for any reason,
* such as being replaced with a different value,
* this may return {@code null}.
@ -115,10 +115,10 @@ public interface ConfigurationSection {
/**
* Gets the parent {@link ConfigurationSection} that directly contains
* this {@link ConfigurationSection}.
*
* <p>
* <p>For any {@link Configuration} themselves, this will return
* {@code null}.
*
* <p>
* <p>If the section is no longer contained within its parent for any
* reason, such as being replaced with a different value, this may
* return {@code null}.
@ -129,7 +129,7 @@ public interface ConfigurationSection {
/**
* Gets the requested Object by path.
*
* <p>
* <p>If the Object does not exist but a default value has been specified,
* this will return the default value. If the Object does not exist and no
* default value was specified, this will return {@code null}.
@ -142,7 +142,7 @@ public interface ConfigurationSection {
/**
* Gets the requested Object by path, returning a default value if not
* found.
*
* <p>
* <p>If the Object does not exist then the specified default value will
* returned regardless of if a default has been identified in the root
* {@link Configuration}.
@ -155,10 +155,10 @@ public interface ConfigurationSection {
/**
* Sets the specified path to the given value.
*
* <p>
* <p>If value is {@code null}, the entry will be removed. Any
* existing entry will be replaced, regardless of what the new value is.
*
* <p>
* <p>Some implementations may have limitations on what you may store. See
* their individual javadoc for details. No implementations should allow
* you to store {@link Configuration}s or {@link ConfigurationSection}s,
@ -171,7 +171,7 @@ public interface ConfigurationSection {
/**
* Creates an empty {@link ConfigurationSection} at the specified path.
*
* <p>
* <p>Any value that was previously set at this path will be overwritten. If
* the previous value was itself a {@link ConfigurationSection}, it will
* be orphaned.
@ -184,7 +184,7 @@ public interface ConfigurationSection {
/**
* Creates a {@link ConfigurationSection} at the specified path, with
* specified values.
*
* <p>
* <p>Any value that was previously set at this path will be overwritten. If
* the previous value was itself a {@link ConfigurationSection}, it will
* be orphaned.
@ -199,7 +199,7 @@ public interface ConfigurationSection {
/**
* Gets the requested String by path.
*
* <p>
* <p>If the String does not exist but a default value has been specified,
* this will return the default value. If the String does not exist and no
* default value was specified, this will return {@code null}.
@ -212,7 +212,7 @@ public interface ConfigurationSection {
/**
* Gets the requested String by path, returning a default value if not
* found.
*
* <p>
* <p>If the String does not exist then the specified default value will
* returned regardless of if a default has been identified in the root
* {@link Configuration}.
@ -226,7 +226,7 @@ public interface ConfigurationSection {
/**
* Checks if the specified path is a String.
*
* <p>
* <p>If the path exists but is not a String, this will return false. If
* the path does not exist, this will return false. If the path does not
* exist but a default value has been specified, this will check if that
@ -239,7 +239,7 @@ public interface ConfigurationSection {
/**
* Gets the requested int by path.
*
* <p>
* <p>If the int does not exist but a default value has been specified, this
* will return the default value. If the int does not exist and no default
* value was specified, this will return 0.
@ -251,7 +251,7 @@ public interface ConfigurationSection {
/**
* Gets the requested int by path, returning a default value if not found.
*
* <p>
* <p>If the int does not exist then the specified default value will
* returned regardless of if a default has been identified in the root
* {@link Configuration}.
@ -265,7 +265,7 @@ public interface ConfigurationSection {
/**
* Checks if the specified path is an int.
*
* <p>
* <p>If the path exists but is not a int, this will return false. If the
* path does not exist, this will return false. If the path does not exist
* but a default value has been specified, this will check if that default
@ -278,7 +278,7 @@ public interface ConfigurationSection {
/**
* Gets the requested boolean by path.
*
* <p>
* <p>If the boolean does not exist but a default value has been specified,
* this will return the default value. If the boolean does not exist and
* no default value was specified, this will return false.
@ -291,7 +291,7 @@ public interface ConfigurationSection {
/**
* Gets the requested boolean by path, returning a default value if not
* found.
*
* <p>
* <p>If the boolean does not exist then the specified default value will
* returned regardless of if a default has been identified in the root
* {@link Configuration}.
@ -305,7 +305,7 @@ public interface ConfigurationSection {
/**
* Checks if the specified path is a boolean.
*
* <p>
* <p>If the path exists but is not a boolean, this will return false. If the
* path does not exist, this will return false. If the path does not exist
* but a default value has been specified, this will check if that default
@ -318,7 +318,7 @@ public interface ConfigurationSection {
/**
* Gets the requested double by path.
*
* <p>
* <p>If the double does not exist but a default value has been specified,
* this will return the default value. If the double does not exist and no
* default value was specified, this will return 0.
@ -331,7 +331,7 @@ public interface ConfigurationSection {
/**
* Gets the requested double by path, returning a default value if not
* found.
*
* <p>
* <p>If the double does not exist then the specified default value will
* returned regardless of if a default has been identified in the root
* {@link Configuration}.
@ -345,7 +345,7 @@ public interface ConfigurationSection {
/**
* Checks if the specified path is a double.
*
* <p>
* <p>If the path exists but is not a double, this will return false. If the
* path does not exist, this will return false. If the path does not exist
* but a default value has been specified, this will check if that default
@ -358,7 +358,7 @@ public interface ConfigurationSection {
/**
* Gets the requested long by path.
*
* <p>
* <p>If the long does not exist but a default value has been specified, this
* will return the default value. If the long does not exist and no
* default value was specified, this will return 0.
@ -371,7 +371,7 @@ public interface ConfigurationSection {
/**
* Gets the requested long by path, returning a default value if not
* found.
*
* <p>
* <p>If the long does not exist then the specified default value will
* returned regardless of if a default has been identified in the root
* {@link Configuration}.
@ -385,7 +385,7 @@ public interface ConfigurationSection {
/**
* Checks if the specified path is a long.
*
* <p>
* <p>If the path exists but is not a long, this will return false. If the
* path does not exist, this will return false. If the path does not exist
* but a default value has been specified, this will check if that default
@ -400,7 +400,7 @@ public interface ConfigurationSection {
/**
* Gets the requested List by path.
*
* <p>
* <p>If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
* default value was specified, this will return null.
@ -413,7 +413,7 @@ public interface ConfigurationSection {
/**
* Gets the requested List by path, returning a default value if not
* found.
*
* <p>
* <p>If the List does not exist then the specified default value will
* returned regardless of if a default has been identified in the root
* {@link Configuration}.
@ -427,7 +427,7 @@ public interface ConfigurationSection {
/**
* Checks if the specified path is a List.
*
* <p>
* <p>If the path exists but is not a List, this will return false. If the
* path does not exist, this will return false. If the path does not exist
* but a default value has been specified, this will check if that default
@ -440,11 +440,11 @@ public interface ConfigurationSection {
/**
* Gets the requested List of String by path.
*
* <p>
* <p>If the List does not exist but a default value has been specified,
* this will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
*
* <p>
* <p>This method will attempt to cast any values into a String if possible,
* but may miss any values out if they are not compatible.
*
@ -455,11 +455,11 @@ public interface ConfigurationSection {
/**
* Gets the requested List of Integer by path.
*
* <p>
* <p>If the List does not exist but a default value has been specified,
* this will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
*
* <p>
* <p>This method will attempt to cast any values into a Integer if
* possible, but may miss any values out if they are not compatible.
*
@ -470,11 +470,11 @@ public interface ConfigurationSection {
/**
* Gets the requested List of Boolean by path.
*
* <p>
* <p>If the List does not exist but a default value has been specified,
* this will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
*
* <p>
* <p>This method will attempt to cast any values into a Boolean if
* possible, but may miss any values out if they are not compatible.
*
@ -485,11 +485,11 @@ public interface ConfigurationSection {
/**
* Gets the requested List of Double by path.
*
* <p>
* <p>If the List does not exist but a default value has been specified,
* this will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
*
* <p>
* <p>This method will attempt to cast any values into a Double if possible,
* but may miss any values out if they are not compatible.
*
@ -500,11 +500,11 @@ public interface ConfigurationSection {
/**
* Gets the requested List of Float by path.
*
* <p>
* <p>If the List does not exist but a default value has been specified,
* this will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
*
* <p>
* <p>This method will attempt to cast any values into a Float if possible,
* but may miss any values out if they are not compatible.
*
@ -515,11 +515,11 @@ public interface ConfigurationSection {
/**
* Gets the requested List of Long by path.
*
* <p>
* <p>If the List does not exist but a default value has been specified,
* this will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
*
* <p>
* <p>This method will attempt to cast any values into a Long if possible,
* but may miss any values out if they are not compatible.
*
@ -530,11 +530,11 @@ public interface ConfigurationSection {
/**
* Gets the requested List of Byte by path.
*
* <p>
* <p>If the List does not exist but a default value has been specified,
* this will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
*
* <p>
* <p>This method will attempt to cast any values into a Byte if possible,
* but may miss any values out if they are not compatible.
*
@ -545,11 +545,11 @@ public interface ConfigurationSection {
/**
* Gets the requested List of Character by path.
*
* <p>
* <p>If the List does not exist but a default value has been specified,
* this will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
*
* <p>
* <p>This method will attempt to cast any values into a Character if
* possible, but may miss any values out if they are not compatible.
*
@ -560,11 +560,11 @@ public interface ConfigurationSection {
/**
* Gets the requested List of Short by path.
*
* <p>
* <p>If the List does not exist but a default value has been specified,
* this will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
*
* <p>
* <p>This method will attempt to cast any values into a Short if
* possible, but may miss any values out if they are not compatible.
*
@ -575,7 +575,7 @@ public interface ConfigurationSection {
/**
* Gets the requested List of Maps by path.
*
* <p>
* <p>If the List does not exist but a default value has been specified,
* this will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
@ -589,7 +589,7 @@ public interface ConfigurationSection {
/**
* Gets the requested ConfigurationSection by path.
*
* <p>
* <p>If the ConfigurationSection does not exist but a default value has
* been specified, this will return the default value. If the
* ConfigurationSection does not exist and no default value was specified,
@ -602,7 +602,7 @@ public interface ConfigurationSection {
/**
* Checks if the specified path is a ConfigurationSection.
*
* <p>
* <p>If the path exists but is not a ConfigurationSection, this will return
* false. If the path does not exist, this will return false. If the path
* does not exist but a default value has been specified, this will check
@ -617,7 +617,7 @@ public interface ConfigurationSection {
/**
* Gets the equivalent {@link ConfigurationSection} from the default
* {@link Configuration} defined in {@link #getRoot()}.
*
* <p>
* <p>If the root contains no defaults, or the defaults doesn't contain a
* value for this path, or the value at this path is not a {@link
* ConfigurationSection} then this will return {@code null}.
@ -628,14 +628,14 @@ public interface ConfigurationSection {
/**
* Sets the default value in the root at the given path as provided.
*
* <p>
* <p>If no source {@link Configuration} was provided as a default
* collection, then a new {@link MemoryConfiguration} will be created to
* hold the new default value.
*
* <p>
* <p>If value is {@code null}, the value will be removed from the
* default Configuration source.
*
* <p>
* <p>If the value as returned by {@link #getDefaultSection()} is
* {@code null}, then this will create a new section at the path,
* replacing anything that may have existed there previously.

View File

@ -3,14 +3,14 @@ package com.intellectualcrafters.configuration;
/**
* Exception thrown when attempting to load an invalid {@link Configuration}.
*/
@SuppressWarnings("serial")
public class InvalidConfigurationException extends Exception {
@SuppressWarnings("serial") public class InvalidConfigurationException extends Exception {
/**
* Creates a new instance of InvalidConfigurationException without a
* message or cause.
*/
public InvalidConfigurationException() {}
public InvalidConfigurationException() {
}
/**
* Constructs an instance of InvalidConfigurationException with the

View File

@ -14,7 +14,8 @@ public class MemoryConfiguration extends MemorySection implements Configuration
/**
* Creates an empty {@link MemoryConfiguration} with no default values.
*/
public MemoryConfiguration() {}
public MemoryConfiguration() {
}
/**
* Creates an empty {@link MemoryConfiguration} using the specified {@link
@ -27,8 +28,7 @@ public class MemoryConfiguration extends MemorySection implements Configuration
this.defaults = defaults;
}
@Override
public void addDefault(String path, Object value) {
@Override public void addDefault(String path, Object value) {
if (this.defaults == null) {
this.defaults = new MemoryConfiguration();
}
@ -36,25 +36,21 @@ public class MemoryConfiguration extends MemorySection implements Configuration
this.defaults.set(path, value);
}
@Override
public void addDefaults(Map<String, Object> defaults) {
@Override public void addDefaults(Map<String, Object> defaults) {
for (Map.Entry<String, Object> entry : defaults.entrySet()) {
addDefault(entry.getKey(), entry.getValue());
}
}
@Override
public void addDefaults(Configuration defaults) {
@Override public void addDefaults(Configuration defaults) {
addDefaults(defaults.getValues(true));
}
@Override
public Configuration getDefaults() {
@Override public Configuration getDefaults() {
return this.defaults;
}
@Override
public void setDefaults(Configuration defaults) {
@Override public void setDefaults(Configuration defaults) {
if (defaults == null) {
throw new NullPointerException("Defaults may not be null");
}
@ -62,13 +58,11 @@ public class MemoryConfiguration extends MemorySection implements Configuration
this.defaults = defaults;
}
@Override
public ConfigurationSection getParent() {
@Override public ConfigurationSection getParent() {
return null;
}
@Override
public MemoryConfigurationOptions options() {
@Override public MemoryConfigurationOptions options() {
if (this.options == null) {
this.options = new MemoryConfigurationOptions(this);
}

View File

@ -9,19 +9,16 @@ public class MemoryConfigurationOptions extends ConfigurationOptions {
super(configuration);
}
@Override
public MemoryConfiguration configuration() {
@Override public MemoryConfiguration configuration() {
return (MemoryConfiguration) super.configuration();
}
@Override
public MemoryConfigurationOptions copyDefaults(boolean value) {
@Override public MemoryConfigurationOptions copyDefaults(boolean value) {
super.copyDefaults(value);
return this;
}
@Override
public MemoryConfigurationOptions pathSeparator(char value) {
@Override public MemoryConfigurationOptions pathSeparator(char value) {
super.pathSeparator(value);
return this;
}

View File

@ -1,11 +1,6 @@
package com.intellectualcrafters.configuration;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.*;
/**
* A type of {@link ConfigurationSection} that is stored in memory.
@ -21,7 +16,7 @@ public class MemorySection implements ConfigurationSection {
/**
* Creates an empty MemorySection for use as a root {@link Configuration}
* section.
*
* <p>
* <p>Note that calling this without being yourself a {@link Configuration}
* will throw an exception!
*
@ -30,7 +25,8 @@ public class MemorySection implements ConfigurationSection {
*/
protected MemorySection() {
if (!(this instanceof Configuration)) {
throw new IllegalStateException("Cannot construct a root MemorySection when not a Configuration");
throw new IllegalStateException(
"Cannot construct a root MemorySection when not a Configuration");
}
this.path = "";
@ -117,7 +113,7 @@ public class MemorySection implements ConfigurationSection {
/**
* Creates a full path to the given {@link ConfigurationSection} from its
* root {@link Configuration}.
*
* <p>
* <p>You may use this method for any given {@link ConfigurationSection}, not
* only {@link MemorySection}.
*
@ -132,7 +128,7 @@ public class MemorySection implements ConfigurationSection {
/**
* Creates a relative path to the given {@link ConfigurationSection} from
* the given relative section.
*
* <p>
* <p>You may use this method for any given {@link ConfigurationSection}, not
* only {@link MemorySection}.
*
@ -141,7 +137,8 @@ public class MemorySection implements ConfigurationSection {
* @param relativeTo Section to create the path relative to.
* @return Full path of the section from its root.
*/
public static String createPath(ConfigurationSection section, String key, ConfigurationSection relativeTo) {
public static String createPath(ConfigurationSection section, String key,
ConfigurationSection relativeTo) {
Configuration root = section.getRoot();
if (root == null) {
throw new IllegalStateException("Cannot create path without a root");
@ -149,7 +146,8 @@ public class MemorySection implements ConfigurationSection {
char separator = root.options().pathSeparator();
StringBuilder builder = new StringBuilder();
for (ConfigurationSection parent = section; (parent != null) && (parent != relativeTo); parent = parent.getParent()) {
for (ConfigurationSection parent = section;
(parent != null) && (parent != relativeTo); parent = parent.getParent()) {
if (builder.length() > 0) {
builder.insert(0, separator);
}
@ -168,8 +166,7 @@ public class MemorySection implements ConfigurationSection {
return builder.toString();
}
@Override
public Set<String> getKeys(boolean deep) {
@Override public Set<String> getKeys(boolean deep) {
Set<String> result = new LinkedHashSet<>();
Configuration root = getRoot();
@ -186,8 +183,7 @@ public class MemorySection implements ConfigurationSection {
return result;
}
@Override
public Map<String, Object> getValues(boolean deep) {
@Override public Map<String, Object> getValues(boolean deep) {
Map<String, Object> result = new LinkedHashMap<>();
Configuration root = getRoot();
@ -204,13 +200,11 @@ public class MemorySection implements ConfigurationSection {
return result;
}
@Override
public boolean contains(String path) {
@Override public boolean contains(String path) {
return get(path) != null;
}
@Override
public boolean isSet(String path) {
@Override public boolean isSet(String path) {
Configuration root = getRoot();
if (root == null) {
return false;
@ -221,40 +215,35 @@ public class MemorySection implements ConfigurationSection {
return get(path, null) != null;
}
@Override
public String getCurrentPath() {
@Override public String getCurrentPath() {
return this.fullPath;
}
@Override
public String getName() {
@Override public String getName() {
return this.path;
}
@Override
public Configuration getRoot() {
@Override public Configuration getRoot() {
return this.root;
}
@Override
public ConfigurationSection getParent() {
@Override public ConfigurationSection getParent() {
return this.parent;
}
@Override
public void addDefault(String path, Object value) {
@Override public void addDefault(String path, Object value) {
Configuration root = getRoot();
if (root == null) {
throw new IllegalStateException("Cannot add default without root");
}
if (root == this) {
throw new UnsupportedOperationException("Unsupported addDefault(String, Object) implementation");
throw new UnsupportedOperationException(
"Unsupported addDefault(String, Object) implementation");
}
root.addDefault(createPath(this, path), value);
}
@Override
public ConfigurationSection getDefaultSection() {
@Override public ConfigurationSection getDefaultSection() {
Configuration root = getRoot();
Configuration defaults = root == null ? null : root.getDefaults();
@ -267,8 +256,7 @@ public class MemorySection implements ConfigurationSection {
return null;
}
@Override
public void set(String path, Object value) {
@Override public void set(String path, Object value) {
Configuration root = getRoot();
if (root == null) {
throw new IllegalStateException("Cannot use section without a root");
@ -302,13 +290,11 @@ public class MemorySection implements ConfigurationSection {
}
}
@Override
public Object get(String path) {
@Override public Object get(String path) {
return get(path, getDefault(path));
}
@Override
public Object get(String path, Object defaultValue) {
@Override public Object get(String path, Object defaultValue) {
if (path == null) {
throw new NullPointerException("Path cannot be null");
}
@ -347,8 +333,7 @@ public class MemorySection implements ConfigurationSection {
return section.get(key, defaultValue);
}
@Override
public ConfigurationSection createSection(String path) {
@Override public ConfigurationSection createSection(String path) {
Configuration root = getRoot();
if (root == null) {
throw new IllegalStateException("Cannot create section without a root");
@ -379,8 +364,7 @@ public class MemorySection implements ConfigurationSection {
return section.createSection(key);
}
@Override
public ConfigurationSection createSection(String path, Map<?, ?> map) {
@Override public ConfigurationSection createSection(String path, Map<?, ?> map) {
ConfigurationSection section = createSection(path);
for (Map.Entry<?, ?> entry : map.entrySet()) {
@ -395,14 +379,12 @@ public class MemorySection implements ConfigurationSection {
}
// Primitives
@Override
public String getString(String path) {
@Override public String getString(String path) {
Object def = getDefault(path);
return getString(path, def != null ? def.toString() : null);
}
@Override
public String getString(String path, String def) {
@Override public String getString(String path, String def) {
Object val = get(path, def);
if (val != null) {
return val.toString();
@ -411,32 +393,27 @@ public class MemorySection implements ConfigurationSection {
}
}
@Override
public boolean isString(String path) {
@Override public boolean isString(String path) {
Object val = get(path);
return val instanceof String;
}
@Override
public int getInt(String path) {
@Override public int getInt(String path) {
Object def = getDefault(path);
return getInt(path, toInt(def, 0));
}
@Override
public int getInt(String path, int def) {
@Override public int getInt(String path, int def) {
Object val = get(path, def);
return toInt(val, def);
}
@Override
public boolean isInt(String path) {
@Override public boolean isInt(String path) {
Object val = get(path);
return val instanceof Integer;
}
@Override
public boolean getBoolean(String path) {
@Override public boolean getBoolean(String path) {
Object def = getDefault(path);
if (def instanceof Boolean) {
return getBoolean(path, (Boolean) def);
@ -445,8 +422,7 @@ public class MemorySection implements ConfigurationSection {
}
}
@Override
public boolean getBoolean(String path, boolean defaultValue) {
@Override public boolean getBoolean(String path, boolean defaultValue) {
Object val = get(path, defaultValue);
if (val instanceof Boolean) {
return (Boolean) val;
@ -455,69 +431,58 @@ public class MemorySection implements ConfigurationSection {
}
}
@Override
public boolean isBoolean(String path) {
@Override public boolean isBoolean(String path) {
Object val = get(path);
return val instanceof Boolean;
}
@Override
public double getDouble(String path) {
@Override public double getDouble(String path) {
Object def = getDefault(path);
return getDouble(path, toDouble(def, 0));
}
@Override
public double getDouble(String path, double defaultValue) {
@Override public double getDouble(String path, double defaultValue) {
Object val = get(path, defaultValue);
return toDouble(val, defaultValue);
}
@Override
public boolean isDouble(String path) {
@Override public boolean isDouble(String path) {
Object val = get(path);
return val instanceof Double;
}
@Override
public long getLong(String path) {
@Override public long getLong(String path) {
Object def = getDefault(path);
return getLong(path, toLong(def, 0));
}
@Override
public long getLong(String path, long def) {
@Override public long getLong(String path, long def) {
Object val = get(path, def);
return toLong(val, def);
}
@Override
public boolean isLong(String path) {
@Override public boolean isLong(String path) {
Object val = get(path);
return val instanceof Long;
}
// Java
@Override
public List<?> getList(String path) {
@Override public List<?> getList(String path) {
Object def = getDefault(path);
return getList(path, def instanceof List ? (List<?>) def : null);
}
@Override
public List<?> getList(String path, List<?> def) {
@Override public List<?> getList(String path, List<?> def) {
Object val = get(path, def);
return (List<?>) ((val instanceof List) ? val : def);
}
@Override
public boolean isList(String path) {
@Override public boolean isList(String path) {
Object val = get(path);
return val instanceof List;
}
@Override
public List<String> getStringList(String path) {
@Override public List<String> getStringList(String path) {
List<?> list = getList(path);
if (list == null) {
@ -535,8 +500,7 @@ public class MemorySection implements ConfigurationSection {
return result;
}
@Override
public List<Integer> getIntegerList(String path) {
@Override public List<Integer> getIntegerList(String path) {
List<?> list = getList(path);
List<Integer> result = new ArrayList<>();
@ -559,8 +523,7 @@ public class MemorySection implements ConfigurationSection {
return result;
}
@Override
public List<Boolean> getBooleanList(String path) {
@Override public List<Boolean> getBooleanList(String path) {
List<?> list = getList(path);
List<Boolean> result = new ArrayList<>();
@ -580,8 +543,7 @@ public class MemorySection implements ConfigurationSection {
return result;
}
@Override
public List<Double> getDoubleList(String path) {
@Override public List<Double> getDoubleList(String path) {
List<?> list = getList(path);
List<Double> result = new ArrayList<>();
@ -604,8 +566,7 @@ public class MemorySection implements ConfigurationSection {
return result;
}
@Override
public List<Float> getFloatList(String path) {
@Override public List<Float> getFloatList(String path) {
List<?> list = getList(path);
List<Float> result = new ArrayList<>();
@ -628,8 +589,7 @@ public class MemorySection implements ConfigurationSection {
return result;
}
@Override
public List<Long> getLongList(String path) {
@Override public List<Long> getLongList(String path) {
List<?> list = getList(path);
List<Long> result = new ArrayList<>();
@ -652,8 +612,7 @@ public class MemorySection implements ConfigurationSection {
return result;
}
@Override
public List<Byte> getByteList(String path) {
@Override public List<Byte> getByteList(String path) {
List<?> list = getList(path);
List<Byte> result = new ArrayList<>();
@ -676,8 +635,7 @@ public class MemorySection implements ConfigurationSection {
return result;
}
@Override
public List<Character> getCharacterList(String path) {
@Override public List<Character> getCharacterList(String path) {
List<?> list = getList(path);
List<Character> result = new ArrayList<>();
@ -699,8 +657,7 @@ public class MemorySection implements ConfigurationSection {
return result;
}
@Override
public List<Short> getShortList(String path) {
@Override public List<Short> getShortList(String path) {
List<?> list = getList(path);
List<Short> result = new ArrayList<>();
@ -723,8 +680,7 @@ public class MemorySection implements ConfigurationSection {
return result;
}
@Override
public List<Map<?, ?>> getMapList(String path) {
@Override public List<Map<?, ?>> getMapList(String path) {
List<?> list = getList(path);
List<Map<?, ?>> result = new ArrayList<>();
@ -737,8 +693,7 @@ public class MemorySection implements ConfigurationSection {
return result;
}
@Override
public ConfigurationSection getConfigurationSection(String path) {
@Override public ConfigurationSection getConfigurationSection(String path) {
Object val = get(path, null);
if (val != null) {
return (val instanceof ConfigurationSection) ? (ConfigurationSection) val : null;
@ -748,21 +703,15 @@ public class MemorySection implements ConfigurationSection {
return (val instanceof ConfigurationSection) ? createSection(path) : null;
}
@Override
public boolean isConfigurationSection(String path) {
@Override public boolean isConfigurationSection(String path) {
Object val = get(path);
return val instanceof ConfigurationSection;
}
protected boolean isPrimitiveWrapper(Object input) {
return (input instanceof Integer)
|| (input instanceof Boolean)
|| (input instanceof Character)
|| (input instanceof Byte)
|| (input instanceof Short)
|| (input instanceof Double)
|| (input instanceof Long)
|| (input instanceof Float);
return (input instanceof Integer) || (input instanceof Boolean)
|| (input instanceof Character) || (input instanceof Byte) || (input instanceof Short)
|| (input instanceof Double) || (input instanceof Long) || (input instanceof Float);
}
protected Object getDefault(String path) {
@ -792,7 +741,8 @@ public class MemorySection implements ConfigurationSection {
}
}
protected void mapChildrenValues(Map<String, Object> output, ConfigurationSection section, boolean deep) {
protected void mapChildrenValues(Map<String, Object> output, ConfigurationSection section,
boolean deep) {
if (section instanceof MemorySection) {
MemorySection sec = (MemorySection) section;
@ -814,13 +764,14 @@ public class MemorySection implements ConfigurationSection {
}
}
@Override
public String toString() {
@Override public String toString() {
Configuration root = getRoot();
if (root == null) {
return getClass().getSimpleName() + "[path='" + getCurrentPath() + "', root='" + null + "']";
return getClass().getSimpleName() + "[path='" + getCurrentPath() + "', root='" + null
+ "']";
} else {
return getClass().getSimpleName() + "[path='" + getCurrentPath() + "', root='" + root.getClass().getSimpleName() + "']";
return getClass().getSimpleName() + "[path='" + getCurrentPath() + "', root='" + root
.getClass().getSimpleName() + "']";
}
}
}

View File

@ -4,16 +4,7 @@ import com.intellectualcrafters.configuration.Configuration;
import com.intellectualcrafters.configuration.InvalidConfigurationException;
import com.intellectualcrafters.configuration.MemoryConfiguration;
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.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.io.*;
import java.nio.charset.StandardCharsets;
/**
@ -25,7 +16,8 @@ public abstract class FileConfiguration extends MemoryConfiguration {
/**
* Creates an empty {@link FileConfiguration} with no default values.
*/
FileConfiguration() {}
FileConfiguration() {
}
/**
* Creates an empty {@link FileConfiguration} using the specified {@link
@ -39,11 +31,11 @@ public abstract class FileConfiguration extends MemoryConfiguration {
/**
* Saves this {@link FileConfiguration} to the specified location.
*
* <p>
* <p>If the file does not exist, it will be created. If already exists, it
* will be overwritten. If it cannot be overwritten or created, an
* exception will be thrown.
*
* <p>
* <p>This method will save using the system default encoding, or possibly
* using UTF8.
*
@ -59,7 +51,8 @@ public abstract class FileConfiguration extends MemoryConfiguration {
String data = saveToString();
try (Writer writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)) {
try (Writer writer = new OutputStreamWriter(new FileOutputStream(file),
StandardCharsets.UTF_8)) {
writer.write(data);
}
}
@ -73,11 +66,11 @@ public abstract class FileConfiguration extends MemoryConfiguration {
/**
* Loads this {@link FileConfiguration} from the specified location.
*
* <p>
* <p>All the values contained within this configuration will be removed,
* leaving only settings and defaults, and the new values will be loaded
* from the given file.
*
* <p>
* <p>If the file cannot be loaded for any reason, an exception will be
* thrown.
*
@ -98,7 +91,7 @@ public abstract class FileConfiguration extends MemoryConfiguration {
/**
* Loads this {@link FileConfiguration} from the specified reader.
*
* <p>
* <p>All the values contained within this configuration will be removed,
* leaving only settings and defaults, and the new values will be loaded
* from the given stream.
@ -112,7 +105,9 @@ public abstract class FileConfiguration extends MemoryConfiguration {
StringBuilder builder = new StringBuilder();
try (BufferedReader input = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader)) {
try (BufferedReader input = reader instanceof BufferedReader ?
(BufferedReader) reader :
new BufferedReader(reader)) {
String line;
while ((line = input.readLine()) != null) {
@ -127,11 +122,11 @@ public abstract class FileConfiguration extends MemoryConfiguration {
/**
* Loads this {@link FileConfiguration} from the specified string, as
* opposed to from file.
*
* <p>
* <p>All the values contained within this configuration will be removed,
* leaving only settings and defaults, and the new values will be loaded
* from the given string.
*
* <p>
* <p>If the string is invalid in any way, an exception will be thrown.
*
* @param contents Contents of a Configuration to load.
@ -143,7 +138,7 @@ public abstract class FileConfiguration extends MemoryConfiguration {
/**
* Compiles the header for this {@link FileConfiguration} and returns the
* result.
*
* <p>
* <p>This will use the header from {@link #options()} -> {@link
* FileConfigurationOptions#header()}, respecting the rules of {@link
* FileConfigurationOptions#copyHeader()} if set.
@ -152,8 +147,7 @@ public abstract class FileConfiguration extends MemoryConfiguration {
*/
protected abstract String buildHeader();
@Override
public FileConfigurationOptions options() {
@Override public FileConfigurationOptions options() {
if (this.options == null) {
this.options = new FileConfigurationOptions(this);
}

View File

@ -16,32 +16,29 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions {
super(configuration);
}
@Override
public FileConfiguration configuration() {
@Override public FileConfiguration configuration() {
return (FileConfiguration) super.configuration();
}
@Override
public FileConfigurationOptions copyDefaults(boolean value) {
@Override public FileConfigurationOptions copyDefaults(boolean value) {
super.copyDefaults(value);
return this;
}
@Override
public FileConfigurationOptions pathSeparator(char value) {
@Override public FileConfigurationOptions pathSeparator(char value) {
super.pathSeparator(value);
return this;
}
/**
* Gets the header that will be applied to the top of the saved output.
*
* <p>
* <p>This header will be commented out and applied directly at the top of
* the generated output of the {@link FileConfiguration}. It is not
* required to include a newline at the end of the header as it will
* automatically be applied, but you may include one if you wish for extra
* spacing.
*
* <p>
* <p>{@code null} is a valid value which will indicate that no header]
* is to be applied. The default value is {@code null}.
*
@ -53,13 +50,13 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions {
/**
* Sets the header that will be applied to the top of the saved output.
*
* <p>
* <p>This header will be commented out and applied directly at the top of
* the generated output of the {@link FileConfiguration}. It is not
* required to include a newline at the end of the header as it will
* automatically be applied, but you may include one if you wish for extra
* spacing.
*
* <p>
* <p>{@code null} is a valid value which will indicate that no header
* is to be applied.
*
@ -73,17 +70,17 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions {
/**
* Gets whether or not the header should be copied from a default source.
*
* <p>
* <p>If this is true, if a default {@link FileConfiguration} is passed to
* {@link FileConfiguration#setDefaults(Configuration)}
* then upon saving it will use the header from that config, instead of
* the one provided here.
*
* <p>
* <p>If no default is set on the configuration, or the default is not of
* type FileConfiguration, or that config has no header ({@link #header()}
* returns null) then the header specified in this configuration will be
* used.
*
* <p>
* <p>Defaults to true.
*
* @return Whether or not to copy the header
@ -94,17 +91,17 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions {
/**
* Sets whether or not the header should be copied from a default source.
*
* <p>
* <p>If this is true, if a default {@link FileConfiguration} is passed to
* {@link FileConfiguration#setDefaults(Configuration)}
* then upon saving it will use the header from that config, instead of
* the one provided here.
*
* <p>
* <p>If no default is set on the configuration, or the default is not of
* type FileConfiguration, or that config has no header ({@link #header()}
* returns null) then the header specified in this configuration will be
* used.
*
* <p>
* <p>Defaults to true.
*
* @param value Whether or not to copy the header

View File

@ -28,11 +28,11 @@ public class YamlConfiguration extends FileConfiguration {
/**
* Creates a new {@link YamlConfiguration}, loading from the given file.
*
* <p>
* <p>Any errors loading the Configuration will be logged and then ignored.
* If the specified input is not a valid config, a blank config will be
* returned.
*
* <p>
* <p>The encoding used may follow the system dependent default.
*
* @param file Input file
@ -64,8 +64,7 @@ public class YamlConfiguration extends FileConfiguration {
return config;
}
@Override
public String saveToString() {
@Override public String saveToString() {
yamlOptions.setIndent(options().indent());
yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
@ -80,8 +79,7 @@ public class YamlConfiguration extends FileConfiguration {
return header + dump;
}
@Override
public void loadFromString(String contents) throws InvalidConfigurationException {
@Override public void loadFromString(String contents) throws InvalidConfigurationException {
Map<?, ?> input;
try {
@ -144,8 +142,7 @@ public class YamlConfiguration extends FileConfiguration {
return result.toString();
}
@Override
protected String buildHeader() {
@Override protected String buildHeader() {
String header = options().header();
if (options().copyHeader()) {
@ -182,8 +179,7 @@ public class YamlConfiguration extends FileConfiguration {
return builder.toString();
}
@Override
public YamlConfigurationOptions options() {
@Override public YamlConfigurationOptions options() {
if (options == null) {
options = new YamlConfigurationOptions(this);
}

View File

@ -11,38 +11,33 @@ public class YamlConfigurationOptions extends FileConfigurationOptions {
super(configuration);
}
@Override
public YamlConfiguration configuration() {
@Override public YamlConfiguration configuration() {
return (YamlConfiguration) super.configuration();
}
@Override
public YamlConfigurationOptions copyDefaults(boolean value) {
@Override public YamlConfigurationOptions copyDefaults(boolean value) {
super.copyDefaults(value);
return this;
}
@Override
public YamlConfigurationOptions pathSeparator(char value) {
@Override public YamlConfigurationOptions pathSeparator(char value) {
super.pathSeparator(value);
return this;
}
@Override
public YamlConfigurationOptions header(String value) {
@Override public YamlConfigurationOptions header(String value) {
super.header(value);
return this;
}
@Override
public YamlConfigurationOptions copyHeader(boolean value) {
@Override public YamlConfigurationOptions copyHeader(boolean value) {
super.copyHeader(value);
return this;
}
/**
* Gets how much spaces should be used to indent each line.
*
* <p>
* <p>The minimum value this may be is 2, and the maximum is 9.
*
* @return How much to indent by
@ -53,7 +48,7 @@ public class YamlConfigurationOptions extends FileConfigurationOptions {
/**
* Sets how much spaces should be used to indent each line.
*
* <p>
* <p>The minimum value this may be is 2, and the maximum is 9.
*
* @param value New indent

View File

@ -16,8 +16,7 @@ public class YamlConstructor extends SafeConstructor {
}
private class ConstructCustomObject extends ConstructYamlMap {
@Override
public Object construct(final Node node) {
@Override public Object construct(final Node node) {
if (node.isTwoStepsConstruction()) {
throw new YAMLException("Unexpected referential mapping structure. Node: " + node);
}
@ -40,8 +39,7 @@ public class YamlConstructor extends SafeConstructor {
return raw;
}
@Override
public void construct2ndStep(final Node node, final Object object) {
@Override public void construct2ndStep(final Node node, final Object object) {
throw new YAMLException("Unexpected referential mapping structure. Node: " + node);
}
}

View File

@ -13,24 +13,25 @@ class YamlRepresenter extends Representer {
YamlRepresenter() {
this.multiRepresenters.put(ConfigurationSection.class, new RepresentConfigurationSection());
this.multiRepresenters.put(ConfigurationSerializable.class, new RepresentConfigurationSerializable());
this.multiRepresenters
.put(ConfigurationSerializable.class, new RepresentConfigurationSerializable());
}
private class RepresentConfigurationSection extends RepresentMap {
@Override
public Node representData(Object data) {
@Override public Node representData(Object data) {
return super.representData(((ConfigurationSection) data).getValues(false));
}
}
private class RepresentConfigurationSerializable extends RepresentMap {
@Override
public Node representData(Object data) {
@Override public Node representData(Object data) {
ConfigurationSerializable serializable = (ConfigurationSerializable) data;
Map<String, Object> values = new LinkedHashMap<>();
values.put(ConfigurationSerialization.SERIALIZED_TYPE_KEY, ConfigurationSerialization.getAlias(serializable.getClass()));
values.put(ConfigurationSerialization.SERIALIZED_TYPE_KEY,
ConfigurationSerialization.getAlias(serializable.getClass()));
values.putAll(serializable.serialize());
return super.representData(values);

View File

@ -24,7 +24,7 @@ public interface ConfigurationSerializable {
/**
* Creates a Map representation of this class.
*
* <p>
* <p>This class must provide a method to restore this class, as defined in
* the {@link ConfigurationSerializable} interface javadoc.
*

View File

@ -17,7 +17,8 @@ import java.util.logging.Logger;
public class ConfigurationSerialization {
public static final String SERIALIZED_TYPE_KEY = "==";
private static final Map<String, Class<? extends ConfigurationSerializable>> aliases = new HashMap<>();
private static final Map<String, Class<? extends ConfigurationSerializable>> aliases =
new HashMap<>();
private final Class<? extends ConfigurationSerializable> clazz;
protected ConfigurationSerialization(Class<? extends ConfigurationSerializable> clazz) {
@ -27,11 +28,11 @@ public class ConfigurationSerialization {
/**
* Attempts to deserialize the given arguments into a new instance of the
* given class.
*
* <p>
* <p>The class must implement {@link ConfigurationSerializable}, including
* the extra methods as specified in the javadoc of
* ConfigurationSerializable.</p>
*
* <p>
* <p>If a new instance could not be made, an example being the class not
* fully implementing the interface, null will be returned.</p>
*
@ -39,19 +40,20 @@ public class ConfigurationSerialization {
* @param clazz Class to deserialize into
* @return New instance of the specified class
*/
public static ConfigurationSerializable deserializeObject(Map<String, ?> args, Class<? extends ConfigurationSerializable> clazz) {
public static ConfigurationSerializable deserializeObject(Map<String, ?> args,
Class<? extends ConfigurationSerializable> clazz) {
return new ConfigurationSerialization(clazz).deserialize(args);
}
/**
* Attempts to deserialize the given arguments into a new instance of the
*
* <p>
* given class.
* <p>
* The class must implement {@link ConfigurationSerializable}, including
* the extra methods as specified in the javadoc of
* ConfigurationSerializable.</p>
*
* <p>
* <p>
* If a new instance could not be made, an example being the class not
* fully implementing the interface, null will be returned.</p>
@ -71,14 +73,16 @@ public class ConfigurationSerialization {
}
clazz = getClassByAlias(alias);
if (clazz == null) {
throw new IllegalArgumentException("Specified class does not exist ('" + alias + "')");
throw new IllegalArgumentException(
"Specified class does not exist ('" + alias + "')");
}
} catch (ClassCastException ex) {
ex.fillInStackTrace();
throw ex;
}
} else {
throw new IllegalArgumentException("Args doesn't contain type key ('" + SERIALIZED_TYPE_KEY + "')");
throw new IllegalArgumentException(
"Args doesn't contain type key ('" + SERIALIZED_TYPE_KEY + "')");
}
return new ConfigurationSerialization(clazz).deserialize(args);
@ -107,7 +111,8 @@ public class ConfigurationSerialization {
* @param alias Alias to register as
* @see SerializableAs
*/
public static void registerClass(Class<? extends ConfigurationSerializable> clazz, String alias) {
public static void registerClass(Class<? extends ConfigurationSerializable> clazz,
String alias) {
aliases.put(alias, clazz);
}
@ -127,7 +132,8 @@ public class ConfigurationSerialization {
* @param clazz Class to unregister
*/
public static void unregisterClass(Class<? extends ConfigurationSerializable> clazz) {
while (aliases.values().remove(clazz)) {}
while (aliases.values().remove(clazz)) {
}
}
/**
@ -195,17 +201,19 @@ public class ConfigurationSerialization {
protected ConfigurationSerializable deserializeViaMethod(Method method, Map<String, ?> args) {
try {
ConfigurationSerializable result = (ConfigurationSerializable) method.invoke(null, args);
ConfigurationSerializable result =
(ConfigurationSerializable) method.invoke(null, args);
if (result == null) {
Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE,
"Could not call method '" + method.toString() + "' of " + this.clazz + " for deserialization: method returned null");
"Could not call method '" + method.toString() + "' of " + this.clazz
+ " for deserialization: method returned null");
} else {
return result;
}
} catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException ex) {
Logger.getLogger(ConfigurationSerialization.class.getName())
.log(Level.SEVERE, "Could not call method '" + method.toString() + "' of " + this.clazz
Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE,
"Could not call method '" + method.toString() + "' of " + this.clazz
+ " for deserialization",
ex instanceof InvocationTargetException ? ex.getCause() : ex);
}
@ -213,12 +221,13 @@ public class ConfigurationSerialization {
return null;
}
protected ConfigurationSerializable deserializeViaCtor(Constructor<? extends ConfigurationSerializable> ctor, Map<String, ?> args) {
protected ConfigurationSerializable deserializeViaCtor(
Constructor<? extends ConfigurationSerializable> ctor, Map<String, ?> args) {
try {
return ctor.newInstance(args);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException ex) {
Logger.getLogger(ConfigurationSerialization.class.getName())
.log(Level.SEVERE, "Could not call constructor '" + ctor.toString() + "' of " + this.clazz
Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE,
"Could not call constructor '" + ctor.toString() + "' of " + this.clazz
+ " for deserialization",
ex instanceof InvocationTargetException ? ex.getCause() : ex);
}

View File

@ -9,8 +9,7 @@ import java.lang.annotation.Target;
* Applies to a {@link ConfigurationSerializable} that will delegate all
* deserialization to another {@link ConfigurationSerializable}.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE)
public @interface DelegateDeserialization {
/**
* Which class should be used as a delegate for this classes

View File

@ -19,9 +19,7 @@ import java.lang.annotation.Target;
*
* @see ConfigurationSerialization#registerClass(Class, String)
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface SerializableAs {
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface SerializableAs {
/**
* This is the name your class will be stored and retrieved as.
* <p>

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