Hows this?

This commit is contained in:
boy0001
2015-09-13 14:04:31 +10:00
parent 1cccdd9d4d
commit 5137b23357
379 changed files with 18471 additions and 28437 deletions

View File

@ -89,32 +89,25 @@ import com.plotsquared.bukkit.uuid.OfflineUUIDWrapper;
import com.plotsquared.bukkit.uuid.SQLUUIDHandler;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
public class BukkitMain extends JavaPlugin implements Listener, IPlotMain
{
public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
public static BukkitMain THIS;
public static WorldEditPlugin worldEdit;
private int[] version;
@Override
public int[] getServerVersion()
{
if (version == null)
{
try
{
public int[] getServerVersion() {
if (version == null) {
try {
version = new int[3];
final String[] split = Bukkit.getBukkitVersion().split("-")[0].split("\\.");
version[0] = Integer.parseInt(split[0]);
version[1] = Integer.parseInt(split[1]);
if (split.length == 3)
{
if (split.length == 3) {
version[2] = Integer.parseInt(split[2]);
}
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
PS.debug(StringMan.getString(Bukkit.getBukkitVersion()));
PS.debug(StringMan.getString(Bukkit.getBukkitVersion().split("-")[0].split("\\.")));
@ -123,118 +116,97 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain
}
return version;
}
@Override
public void onEnable()
{
public void onEnable() {
THIS = this;
PS.instance = new PS(this, "Bukkit");
}
@Override
public void onDisable()
{
public void onDisable() {
PS.get().disable();
Bukkit.getScheduler().cancelTasks(this);
THIS = null;
}
@Override
public void log(String message)
{
if (message == null) { return; }
if ((THIS != null) && (Bukkit.getServer().getConsoleSender() != null))
{
try
{
public void log(String message) {
if (message == null) {
return;
}
if ((THIS != null) && (Bukkit.getServer().getConsoleSender() != null)) {
try {
message = C.color(message);
if (!Settings.CONSOLE_COLOR)
{
if (!Settings.CONSOLE_COLOR) {
message = ChatColor.stripColor(message);
}
Bukkit.getServer().getConsoleSender().sendMessage(message);
return;
}
catch (final Throwable e)
{}
} catch (final Throwable e) {}
}
System.out.println(ConsoleColors.fromString(message));
}
@Override
public void disable()
{
if (THIS != null)
{
public void disable() {
if (THIS != null) {
onDisable();
}
}
@Override
public int[] getPluginVersion()
{
public int[] getPluginVersion() {
final String[] split = getDescription().getVersion().split("\\.");
return new int[] { Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]) };
}
@Override
public void registerCommands()
{
public void registerCommands() {
final BukkitCommand bcmd = new BukkitCommand();
final PluginCommand plotCommand = getCommand("plots");
plotCommand.setExecutor(bcmd);
plotCommand.setAliases(Arrays.asList("p", "ps", "plotme", "plot"));
plotCommand.setTabCompleter(bcmd);
}
@Override
public File getDirectory()
{
public File getDirectory() {
return getDataFolder();
}
@Override
public File getWorldContainer() {
return Bukkit.getWorldContainer();
}
@Override
public TaskManager getTaskManager()
{
public TaskManager getTaskManager() {
return new BukkitTaskManager();
}
@Override
public void runEntityTask()
{
public void runEntityTask() {
log(C.PREFIX.s() + "KillAllEntities started.");
TaskManager.runTaskRepeat(new Runnable()
{
TaskManager.runTaskRepeat(new Runnable() {
long ticked = 0l;
long error = 0l;
@Override
public void run()
{
if (ticked > 36_000L)
{
public void run() {
if (ticked > 36_000L) {
ticked = 0l;
if (error > 0)
{
if (error > 0) {
log(C.PREFIX.s() + "KillAllEntities has been running for 6 hours. Errors: " + error);
}
error = 0l;
}
World world;
for (final PlotWorld pw : PS.get().getPlotWorldObjects())
{
for (final PlotWorld pw : PS.get().getPlotWorldObjects()) {
world = Bukkit.getWorld(pw.worldname);
try
{
for (final Entity entity : world.getEntities())
{
switch (entity.getType())
{
try {
for (final Entity entity : world.getEntities()) {
switch (entity.getType()) {
case EGG:
case ENDER_CRYSTAL:
case COMPLEX_PART:
@ -250,8 +222,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain
case UNKNOWN:
case ITEM_FRAME:
case PAINTING:
case PLAYER:
{
case PLAYER: {
// non moving / unremovable
continue;
}
@ -259,8 +230,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain
case SPLASH_POTION:
case SNOWBALL:
case ENDER_PEARL:
case ARROW:
{
case ARROW: {
// managed elsewhere | projectile
continue;
}
@ -271,29 +241,24 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain
case MINECART_HOPPER:
case MINECART_MOB_SPAWNER:
case MINECART_TNT:
case BOAT:
{
if (!Settings.KILL_ROAD_VEHICLES)
{
case BOAT: {
if (!Settings.KILL_ROAD_VEHICLES) {
continue;
}
final Location loc = entity.getLocation();
if (MainUtil.isPlotRoad(BukkitUtil.getLocation(loc)))
{
if (MainUtil.isPlotRoad(BukkitUtil.getLocation(loc))) {
entity.remove();
}
break;
}
case SMALL_FIREBALL:
case FIREBALL:
case DROPPED_ITEM:
{
case DROPPED_ITEM: {
// dropped item
continue;
}
case PRIMED_TNT:
case FALLING_BLOCK:
{
case FALLING_BLOCK: {
// managed elsewhere
continue;
}
@ -329,18 +294,14 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain
case WITHER:
case WOLF:
case ZOMBIE:
default:
{
if (!Settings.KILL_ROAD_MOBS)
{
default: {
if (!Settings.KILL_ROAD_MOBS) {
continue;
}
final Location loc = entity.getLocation();
if (MainUtil.isPlotRoad(BukkitUtil.getLocation(loc)))
{
if (MainUtil.isPlotRoad(BukkitUtil.getLocation(loc))) {
final Entity passenger = entity.getPassenger();
if (!(passenger instanceof Player))
{
if (!(passenger instanceof Player)) {
entity.remove();
}
}
@ -348,143 +309,111 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain
}
}
}
}
catch (final Throwable e)
{
} catch (final Throwable e) {
++error;
}
finally
{
} finally {
++ticked;
}
}
}
}, 20);
}
@Override
final public ChunkGenerator getDefaultWorldGenerator(final String world, final String id)
{
final public ChunkGenerator getDefaultWorldGenerator(final String world, final String id) {
WorldEvents.lastWorld = world;
if (!PS.get().setupPlotWorld(world, id)) { return null; }
if (!PS.get().setupPlotWorld(world, id)) {
return null;
}
final HybridGen result = new HybridGen(world);
TaskManager.runTaskLater(new Runnable()
{
TaskManager.runTaskLater(new Runnable() {
@Override
public void run()
{
if ((WorldEvents.lastWorld != null) && WorldEvents.lastWorld.equals(world))
{
public void run() {
if ((WorldEvents.lastWorld != null) && WorldEvents.lastWorld.equals(world)) {
WorldEvents.lastWorld = null;
}
}
}, 20);
return result;
}
@Override
public void registerPlayerEvents()
{
public void registerPlayerEvents() {
getServer().getPluginManager().registerEvents(new PlayerEvents(), this);
if (PS.get().checkVersion(getServerVersion(), 1, 8, 0))
{
if (PS.get().checkVersion(getServerVersion(), 1, 8, 0)) {
getServer().getPluginManager().registerEvents(new PlayerEvents_1_8(), this);
}
if (PS.get().checkVersion(getServerVersion(), 1, 8, 3))
{
if (PS.get().checkVersion(getServerVersion(), 1, 8, 3)) {
getServer().getPluginManager().registerEvents(new PlayerEvents_1_8_3(), this);
}
}
@Override
public void registerInventoryEvents()
{
public void registerInventoryEvents() {
// Part of PlayerEvents - can be moved if necessary
}
@Override
public void registerPlotPlusEvents()
{
public void registerPlotPlusEvents() {
PlotPlusListener.startRunnable(this);
getServer().getPluginManager().registerEvents(new PlotPlusListener(), this);
}
@Override
public void registerForceFieldEvents()
{
public void registerForceFieldEvents() {
getServer().getPluginManager().registerEvents(new ForceFieldListener(), this);
}
@Override
public boolean initWorldEdit()
{
if (getServer().getPluginManager().getPlugin("WorldEdit") != null)
{
public boolean initWorldEdit() {
if (getServer().getPluginManager().getPlugin("WorldEdit") != null) {
BukkitMain.worldEdit = (WorldEditPlugin) getServer().getPluginManager().getPlugin("WorldEdit");
final String version = BukkitMain.worldEdit.getDescription().getVersion();
if ((version != null) && version.startsWith("5."))
{
if ((version != null) && version.startsWith("5.")) {
log("&cThis version of WorldEdit does not support PlotSquared.");
log("&cPlease use WorldEdit 6+ for masking support");
log("&c - http://builds.enginehub.org/job/worldedit");
}
else
{
} else {
getServer().getPluginManager().registerEvents(new WEListener(), this);
return true;
}
}
return false;
}
@Override
public EconHandler getEconomyHandler()
{
try
{
public EconHandler getEconomyHandler() {
try {
final BukkitEconHandler econ = new BukkitEconHandler();
if (econ.init()) { return econ; }
}
catch (final Throwable e)
{}
if (econ.init()) {
return econ;
}
} catch (final Throwable e) {}
return null;
}
@Override
public BlockManager initBlockManager()
{
if (PS.get().checkVersion(getServerVersion(), 1, 8, 0))
{
try
{
public BlockManager initBlockManager() {
if (PS.get().checkVersion(getServerVersion(), 1, 8, 0)) {
try {
BukkitSetBlockManager.setBlockManager = new SetBlockFast_1_8();
}
catch (final Throwable e)
{
} catch (final Throwable e) {
e.printStackTrace();
BukkitSetBlockManager.setBlockManager = new SetBlockSlow();
}
try
{
try {
new SendChunk();
MainUtil.canSendChunk = true;
}
catch (final Throwable e)
{
} catch (final Throwable e) {
e.printStackTrace();
MainUtil.canSendChunk = false;
}
}
else
{
try
{
} else {
try {
BukkitSetBlockManager.setBlockManager = new SetBlockFast();
}
catch (final Throwable e)
{
} catch (final Throwable e) {
MainUtil.canSetFast = false;
BukkitSetBlockManager.setBlockManager = new SetBlockSlow();
}
@ -492,15 +421,12 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain
BlockUpdateUtil.setBlockManager = BukkitSetBlockManager.setBlockManager;
return BlockManager.manager = new BukkitUtil();
}
@Override
public boolean initPlotMeConverter()
{
TaskManager.runTaskLaterAsync(new Runnable()
{
public boolean initPlotMeConverter() {
TaskManager.runTaskLaterAsync(new Runnable() {
@Override
public void run()
{
public void run() {
if (new LikePlotMeConverter("PlotMe").run(new ClassicPlotMeConnector())) {
return;
}
@ -514,181 +440,140 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain
}, 20);
return (Bukkit.getPluginManager().getPlugin("PlotMe") != null) || (Bukkit.getPluginManager().getPlugin("AthionPlots") != null);
}
@Override
public BukkitGeneratorWrapper getGenerator(final String world, final String name)
{
if (name == null) { return new BukkitGeneratorWrapper(world, null); }
public BukkitGeneratorWrapper getGenerator(final String world, final String name) {
if (name == null) {
return new BukkitGeneratorWrapper(world, null);
}
final Plugin gen_plugin = Bukkit.getPluginManager().getPlugin(name);
ChunkGenerator gen;
if ((gen_plugin != null) && gen_plugin.isEnabled())
{
if ((gen_plugin != null) && gen_plugin.isEnabled()) {
gen = gen_plugin.getDefaultWorldGenerator(world, "");
}
else
{
} else {
gen = new HybridGen(world);
}
return new BukkitGeneratorWrapper(world, gen);
}
@Override
public HybridUtils initHybridUtils()
{
public HybridUtils initHybridUtils() {
return new BukkitHybridUtils();
}
@Override
public SetupUtils initSetupUtils()
{
public SetupUtils initSetupUtils() {
return new BukkitSetupUtils();
}
@Override
public UUIDHandlerImplementation initUUIDHandler()
{
public UUIDHandlerImplementation initUUIDHandler() {
final boolean checkVersion = PS.get().checkVersion(getServerVersion(), 1, 7, 6);
UUIDWrapper wrapper;
if (Settings.OFFLINE_MODE)
{
if (Settings.UUID_LOWERCASE)
{
if (Settings.OFFLINE_MODE) {
if (Settings.UUID_LOWERCASE) {
wrapper = (new LowerOfflineUUIDWrapper());
}
else
{
} else {
wrapper = (new OfflineUUIDWrapper());
}
Settings.OFFLINE_MODE = true;
}
else if (checkVersion)
{
} else if (checkVersion) {
wrapper = (new DefaultUUIDWrapper());
Settings.OFFLINE_MODE = false;
}
else
{
if (Settings.UUID_LOWERCASE)
{
} else {
if (Settings.UUID_LOWERCASE) {
wrapper = (new LowerOfflineUUIDWrapper());
}
else
{
} else {
wrapper = (new OfflineUUIDWrapper());
}
Settings.OFFLINE_MODE = true;
}
if (!checkVersion)
{
if (!checkVersion) {
log(C.PREFIX.s() + " &c[WARN] Titles are disabled - please update your version of Bukkit to support this feature.");
Settings.TITLES = false;
FlagManager.removeFlag(FlagManager.getFlag("titles"));
}
else
{
} else {
AbstractTitle.TITLE_CLASS = new DefaultTitle();
if (wrapper instanceof DefaultUUIDWrapper)
{
if (wrapper instanceof DefaultUUIDWrapper) {
Settings.TWIN_MODE_UUID = true;
}
else if ((wrapper.getClass() == OfflineUUIDWrapper.class) && !Bukkit.getOnlineMode())
{
} else if ((wrapper.getClass() == OfflineUUIDWrapper.class) && !Bukkit.getOnlineMode()) {
Settings.TWIN_MODE_UUID = true;
}
}
if (Settings.OFFLINE_MODE)
{
if (Settings.OFFLINE_MODE) {
log(C.PREFIX.s() + " &6PlotSquared is using Offline Mode UUIDs either because of user preference, or because you are using an old version of Bukkit");
}
else
{
} else {
log(C.PREFIX.s() + " &6PlotSquared is using online UUIDs");
}
return Settings.USE_SQLUUIDHANDLER ? new SQLUUIDHandler(wrapper) : new FileUUIDHandler(wrapper);
}
@Override
public ChunkManager initChunkManager()
{
public ChunkManager initChunkManager() {
return new BukkitChunkManager();
}
@Override
public EventUtil initEventUtil()
{
public EventUtil initEventUtil() {
return new BukkitEventUtil();
}
@Override
public void registerTNTListener()
{
public void registerTNTListener() {
getServer().getPluginManager().registerEvents(new TNTListener(), this);
}
@Override
public void unregister(final PlotPlayer player)
{
public void unregister(final PlotPlayer player) {
BukkitUtil.removePlayer(player.getName());
}
@Override
public void registerChunkProcessor()
{
public void registerChunkProcessor() {
getServer().getPluginManager().registerEvents(new ChunkListener(), this);
}
@Override
public void registerWorldEvents()
{
public void registerWorldEvents() {
getServer().getPluginManager().registerEvents(new WorldEvents(), this);
}
@Override
public InventoryUtil initInventoryUtil()
{
public InventoryUtil initInventoryUtil() {
return new BukkitInventoryUtil();
}
@Override
public String getServerName()
{
public String getServerName() {
return Bukkit.getServerName();
}
@Override
public void startMetrics()
{
try
{
public void startMetrics() {
try {
final Metrics metrics = new Metrics(this);
metrics.start();
log(C.PREFIX.s() + "&6Metrics enabled.");
}
catch (final Exception e)
{
} catch (final Exception e) {
log(C.PREFIX.s() + "&cFailed to load up metrics.");
}
}
@Override
public void setGenerator(final String worldname)
{
public void setGenerator(final String worldname) {
World world = BukkitUtil.getWorld(worldname);
if (world == null)
{
if (world == null) {
// create world
final ConfigurationSection worldConfig = PS.get().config.getConfigurationSection("worlds." + worldname);
String manager = worldConfig.getString("generator.plugin");
if (manager == null)
{
if (manager == null) {
manager = "PlotSquared";
}
String generator = worldConfig.getString("generator.init");
if (generator == null)
{
if (generator == null) {
generator = manager;
}
final int type = worldConfig.getInt("generator.type");
final int terrain = worldConfig.getInt("generator.terrain");
final SetupObject setup = new SetupObject();
@ -699,109 +584,82 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain
setup.step = new ConfigurationNode[0];
setup.world = worldname;
SetupUtils.manager.setupWorld(setup);
}
else
{
try
{
if (!PS.get().isPlotWorld(worldname))
{
} else {
try {
if (!PS.get().isPlotWorld(worldname)) {
SetGenCB.setGenerator(BukkitUtil.getWorld(worldname));
}
}
catch (final Exception e)
{
} catch (final Exception e) {
log("Failed to reload world: " + world);
Bukkit.getServer().unloadWorld(world, false);
}
}
world = Bukkit.getWorld(worldname);
final ChunkGenerator gen = world.getGenerator();
if (gen instanceof BukkitPlotGenerator)
{
if (gen instanceof BukkitPlotGenerator) {
PS.get().loadWorld(worldname, new BukkitGeneratorWrapper(worldname, gen));
}
else
{
if (PS.get().config.contains("worlds." + worldname))
{
} else {
if (PS.get().config.contains("worlds." + worldname)) {
PS.get().loadWorld(worldname, new BukkitGeneratorWrapper(worldname, null));
}
}
}
@Override
public SchematicHandler initSchematicHandler()
{
public SchematicHandler initSchematicHandler() {
return new BukkitSchematicHandler();
}
@Override
public AbstractTitle initTitleManager()
{
public AbstractTitle initTitleManager() {
// Already initialized in UUID handler
return AbstractTitle.TITLE_CLASS;
}
@Override
public PlotPlayer wrapPlayer(final Object obj)
{
if (obj instanceof Player)
{
public PlotPlayer wrapPlayer(final Object obj) {
if (obj instanceof Player) {
return BukkitUtil.getPlayer((Player) obj);
}
else if (obj instanceof OfflinePlayer)
{
} else if (obj instanceof OfflinePlayer) {
return BukkitUtil.getPlayer((OfflinePlayer) obj);
}
else if (obj instanceof String)
{
} else if (obj instanceof String) {
return UUIDHandler.getPlayer((String) obj);
} else if (obj instanceof UUID) {
return UUIDHandler.getPlayer((UUID) obj);
}
else if (obj instanceof UUID) { return UUIDHandler.getPlayer((UUID) obj); }
return null;
}
@Override
public String getNMSPackage()
{
public String getNMSPackage() {
final Server server = Bukkit.getServer();
final Class<?> bukkitServerClass = server.getClass();
String[] pas = bukkitServerClass.getName().split("\\.");
if (pas.length == 5)
{
if (pas.length == 5) {
final String verB = pas[3];
return verB;
}
try
{
try {
final Method getHandle = bukkitServerClass.getDeclaredMethod("getHandle");
final Object handle = getHandle.invoke(server);
final Class handleServerClass = handle.getClass();
pas = handleServerClass.getName().split("\\.");
if (pas.length == 5)
{
if (pas.length == 5) {
final String verM = pas[3];
return verM;
}
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
}
PS.debug("Unknown NMS package: " + StringMan.getString(pas));
return "1_8_R3";
}
@Override
public ChatManager<?> initChatManager()
{
if (Settings.FANCY_CHAT)
{
public ChatManager<?> initChatManager() {
if (Settings.FANCY_CHAT) {
return new BukkitChatManager();
}
else
{
} else {
return new BukkitPlainChatManager();
}
}

View File

@ -16,62 +16,58 @@ import org.apache.commons.lang.Validate;
* @param <E> The type of elements in the array.
* @see Arrays
*/
public final class ArrayWrapper<E>
{
public final class ArrayWrapper<E> {
/**
* Creates an array wrapper with some elements.
* @param elements The elements of the array.
*/
public ArrayWrapper(final E... elements)
{
public ArrayWrapper(final E... elements) {
setArray(elements);
}
private E[] _array;
/**
* Retrieves a reference to the wrapped array instance.
* @return The array wrapped by this instance.
*/
public E[] getArray()
{
public E[] getArray() {
return _array;
}
/**
* Set this wrapper to wrap a new array instance.
* @param array The new wrapped array.
*/
public void setArray(final E[] array)
{
public void setArray(final E[] array) {
Validate.notNull(array, "The array must not be null.");
_array = array;
}
/**
* Determines if this object has a value equivalent to another object.
* @see Arrays#equals(Object[], Object[])
*/
@SuppressWarnings("rawtypes")
@Override
public boolean equals(final Object other)
{
if (!(other instanceof ArrayWrapper)) { return false; }
public boolean equals(final Object other) {
if (!(other instanceof ArrayWrapper)) {
return false;
}
return Arrays.equals(_array, ((ArrayWrapper) other)._array);
}
/**
* Gets the hash code represented by this objects value.
* @see Arrays#hashCode(Object[])
* @return This object's hash code.
*/
@Override
public int hashCode()
{
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.
@ -80,31 +76,26 @@ public final class ArrayWrapper<E>
* @return An array of elements in the specified iterable.
*/
@SuppressWarnings("unchecked")
public static <T> T[] toArray(final Iterable<? extends T> list, final Class<T> c)
{
public static <T> T[] toArray(final Iterable<? extends T> list, final Class<T> c) {
int size = -1;
if (list instanceof Collection<?>)
{
if (list instanceof Collection<?>) {
@SuppressWarnings("rawtypes")
final Collection coll = (Collection) list;
size = coll.size();
}
if (size < 0)
{
if (size < 0) {
size = 0;
// Ugly hack: Count it ourselves
for (@SuppressWarnings("unused")
final T element : list)
{
final T element : list) {
size++;
}
}
final T[] result = (T[]) Array.newInstance(c, size);
int i = 0;
for (final T element : list)
{ // Assumes iteration order is consistent
for (final T element : list) { // Assumes iteration order is consistent
result[i++] = element; // Assign array element at index THEN increment counter
}
return result;

File diff suppressed because it is too large Load Diff

View File

@ -7,14 +7,13 @@ import com.google.gson.stream.JsonWriter;
/**
* Represents an object that can be serialized to a JSON writer instance.
*/
interface JsonRepresentedObject
{
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.
*/
void writeJson(final JsonWriter writer) throws IOException;
}

View File

@ -12,43 +12,36 @@ import com.intellectualcrafters.configuration.serialization.ConfigurationSeriali
* Writes by this object will not write name values nor begin/end objects in the JSON stream.
* All writes merely write the represented string value.
*/
final class JsonString implements JsonRepresentedObject, ConfigurationSerializable
{
final class JsonString implements JsonRepresentedObject, ConfigurationSerializable {
private final String _value;
public JsonString(final CharSequence value)
{
public JsonString(final CharSequence value) {
_value = value == null ? null : value.toString();
}
@Override
public void writeJson(final JsonWriter writer) throws IOException
{
public void writeJson(final JsonWriter writer) throws IOException {
writer.value(getValue());
}
public String getValue()
{
public String getValue() {
return _value;
}
@Override
public Map<String, Object> serialize()
{
public Map<String, Object> serialize() {
final HashMap<String, Object> theSingleValue = new HashMap<String, Object>();
theSingleValue.put("stringValue", _value);
return theSingleValue;
}
public static JsonString deserialize(final Map<String, Object> map)
{
public static JsonString deserialize(final Map<String, Object> map) {
return new JsonString(map.get("stringValue").toString());
}
@Override
public String toString()
{
public String toString() {
return _value;
}
}

View File

@ -18,67 +18,54 @@ import com.intellectualcrafters.configuration.serialization.ConfigurationSeriali
/**
* Internal class: Represents a component of a JSON-serializable {@link FancyMessage}.
*/
final class MessagePart implements JsonRepresentedObject, ConfigurationSerializable, Cloneable
{
final class MessagePart implements JsonRepresentedObject, ConfigurationSerializable, Cloneable {
ChatColor color = ChatColor.WHITE;
ArrayList<ChatColor> styles = new ArrayList<ChatColor>();
String clickActionName = null, clickActionData = null,
hoverActionName = null;
String clickActionName = null, clickActionData = null, hoverActionName = null;
JsonRepresentedObject hoverActionData = null;
TextualComponent text = null;
String insertionData = null;
ArrayList<JsonRepresentedObject> translationReplacements = new ArrayList<JsonRepresentedObject>();
MessagePart(final TextualComponent text)
{
MessagePart(final TextualComponent text) {
this.text = text;
}
MessagePart()
{
MessagePart() {
text = null;
}
boolean hasText()
{
boolean hasText() {
return text != null;
}
@Override
@SuppressWarnings("unchecked")
public MessagePart clone() throws CloneNotSupportedException
{
public MessagePart clone() throws CloneNotSupportedException {
final MessagePart obj = (MessagePart) super.clone();
obj.styles = (ArrayList<ChatColor>) styles.clone();
if (hoverActionData instanceof JsonString)
{
if (hoverActionData instanceof JsonString) {
obj.hoverActionData = new JsonString(((JsonString) hoverActionData).getValue());
}
else if (hoverActionData instanceof FancyMessage)
{
} 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
{
static {
final ImmutableBiMap.Builder<ChatColor, String> builder = ImmutableBiMap.builder();
for (final ChatColor style : ChatColor.values())
{
if (!style.isFormat())
{
for (final ChatColor style : ChatColor.values()) {
if (!style.isFormat()) {
continue;
}
String styleName;
switch (style)
{
switch (style) {
case MAGIC:
styleName = "obfuscated";
break;
@ -89,65 +76,47 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa
styleName = style.name().toLowerCase();
break;
}
builder.put(style, styleName);
}
stylesToNames = builder.build();
}
@Override
public void writeJson(final JsonWriter json)
{
try
{
public void writeJson(final JsonWriter json) {
try {
json.beginObject();
text.writeJson(json);
json.name("color").value(color.name().toLowerCase());
for (final ChatColor style : styles)
{
for (final ChatColor style : styles) {
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();
if ((clickActionName != null) && (clickActionData != null)) {
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)
.name("value");
if ((hoverActionName != null) && (hoverActionData != null)) {
json.name("hoverEvent").beginObject().name("action").value(hoverActionName).name("value");
hoverActionData.writeJson(json);
json.endObject();
}
if (insertionData != null)
{
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 (final JsonRepresentedObject obj : translationReplacements)
{
for (final JsonRepresentedObject obj : translationReplacements) {
obj.writeJson(json);
}
json.endArray();
}
json.endObject();
}
catch (final IOException e)
{
} catch (final IOException e) {
Bukkit.getLogger().log(Level.WARNING, "A problem occured during writing of JSON string", e);
}
}
@Override
public Map<String, Object> serialize()
{
public Map<String, Object> serialize() {
final HashMap<String, Object> map = new HashMap<String, Object>();
map.put("text", text);
map.put("styles", styles);
@ -160,10 +129,9 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa
map.put("translationReplacements", translationReplacements);
return map;
}
@SuppressWarnings("unchecked")
public static MessagePart deserialize(final Map<String, Object> serialized)
{
public static MessagePart deserialize(final Map<String, Object> serialized) {
final MessagePart part = new MessagePart((TextualComponent) serialized.get("text"));
part.styles = (ArrayList<ChatColor>) serialized.get("styles");
part.color = ChatColor.getByChar(serialized.get("color").toString());
@ -175,10 +143,9 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa
part.translationReplacements = (ArrayList<JsonRepresentedObject>) serialized.get("translationReplacements");
return part;
}
static
{
static {
ConfigurationSerialization.registerClass(MessagePart.class);
}
}

View File

@ -12,37 +12,32 @@ import org.bukkit.Bukkit;
* A class containing static utility methods and caches which are intended as reflective conveniences.
* Unless otherwise noted, upon failure methods will return {@code null}.
*/
public final class Reflection
{
public final class Reflection {
private static String _versionString;
private Reflection()
{
private Reflection() {
}
/**
* Gets the version string from the package name of the CraftBukkit server implementation.
* This is needed to bypass the JAR package name changing on each update.
* @return The version string of the OBC and NMS packages, <em>including the trailing dot</em>.
*/
public synchronized static String getVersion()
{
if (_versionString == null)
{
if (Bukkit.getServer() == null)
{
public synchronized static String getVersion() {
if (_versionString == null) {
if (Bukkit.getServer() == null) {
// The server hasn't started, static initializer call?
return null;
}
final String name = Bukkit.getServer().getClass().getPackage().getName();
_versionString = name.substring(name.lastIndexOf('.') + 1) + ".";
}
return _versionString;
}
/**
* Stores loaded classes from the {@code net.minecraft.server} package.
*/
@ -51,25 +46,23 @@ public final class Reflection
* Stores loaded classes from the {@code org.bukkit.craftbukkit} package (and subpackages).
*/
private static final Map<String, Class<?>> _loadedOBCClasses = new HashMap<String, Class<?>>();
/**
* Gets a {@link Class} object representing a type contained within the {@code net.minecraft.server} versioned package.
* The class instances returned by this method are cached, such that no lookup will be done twice (unless multiple threads are accessing this method simultaneously).
* @param className The name of the class, excluding the package, within NMS.
* @return The class instance representing the specified NMS class, or {@code null} if it could not be loaded.
*/
public synchronized static Class<?> getNMSClass(final String className)
{
if (_loadedNMSClasses.containsKey(className)) { return _loadedNMSClasses.get(className); }
public synchronized static Class<?> getNMSClass(final String className) {
if (_loadedNMSClasses.containsKey(className)) {
return _loadedNMSClasses.get(className);
}
final String fullName = "net.minecraft.server." + getVersion() + className;
Class<?> clazz = null;
try
{
try {
clazz = Class.forName(fullName);
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
_loadedNMSClasses.put(className, null);
return null;
@ -77,25 +70,23 @@ public final class Reflection
_loadedNMSClasses.put(className, clazz);
return clazz;
}
/**
* Gets a {@link Class} object representing a type contained within the {@code org.bukkit.craftbukkit} versioned package.
* The class instances returned by this method are cached, such that no lookup will be done twice (unless multiple threads are accessing this method simultaneously).
* @param className The name of the class, excluding the package, within OBC. This name may contain a subpackage name, such as {@code inventory.CraftItemStack}.
* @return The class instance representing the specified OBC class, or {@code null} if it could not be loaded.
*/
public synchronized static Class<?> getOBCClass(final String className)
{
if (_loadedOBCClasses.containsKey(className)) { return _loadedOBCClasses.get(className); }
public synchronized static Class<?> getOBCClass(final String className) {
if (_loadedOBCClasses.containsKey(className)) {
return _loadedOBCClasses.get(className);
}
final String fullName = "org.bukkit.craftbukkit." + getVersion() + className;
Class<?> clazz = null;
try
{
try {
clazz = Class.forName(fullName);
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
_loadedOBCClasses.put(className, null);
return null;
@ -103,7 +94,7 @@ public final class Reflection
_loadedOBCClasses.put(className, clazz);
return clazz;
}
/**
* Attempts to get the NMS handle of a CraftBukkit object.
* <p>
@ -112,21 +103,17 @@ 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(final Object obj)
{
try
{
public synchronized static Object getHandle(final Object obj) {
try {
return getMethod(obj.getClass(), "getHandle").invoke(obj);
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
return null;
}
}
private static final Map<Class<?>, Map<String, Field>> _loadedFields = new HashMap<Class<?>, Map<String, Field>>();
/**
* Retrieves a {@link Field} instance declared by the specified class with the specified name.
* Java access modifiers are ignored during this retrieval. No guarantee is made as to whether the field
@ -144,32 +131,24 @@ public final class Reflection
* @return A field object with the specified name declared by the specified class.
* @see Class#getDeclaredField(String)
*/
public synchronized static Field getField(final Class<?> clazz, final String name)
{
public synchronized static Field getField(final Class<?> clazz, final String name) {
Map<String, Field> loaded;
if (!_loadedFields.containsKey(clazz))
{
if (!_loadedFields.containsKey(clazz)) {
loaded = new HashMap<String, Field>();
_loadedFields.put(clazz, loaded);
}
else
{
} else {
loaded = _loadedFields.get(clazz);
}
if (loaded.containsKey(name))
{
if (loaded.containsKey(name)) {
// If the field is loaded (or cached as not existing), return the relevant value, which might be null
return loaded.get(name);
}
try
{
try {
final Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
loaded.put(name, field);
return field;
}
catch (final Exception e)
{
} catch (final Exception e) {
// Error loading
e.printStackTrace();
// Cache field as not existing
@ -177,13 +156,13 @@ public final class Reflection
return null;
}
}
/**
* 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<Class<?>, Map<String, Map<ArrayWrapper<Class<?>>, Method>>>();
/**
* Retrieves a {@link Method} instance declared by the specified class with the specified name and argument types.
* Java access modifiers are ignored during this retrieval. No guarantee is made as to whether the field
@ -204,28 +183,24 @@ public final class Reflection
* @param args The formal argument types of the method.
* @return A method object with the specified name declared by the specified class.
*/
public synchronized static Method getMethod(final Class<?> clazz, final String name,
final Class<?>... args)
{
if (!_loadedMethods.containsKey(clazz))
{
public synchronized static Method getMethod(final Class<?> clazz, final String name, final Class<?>... args) {
if (!_loadedMethods.containsKey(clazz)) {
_loadedMethods.put(clazz, new HashMap<String, Map<ArrayWrapper<Class<?>>, Method>>());
}
final Map<String, Map<ArrayWrapper<Class<?>>, Method>> loadedMethodNames = _loadedMethods.get(clazz);
if (!loadedMethodNames.containsKey(name))
{
if (!loadedMethodNames.containsKey(name)) {
loadedMethodNames.put(name, new HashMap<ArrayWrapper<Class<?>>, Method>());
}
final Map<ArrayWrapper<Class<?>>, Method> loadedSignatures = loadedMethodNames.get(name);
final ArrayWrapper<Class<?>> wrappedArg = new ArrayWrapper<Class<?>>(args);
if (loadedSignatures.containsKey(wrappedArg)) { return loadedSignatures.get(wrappedArg); }
for (final Method m : clazz.getMethods())
{
if (m.getName().equals(name) && Arrays.equals(args, m.getParameterTypes()))
{
if (loadedSignatures.containsKey(wrappedArg)) {
return loadedSignatures.get(wrappedArg);
}
for (final Method m : clazz.getMethods()) {
if (m.getName().equals(name) && Arrays.equals(args, m.getParameterTypes())) {
m.setAccessible(true);
loadedSignatures.put(wrappedArg, m);
return m;
@ -234,5 +209,5 @@ public final class Reflection
loadedSignatures.put(wrappedArg, null);
return null;
}
}

View File

@ -16,38 +16,35 @@ import com.intellectualcrafters.configuration.serialization.ConfigurationSeriali
* but also to represent localized strings and other text values.
* <p>Different instances of this class can be created with static constructor methods.</p>
*/
public abstract class TextualComponent implements Cloneable
{
static
{
public abstract class TextualComponent implements Cloneable {
static {
ConfigurationSerialization.registerClass(TextualComponent.ArbitraryTextTypeComponent.class);
ConfigurationSerialization.registerClass(TextualComponent.ComplexTextTypeComponent.class);
}
@Override
public String toString()
{
public String toString() {
return getReadableString();
}
/**
* @return The JSON key used to represent text components of this type.
*/
public abstract String getKey();
/**
* @return A readable String
*/
public abstract String getReadableString();
/**
* 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;
/**
* Writes the text data represented by this textual component to the specified JSON writer object.
* A new object within the writer is not started.
@ -55,220 +52,183 @@ public abstract class TextualComponent implements Cloneable
* @throws IOException If an error occurs while writing to the stream.
*/
public abstract void writeJson(final JsonWriter writer) throws IOException;
static TextualComponent deserialize(final Map<String, Object> map)
{
if (map.containsKey("key") && (map.size() == 2) && map.containsKey("value"))
{
static TextualComponent deserialize(final Map<String, Object> map) {
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);
}
return null;
}
static boolean isTextKey(final String key)
{
static boolean isTextKey(final String key) {
return key.equals("translate") || key.equals("text") || key.equals("score") || key.equals("selector");
}
static boolean isTranslatableText(final TextualComponent component)
{
static boolean isTranslatableText(final TextualComponent component) {
return (component instanceof ComplexTextTypeComponent) && ((ComplexTextTypeComponent) component).getKey().equals("translate");
}
/**
* 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
{
public ArbitraryTextTypeComponent(final String key, final String value)
{
private static final class ArbitraryTextTypeComponent extends TextualComponent implements ConfigurationSerializable {
public ArbitraryTextTypeComponent(final String key, final String value) {
setKey(key);
setValue(value);
}
@Override
public String getKey()
{
public String getKey() {
return _key;
}
public void setKey(final String key)
{
public void setKey(final String key) {
Preconditions.checkArgument((key != null) && !key.isEmpty(), "The key must be specified.");
_key = key;
}
public String getValue()
{
public String getValue() {
return _value;
}
public void setValue(final String value)
{
public void setValue(final String value) {
Preconditions.checkArgument(value != null, "The value must be specified.");
_value = value;
}
private String _key;
private String _value;
@Override
public TextualComponent clone() throws CloneNotSupportedException
{
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(final JsonWriter writer) throws IOException
{
public void writeJson(final JsonWriter writer) throws IOException {
writer.name(getKey()).value(getValue());
}
@Override
@SuppressWarnings("serial")
public Map<String, Object> serialize()
{
return new HashMap<String, Object>()
{
public Map<String, Object> serialize() {
return new HashMap<String, Object>() {
{
put("key", getKey());
put("value", getValue());
}
};
}
public static ArbitraryTextTypeComponent deserialize(final Map<String, Object> map)
{
public static ArbitraryTextTypeComponent deserialize(final Map<String, Object> map) {
return new ArbitraryTextTypeComponent(map.get("key").toString(), map.get("value").toString());
}
@Override
public String getReadableString()
{
public String getReadableString() {
return getValue();
}
}
/**
* Internal class used to represent a text component with a nested JSON value.
* Exception validating done is on keys and values.
*/
private static final class ComplexTextTypeComponent extends TextualComponent implements ConfigurationSerializable
{
public ComplexTextTypeComponent(final String key, final Map<String, String> values)
{
private static final class ComplexTextTypeComponent extends TextualComponent implements ConfigurationSerializable {
public ComplexTextTypeComponent(final String key, final Map<String, String> values) {
setKey(key);
setValue(values);
}
@Override
public String getKey()
{
public String getKey() {
return _key;
}
public void setKey(final String key)
{
public void setKey(final String key) {
Preconditions.checkArgument((key != null) && !key.isEmpty(), "The key must be specified.");
_key = key;
}
public Map<String, String> getValue()
{
public Map<String, String> getValue() {
return _value;
}
public void setValue(final Map<String, String> value)
{
public void setValue(final Map<String, String> value) {
Preconditions.checkArgument(value != null, "The value must be specified.");
_value = value;
}
private String _key;
private Map<String, String> _value;
@Override
public TextualComponent clone() throws CloneNotSupportedException
{
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 ComplexTextTypeComponent(getKey(), getValue());
}
@Override
public void writeJson(final JsonWriter writer) throws IOException
{
public void writeJson(final JsonWriter writer) throws IOException {
writer.name(getKey());
writer.beginObject();
for (final Map.Entry<String, String> jsonPair : _value.entrySet())
{
for (final Map.Entry<String, String> jsonPair : _value.entrySet()) {
writer.name(jsonPair.getKey()).value(jsonPair.getValue());
}
writer.endObject();
}
@Override
@SuppressWarnings("serial")
public Map<String, Object> serialize()
{
return new java.util.HashMap<String, Object>()
{
public Map<String, Object> serialize() {
return new java.util.HashMap<String, Object>() {
{
put("key", getKey());
for (final Map.Entry<String, String> valEntry : getValue().entrySet())
{
for (final Map.Entry<String, String> valEntry : getValue().entrySet()) {
put("value." + valEntry.getKey(), valEntry.getValue());
}
}
};
}
public static ComplexTextTypeComponent deserialize(final Map<String, Object> map)
{
public static ComplexTextTypeComponent deserialize(final Map<String, Object> map) {
String key = null;
final Map<String, String> value = new HashMap<String, String>();
for (final Map.Entry<String, Object> valEntry : map.entrySet())
{
if (valEntry.getKey().equals("key"))
{
for (final Map.Entry<String, Object> valEntry : map.entrySet()) {
if (valEntry.getKey().equals("key")) {
key = (String) valEntry.getValue();
}
else if (valEntry.getKey().startsWith("value."))
{
} else if (valEntry.getKey().startsWith("value.")) {
value.put(valEntry.getKey().substring(6) /* Strips out the value prefix */, valEntry.getValue().toString());
}
}
return new ComplexTextTypeComponent(key, value);
}
@Override
public String getReadableString()
{
public String getReadableString() {
return getKey();
}
}
/**
* Create a textual component representing a string literal.
* This is the default type of textual component when a single string literal is given to a method.
* @param textValue The text which will be represented.
* @return The text component representing the specified literal text.
*/
public static TextualComponent rawText(final String textValue)
{
public static TextualComponent rawText(final String textValue) {
return new ArbitraryTextTypeComponent("text", textValue);
}
/**
* Create a textual component representing a localized string.
* The client will see this text component as their localized version of the specified string <em>key</em>, which can be overridden by a resource pack.
@ -278,16 +238,14 @@ public abstract class TextualComponent implements Cloneable
* @param translateKey The string key which maps to localized text.
* @return The text component representing the specified localized text.
*/
public static TextualComponent localizedText(final String translateKey)
{
public static TextualComponent localizedText(final String translateKey) {
return new ArbitraryTextTypeComponent("translate", translateKey);
}
private static void throwUnsupportedSnapshot()
{
private static void throwUnsupportedSnapshot() {
throw new UnsupportedOperationException("This feature is only supported in snapshot releases.");
}
/**
* Create a textual component representing a scoreboard value.
* The client will see their own score for the specified objective as the text represented by this component.
@ -297,11 +255,10 @@ public abstract class TextualComponent implements Cloneable
* @param scoreboardObjective The name of the objective for which to display the score.
* @return The text component representing the specified scoreboard score (for the viewing player), or {@code null} if an error occurs during JSON serialization.
*/
public static TextualComponent objectiveScore(final String scoreboardObjective)
{
public static TextualComponent objectiveScore(final String scoreboardObjective) {
return objectiveScore("*", scoreboardObjective);
}
/**
* 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.
@ -313,16 +270,12 @@ public abstract class TextualComponent implements Cloneable
* @param scoreboardObjective The name of the objective for which to display the score.
* @return The text component representing the specified scoreboard score for the specified player, or {@code null} if an error occurs during JSON serialization.
*/
public static TextualComponent objectiveScore(final String playerName, final String scoreboardObjective)
{
public static TextualComponent objectiveScore(final String playerName, final String scoreboardObjective) {
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());
}
/**
* Create a textual component representing a player name, retrievable by using a standard minecraft selector.
* The client will see the players or entities captured by the specified selector as the text represented by this component.
@ -332,10 +285,9 @@ public abstract class TextualComponent implements Cloneable
* @param selector The minecraft player or entity selector which will capture the entities whose string representations will be displayed in the place of this text component.
* @return The text component representing the name of the entities captured by the selector.
*/
public static TextualComponent selector(final String selector)
{
public static TextualComponent selector(final String selector) {
throwUnsupportedSnapshot(); // Remove this line when the feature is released to non-snapshot versions, in addition to updating ALL THE OVERLOADS documentation accordingly
return new ArbitraryTextTypeComponent("selector", selector);
}
}

View File

@ -14,30 +14,27 @@ import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotId;
public abstract class APlotMeConnector
{
public abstract class APlotMeConnector {
public abstract Connection getPlotMeConnection(final String plugin, final FileConfiguration plotConfig, final String dataFolder);
public abstract HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(final Connection connection) throws SQLException;
public abstract boolean accepts(final String version);
public String getWorld(final String world)
{
for (final World newworld : Bukkit.getWorlds())
{
if (newworld.getName().equalsIgnoreCase(world)) { return newworld.getName(); }
public String getWorld(final String world) {
for (final World newworld : Bukkit.getWorlds()) {
if (newworld.getName().equalsIgnoreCase(world)) {
return newworld.getName();
}
}
return world;
}
public boolean isValidConnection(final Connection connection)
{
public boolean isValidConnection(final Connection connection) {
return connection != null;
}
public void copyConfig(final FileConfiguration plotConfig, final String world, final String actualWorldName)
{
public void copyConfig(final FileConfiguration plotConfig, final String world, final String actualWorldName) {
final Integer pathwidth = plotConfig.getInt("worlds." + world + ".PathWidth"); //
PS.get().config.set("worlds." + actualWorldName + ".road.width", pathwidth);
final Integer plotsize = plotConfig.getInt("worlds." + world + ".PlotSize"); //
@ -51,78 +48,62 @@ public abstract class APlotMeConnector
final String road = plotConfig.getString("worlds." + world + ".RoadMainBlockId");
PS.get().config.set("worlds." + actualWorldName + ".road.block", road);
Integer height = plotConfig.getInt("worlds." + world + ".RoadHeight"); //
if (height == null)
{
if (height == null) {
height = 64;
}
PS.get().config.set("worlds." + actualWorldName + ".road.height", height);
}
public Location getPlotTopLocAbs(final int path, final int plot, final PlotId plotid)
{
public Location getPlotTopLocAbs(final int path, final int plot, final PlotId plotid) {
final int px = plotid.x;
final int pz = plotid.y;
final int x = (px * (path + plot)) - ((int) Math.floor(path / 2)) - 1;
final int z = (pz * (path + plot)) - ((int) Math.floor(path / 2)) - 1;
return new Location(null, x, 256, z);
}
public Location getPlotBottomLocAbs(final int path, final int plot, final PlotId plotid)
{
public Location getPlotBottomLocAbs(final int path, final int plot, final PlotId plotid) {
final int px = plotid.x;
final int pz = plotid.y;
final int x = (px * (path + plot)) - plot - ((int) Math.floor(path / 2)) - 1;
final int z = (pz * (path + plot)) - plot - ((int) Math.floor(path / 2)) - 1;
return new Location(null, x, 1, z);
}
public void setMerged(final HashMap<String, HashMap<PlotId, boolean[]>> merges, final String world, final PlotId id, final int direction)
{
public void setMerged(final HashMap<String, HashMap<PlotId, boolean[]>> merges, final String world, final PlotId id, final int direction) {
final HashMap<PlotId, boolean[]> plots = merges.get(world);
PlotId id2;
switch (direction)
{
case 0:
{
switch (direction) {
case 0: {
id2 = new PlotId(id.x, id.y);
break;
}
case 1:
{
case 1: {
id2 = new PlotId(id.x, id.y);
break;
}
case 2:
{
case 2: {
id2 = new PlotId(id.x, id.y);
break;
}
case 3:
{
case 3: {
id2 = new PlotId(id.x, id.y);
break;
}
default:
{
default: {
return;
}
}
boolean[] merge1;
boolean[] merge2;
if (plots.containsKey(id))
{
if (plots.containsKey(id)) {
merge1 = plots.get(id);
}
else
{
} else {
merge1 = new boolean[] { false, false, false, false };
}
if (plots.containsKey(id2))
{
if (plots.containsKey(id2)) {
merge2 = plots.get(id2);
}
else
{
} else {
merge2 = new boolean[] { false, false, false, false };
}
merge1[direction] = true;
@ -130,5 +111,5 @@ public abstract class APlotMeConnector
plots.put(id, merge1);
plots.put(id2, merge1);
}
}

View File

@ -24,38 +24,29 @@ import com.intellectualcrafters.plot.object.StringWrapper;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.UUIDHandler;
public class ClassicPlotMeConnector extends APlotMeConnector
{
public class ClassicPlotMeConnector extends APlotMeConnector {
private String plugin;
@Override
public Connection getPlotMeConnection(final String plugin, final FileConfiguration plotConfig, final String dataFolder)
{
public Connection getPlotMeConnection(final String plugin, final FileConfiguration plotConfig, final String dataFolder) {
this.plugin = plugin.toLowerCase();
try
{
if (plotConfig.getBoolean("usemySQL"))
{
try {
if (plotConfig.getBoolean("usemySQL")) {
final String user = plotConfig.getString("mySQLuname");
final String password = plotConfig.getString("mySQLpass");
final String con = plotConfig.getString("mySQLconn");
return DriverManager.getConnection(con, user, password);
// return new MySQL(plotsquared, hostname, port, database, username, password)
}
else
{
} else {
return new SQLite(dataFolder + File.separator + "plots.db").openConnection();
}
}
catch (SQLException | ClassNotFoundException e)
{}
} catch (SQLException | ClassNotFoundException e) {}
return null;
}
@Override
public HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(final Connection connection) throws SQLException
{
public HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(final Connection connection) throws SQLException {
ResultSet r;
PreparedStatement stmt;
final HashMap<String, Integer> plotWidth = new HashMap<>();
@ -67,26 +58,20 @@ public class ClassicPlotMeConnector extends APlotMeConnector
String column = null;
final boolean checkUUID = DBFunc.hasColumn(r, "ownerid");
final boolean checkUUID2 = DBFunc.hasColumn(r, "ownerId");
if (checkUUID)
{
if (checkUUID) {
column = "ownerid";
}
else if (checkUUID2)
{
} else if (checkUUID2) {
column = "ownerId";
}
final boolean merge = !plugin.equals("plotme") && Settings.CONVERT_PLOTME;
int missing = 0;
while (r.next())
{
while (r.next()) {
final PlotId id = new PlotId(r.getInt("idX"), r.getInt("idZ"));
final String name = r.getString("owner");
final String world = LikePlotMeConverter.getWorld(r.getString("world"));
if (!plots.containsKey(world))
{
if (!plots.containsKey(world)) {
plots.put(world, new HashMap<PlotId, Plot>());
if (merge)
{
if (merge) {
final int plot = PS.get().config.getInt("worlds." + world + ".plot.size");
final int path = PS.get().config.getInt("worlds." + world + ".road.width");
plotWidth.put(world, plot);
@ -94,8 +79,7 @@ public class ClassicPlotMeConnector extends APlotMeConnector
merges.put(world, new HashMap<PlotId, boolean[]>());
}
}
if (merge)
{
if (merge) {
final int tx = r.getInt("topX");
final int tz = r.getInt("topZ");
final int bx = r.getInt("bottomX") - 1;
@ -104,64 +88,46 @@ public class ClassicPlotMeConnector extends APlotMeConnector
final int plot = plotWidth.get(world);
final Location top = getPlotTopLocAbs(path, plot, id);
final Location bot = getPlotBottomLocAbs(path, plot, id);
if (tx > top.getX())
{
if (tx > top.getX()) {
setMerged(merges, world, id, 1);
}
if (tz > top.getZ())
{
if (tz > top.getZ()) {
setMerged(merges, world, id, 2);
}
if (bx < bot.getX())
{
if (bx < bot.getX()) {
setMerged(merges, world, id, 3);
}
if (bz > bot.getZ())
{
if (bz > bot.getZ()) {
setMerged(merges, world, id, 0);
}
}
UUID owner = UUIDHandler.getUUID(name, null);
if (owner == null)
{
if (name.equals("*"))
{
if (owner == null) {
if (name.equals("*")) {
owner = DBFunc.everyone;
}
else
{
if (checkUUID || checkUUID2)
{
try
{
} else {
if (checkUUID || checkUUID2) {
try {
final byte[] bytes = r.getBytes(column);
if (bytes != null)
{
try
{
if (bytes != null) {
try {
final ByteBuffer bb = ByteBuffer.wrap(bytes);
final long high = bb.getLong();
final long low = bb.getLong();
owner = new UUID(high, low);
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
owner = UUID.nameUUIDFromBytes(bytes);
}
if (owner != null)
{
if (owner != null) {
UUIDHandler.add(new StringWrapper(name), owner);
}
}
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
}
}
if (owner == null)
{
if (owner == null) {
if (name.length() > 0) {
owner = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name.toLowerCase()).getBytes(Charsets.UTF_8));
}
@ -170,9 +136,7 @@ public class ClassicPlotMeConnector extends APlotMeConnector
continue;
}
}
}
else
{
} else {
UUIDHandler.add(new StringWrapper(name), owner);
}
final Plot plot = new Plot(world, id, owner);
@ -182,163 +146,127 @@ public class ClassicPlotMeConnector extends APlotMeConnector
MainUtil.sendConsoleMessage("&cSome names could not be identified:");
MainUtil.sendConsoleMessage("&7 - Empty quotes mean PlotMe just stored an unowned plot in the database");
MainUtil.sendConsoleMessage("&7 - Names you have never seen before could be from people mistyping commands");
MainUtil.sendConsoleMessage("&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)");
MainUtil
.sendConsoleMessage("&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)");
}
for (final Entry<String, HashMap<PlotId, boolean[]>> entry : merges.entrySet())
{
for (final Entry<String, HashMap<PlotId, boolean[]>> entry : merges.entrySet()) {
final String world = entry.getKey();
for (final Entry<PlotId, boolean[]> entry2 : entry.getValue().entrySet())
{
for (final Entry<PlotId, boolean[]> entry2 : entry.getValue().entrySet()) {
final HashMap<PlotId, Plot> newplots = plots.get(world);
final Plot plot = newplots.get(entry2.getKey());
if (plot != null)
{
if (plot != null) {
plot.getSettings().setMerged(entry2.getValue());
}
}
}
r.close();
stmt.close();
try
{
try {
MainUtil.sendConsoleMessage(" - " + plugin + "Denied");
stmt = connection.prepareStatement("SELECT * FROM `" + plugin + "Denied`");
r = stmt.executeQuery();
while (r.next())
{
while (r.next()) {
final PlotId id = new PlotId(r.getInt("idX"), r.getInt("idZ"));
final String name = r.getString("player");
final String world = LikePlotMeConverter.getWorld(r.getString("world"));
UUID denied = UUIDHandler.getUUID(name, null);
if (denied == null)
{
if (name.equals("*"))
{
if (denied == null) {
if (name.equals("*")) {
denied = DBFunc.everyone;
}
else
{
if (DBFunc.hasColumn(r, "playerid"))
{
try
{
} else {
if (DBFunc.hasColumn(r, "playerid")) {
try {
final byte[] bytes = r.getBytes("playerid");
if (bytes != null)
{
try
{
if (bytes != null) {
try {
final ByteBuffer bb = ByteBuffer.wrap(bytes);
final long high = bb.getLong();
final long low = bb.getLong();
denied = new UUID(high, low);
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
denied = UUID.nameUUIDFromBytes(bytes);
}
if (denied != null)
{
if (denied != null) {
UUIDHandler.add(new StringWrapper(name), denied);
}
}
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
}
}
}
if (denied == null)
{
if (denied == null) {
MainUtil.sendConsoleMessage("&6Could not identify denied for plot: " + id);
continue;
}
}
if (plots.get(world).containsKey(id))
{
if (plots.get(world).containsKey(id)) {
plots.get(world).get(id).getDenied().add(denied);
}
}
stmt = connection.prepareStatement("SELECT * FROM `" + plugin + "Allowed`");
r = stmt.executeQuery();
while (r.next())
{
while (r.next()) {
final PlotId id = new PlotId(r.getInt("idX"), r.getInt("idZ"));
final String name = r.getString("player");
final String world = LikePlotMeConverter.getWorld(r.getString("world"));
UUID helper = UUIDHandler.getUUID(name, null);
if (helper == null)
{
if (name.equals("*"))
{
if (helper == null) {
if (name.equals("*")) {
helper = DBFunc.everyone;
}
else
{
if (DBFunc.hasColumn(r, "playerid"))
{
try
{
} else {
if (DBFunc.hasColumn(r, "playerid")) {
try {
final byte[] bytes = r.getBytes("playerid");
if (bytes != null)
{
try
{
if (bytes != null) {
try {
final ByteBuffer bb = ByteBuffer.wrap(bytes);
final long high = bb.getLong();
final long low = bb.getLong();
helper = new UUID(high, low);
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
helper = UUID.nameUUIDFromBytes(bytes);
}
if (helper != null)
{
if (helper != null) {
UUIDHandler.add(new StringWrapper(name), helper);
}
}
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
}
}
}
if (helper == null)
{
if (helper == null) {
MainUtil.sendConsoleMessage("&6Could not identify helper for plot: " + id);
continue;
}
}
if (plots.get(world).containsKey(id))
{
if (plots.get(world).containsKey(id)) {
plots.get(world).get(id).getTrusted().add(helper);
}
}
r.close();
stmt.close();
}
catch (final Exception e)
{}
} catch (final Exception e) {}
return plots;
}
@Override
public boolean accepts(final String version)
{
if (version == null) { return true; }
public boolean accepts(final String version) {
if (version == null) {
return true;
}
return PS.get().canUpdate(version, "0.17.0");
}
}

View File

@ -53,202 +53,179 @@ import com.plotsquared.bukkit.generator.HybridGen;
* Created 2014-08-17 for PlotSquared
*
*/
*/
{
public class LikePlotMeConverter {
private final String plugin;
/**
* Constructor
*
* @param plugin Plugin Used to run the converter
*/
* @param plugin Plugin Used to run the converter
*/
public LikePlotMeConverter(final String plugin) {
this.plugin = plugin;
}
public static String getWorld(final String world)
{
for (final World newworld : Bukkit.getWorlds())
this.plugin = plugin;
}
public static String getWorld(final String world) {
for (final World newworld : Bukkit.getWorlds()) {
if (newworld.getName().equalsIgnoreCase(world)) {
return newworld.getName();
}
}
return world;
}
return world;
}
private void sendMessage(final String message) {
PS.debug("&3PlotMe&8->&3PlotSquared&8: &7" + message);
}
PS.debug("&3PlotMe&8->&3PlotSquared&8: &7" + message);
}
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 String getAthionPlotsPath() {
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(final String dataFolder) {
final File plotMeFile = new File(dataFolder + "config.yml");
if (!plotMeFile.exists()) {
return null;
}
return YamlConfiguration.loadConfiguration(plotMeFile);
}
return YamlConfiguration.loadConfiguration(plotMeFile);
}
public Set<String> getPlotMeWorlds(final FileConfiguration plotConfig) {
return plotConfig.getConfigurationSection("worlds").getKeys(false);
}
public void updateWorldYml(final String plugin, final String location)
{
return plotConfig.getConfigurationSection("worlds").getKeys(false);
}
public void updateWorldYml(final String plugin, final String location) {
try {
final Path path = Paths.get(location);
final Path path = Paths.get(location);
final File file = new File(location);
if (!file.exists()) {
return;
}
final Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(path), charset);
content = content.replaceAll("PlotMe-DefaultGenerator", "PlotSquared");
content = content.replaceAll(plugin, "PlotSquared");
Files.write(path, content.getBytes(charset));
}
content = content.replaceAll(plugin, "PlotSquared");
Files.write(path, content.getBytes(charset));
{}
}
public boolean run(final APlotMeConnector connector)
{
} catch (final Exception e) {}
}
public boolean run(final APlotMeConnector connector) {
try {
final String dataFolder = getPlotMePath();
final FileConfiguration plotConfig = getPlotMeConfig(dataFolder);
final String dataFolder = getPlotMePath();
final FileConfiguration plotConfig = getPlotMeConfig(dataFolder);
if (plotConfig == null) {
return false;
}
String version = plotConfig.getString("Version");
String version = plotConfig.getString("Version");
if (version == null) {
version = plotConfig.getString("version");
}
version = plotConfig.getString("version");
}
if (!connector.accepts(version)) {
return false;
}
PS.debug("&3Using connector: " + connector.getClass().getCanonicalName());
final Connection connection = connector.getPlotMeConnection(plugin, plotConfig, dataFolder);
final Connection connection = connector.getPlotMeConnection(plugin, plotConfig, dataFolder);
if (!connector.isValidConnection(connection)) {
sendMessage("Cannot connect to PlotMe DB. Conversion process will not continue");
return false;
return false;
}
sendMessage(plugin + " conversion has started. To disable this, please set 'plotme-convert.enabled' in the 'settings.yml'");
sendMessage(plugin + " conversion has started. To disable this, please set 'plotme-convert.enabled' in the 'settings.yml'");
sendMessage("Connecting to " + plugin + " DB");
int plotCount = 0;
int plotCount = 0;
final ArrayList<Plot> createdPlots = new ArrayList<>();
sendMessage("Collecting plot data");
final String dbPrefix = plugin.toLowerCase();
sendMessage(" - " + dbPrefix + "Plots");
final Set<String> worlds = getPlotMeWorlds(plotConfig);
sendMessage(" - " + dbPrefix + "Plots");
final Set<String> worlds = getPlotMeWorlds(plotConfig);
if (Settings.CONVERT_PLOTME) {
sendMessage("Updating bukkit.yml");
updateWorldYml(plugin, "bukkit.yml");
updateWorldYml(plugin, "plugins/Multiverse-Core/worlds.yml");
updateWorldYml(plugin, "bukkit.yml");
updateWorldYml(plugin, "plugins/Multiverse-Core/worlds.yml");
{
sendMessage("Copying config for: " + world);
for (final String world : plotConfig.getConfigurationSection("worlds").getKeys(false)) {
sendMessage("Copying config for: " + world);
try {
final String actualWorldName = getWorld(world);
connector.copyConfig(plotConfig, world, actualWorldName);
PS.get().config.save(PS.get().configFile);
}
connector.copyConfig(plotConfig, world, actualWorldName);
PS.get().config.save(PS.get().configFile);
} catch (final Exception e) {
e.printStackTrace();
sendMessage("&c-- &lFailed to save configuration for world '" + world + "'\nThis will need to be done using the setup command, or manually");
}
}
}
final HashMap<String, HashMap<PlotId, Plot>> plots = connector.getPlotMePlots(connection);
}
final HashMap<String, HashMap<PlotId, Plot>> plots = connector.getPlotMePlots(connection);
for (final Entry<String, HashMap<PlotId, Plot>> entry : plots.entrySet()) {
plotCount += entry.getValue().size();
}
plotCount += entry.getValue().size();
}
if (!Settings.CONVERT_PLOTME) {
return false;
}
sendMessage(" - " + dbPrefix + "Allowed");
sendMessage("Collected " + plotCount + " plots from PlotMe");
final File PLOTME_DG_FILE = new File(dataFolder + File.separator + "PlotMe-DefaultGenerator" + File.separator + "config.yml");
sendMessage("Collected " + plotCount + " plots from PlotMe");
final File PLOTME_DG_FILE = new File(dataFolder + File.separator + "PlotMe-DefaultGenerator" + File.separator + "config.yml");
{
final YamlConfiguration PLOTME_DG_YML = YamlConfiguration.loadConfiguration(PLOTME_DG_FILE);
try
{
if (PLOTME_DG_FILE.exists()) {
final YamlConfiguration PLOTME_DG_YML = YamlConfiguration.loadConfiguration(PLOTME_DG_FILE);
try {
for (final String world : plots.keySet()) {
final String actualWorldName = getWorld(world);
final String plotMeWorldName = world.toLowerCase();
Integer pathwidth = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".PathWidth"); //
final String plotMeWorldName = world.toLowerCase();
Integer pathwidth = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".PathWidth"); //
if (pathwidth == null) {
pathwidth = 7;
}
}
PS.get().config.set("worlds." + world + ".road.width", pathwidth);
Integer pathheight = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".RoadHeight"); //
Integer pathheight = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".RoadHeight"); //
if ((pathheight == null) || (pathheight == 0)) {
pathheight = 64;
}
PS.get().config.set("worlds." + world + ".road.height", pathheight);
PS.get().config.set("worlds." + world + ".wall.height", pathheight);
PS.get().config.set("worlds." + world + ".plot.height", pathheight);
Integer plotsize = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".PlotSize"); //
PS.get().config.set("worlds." + world + ".plot.height", pathheight);
Integer plotsize = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".PlotSize"); //
if ((plotsize == null) || (plotsize == 0)) {
plotsize = 32;
}
PS.get().config.set("worlds." + world + ".plot.size", plotsize);
String wallblock = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".WallBlock"); //
PS.get().config.set("worlds." + world + ".plot.size", plotsize);
String wallblock = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".WallBlock"); //
if (wallblock == null) {
wallblock = "44";
}
PS.get().config.set("worlds." + world + ".wall.block", wallblock);
String floor = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".PlotFloorBlock"); //
PS.get().config.set("worlds." + world + ".wall.block", wallblock);
String floor = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".PlotFloorBlock"); //
if (floor == null) {
floor = "2";
}
PS.get().config.set("worlds." + world + ".plot.floor", Arrays.asList(floor));
String filling = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".FillBlock"); //
PS.get().config.set("worlds." + world + ".plot.floor", Arrays.asList(floor));
String filling = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".FillBlock"); //
if (filling == null) {
filling = "3";
}
PS.get().config.set("worlds." + world + ".plot.filling", Arrays.asList(filling));
String road = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".RoadMainBlock");
PS.get().config.set("worlds." + world + ".plot.filling", Arrays.asList(filling));
String road = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".RoadMainBlock");
if (road == null) {
road = "5";
}
PS.get().config.set("worlds." + world + ".road.block", road);
Integer height = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".RoadHeight"); //
PS.get().config.set("worlds." + world + ".road.block", road);
Integer height = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".RoadHeight"); //
{
height = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".GroundHeight"); //
if ((height == null) || (height == 0)) {
height = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".GroundHeight"); //
if ((height == null) || (height == 0)) {
height = 64;
@ -257,121 +234,86 @@ public class LikePlotMeConverter
PS.get().config.set("worlds." + actualWorldName + ".road.height", height);
PS.get().config.set("worlds." + actualWorldName + ".plot.height", height);
PS.get().config.set("worlds." + actualWorldName + ".wall.height", height);
PS.get().config.save(PS.get().configFile);
}
}
PS.get().config.save(PS.get().configFile);
}
{}
}
} catch (final Exception e) {}
}
{
int duplicate = 0;
for (final Plot plot : plots.get(world).values())
{
for (final String world : plots.keySet()) {
int duplicate = 0;
for (final Plot plot : plots.get(world).values()) {
{
createdPlots.add(plot);
}
if (PS.get().getPlot(world, plot.id) == null) {
createdPlots.add(plot);
} else {
duplicate++;
}
}
}
}
if (duplicate > 0) {
PS.debug("&c[WARNING] Found " + duplicate + " duplicate plots already in DB for world: '" + world + "'. Have you run the converter already?");
}
}
sendMessage("Creating plot DB");
Thread.sleep(1000);
final AtomicBoolean done = new AtomicBoolean(false);
Thread.sleep(1000);
final AtomicBoolean done = new AtomicBoolean(false);
{
@Override
public void run()
{
DBFunc.createPlotsAndData(createdPlots, new Runnable() {
@Override
public void run() {
if (done.get()) {
sendMessage("&aDatabase conversion is now complete!");
PS.debug("&c - Stop the server");
PS.debug("&c - Disable 'plotme-convert.enabled' and 'plotme-convert.cache-uuids' in the settings.yml");
PS.debug("&c - Correct any generator settings that haven't copied to 'settings.yml' properly");
PS.debug("&c - Start the server");
PS.get().setAllPlotsRaw(DBFunc.getPlots());
}
PS.debug("&c - Start the server");
PS.get().setAllPlotsRaw(DBFunc.getPlots());
} else {
sendMessage("&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!");
done.set(true);
}
}
});
sendMessage("Saving configuration...");
});
sendMessage("Saving configuration...");
{
PS.get().config.save(PS.get().configFile);
}
try {
PS.get().config.save(PS.get().configFile);
} catch (final IOException e) {
sendMessage(" - &cFailed to save configuration.");
}
sendMessage(" - &cFailed to save configuration.");
}
{
@Override
public void run()
{
TaskManager.runTask(new Runnable() {
@Override
public void run() {
try {
boolean MV = false;
boolean MW = false;
boolean MV = false;
boolean MW = false;
{
MV = true;
}
if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) && Bukkit.getPluginManager().getPlugin("Multiverse-Core").isEnabled()) {
MV = true;
} else if ((Bukkit.getPluginManager().getPlugin("MultiWorld") != null) && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled()) {
MW = true;
}
MW = true;
}
{
final World world = Bukkit.getWorld(getWorld(worldname));
for (final String worldname : worlds) {
final World world = Bukkit.getWorld(getWorld(worldname));
if (world == null) {
sendMessage("&cInvalid world in PlotMe configuration: " + worldname);
}
final String actualWorldName = world.getName();
sendMessage("Reloading generator for world: '" + actualWorldName + "'...");
PS.get().removePlotWorld(actualWorldName);
sendMessage("Reloading generator for world: '" + actualWorldName + "'...");
PS.get().removePlotWorld(actualWorldName);
if (MV) {
// unload world with MV
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv unload " + actualWorldName);
// unload world with MV
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv unload " + actualWorldName);
{
Thread.sleep(1000);
}
try {
Thread.sleep(1000);
} catch (final InterruptedException ex) {
Thread.currentThread().interrupt();
}
// load world with MV
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv import " + actualWorldName + " normal -g PlotSquared");
}
// load world with MV
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv import " + actualWorldName + " normal -g PlotSquared");
} else if (MW) {
// unload world with MW
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw unload " + actualWorldName);
// unload world with MW
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw unload " + actualWorldName);
{
Thread.sleep(1000);
}
try {
Thread.sleep(1000);
} catch (final InterruptedException ex) {
Thread.currentThread().interrupt();
}
// load world with MW
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + actualWorldName + " plugin:PlotSquared");
}
// load world with MW
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + actualWorldName + " plugin:PlotSquared");
} else {
// Load using Bukkit API
@ -379,29 +321,22 @@ public class LikePlotMeConverter
Bukkit.getServer().unloadWorld(world, true);
final World myworld = WorldCreator.name(actualWorldName).generator(new HybridGen(actualWorldName)).createWorld();
myworld.save();
}
}
}
}
}
} catch (final Exception e) {
e.printStackTrace();
}
e.printStackTrace();
}
if (done.get()) {
sendMessage("&aDatabase conversion is now complete!");
PS.debug("&c - Stop the server");
PS.debug("&c - Disable 'plotme-convert.enabled' and 'plotme-convert.cache-uuids' in the settings.yml");
PS.debug("&c - Correct any generator settings that haven't copied to 'settings.yml' properly");
PS.debug("&c - Start the server");
}
PS.debug("&c - Correct any generator settings that haven't copied to 'settings.yml' properly");
PS.debug("&c - Start the server");
} else {
sendMessage("&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!");
done.set(true);
}
}
});
}
}
});
} catch (final Exception e) {
e.printStackTrace();

View File

@ -22,38 +22,31 @@ import com.intellectualcrafters.plot.object.StringWrapper;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.UUIDHandler;
public class PlotMeConnector_017 extends APlotMeConnector
{
public class PlotMeConnector_017 extends APlotMeConnector {
private String plugin;
@Override
public Connection getPlotMeConnection(final String plugin, final FileConfiguration plotConfig, final String dataFolder)
{
public Connection getPlotMeConnection(final String plugin, final FileConfiguration plotConfig, final String dataFolder) {
this.plugin = plugin.toLowerCase();
try
{
if (plotConfig.getBoolean("usemySQL"))
{
try {
if (plotConfig.getBoolean("usemySQL")) {
final String user = plotConfig.getString("mySQLuname");
final String password = plotConfig.getString("mySQLpass");
final String con = plotConfig.getString("mySQLconn");
return DriverManager.getConnection(con, user, password);
}
else
{
} else {
final File file = new File(dataFolder + File.separator + "plotmecore.db");
if (file.exists()) { return new SQLite(dataFolder + File.separator + "plotmecore.db").openConnection(); }
if (file.exists()) {
return new SQLite(dataFolder + File.separator + "plotmecore.db").openConnection();
}
return new SQLite(dataFolder + File.separator + "plots.db").openConnection();
}
}
catch (SQLException | ClassNotFoundException e)
{}
} catch (SQLException | ClassNotFoundException e) {}
return null;
}
@Override
public HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(final Connection connection) throws SQLException
{
public HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(final Connection connection) throws SQLException {
ResultSet r;
PreparedStatement stmt;
final HashMap<String, Integer> plotWidth = new HashMap<>();
@ -64,16 +57,13 @@ public class PlotMeConnector_017 extends APlotMeConnector
r = stmt.executeQuery();
final boolean checkUUID = DBFunc.hasColumn(r, "ownerID");
final boolean merge = !plugin.equals("plotme") && Settings.CONVERT_PLOTME;
while (r.next())
{
while (r.next()) {
final int key = r.getInt("plot_id");
final PlotId id = new PlotId(r.getInt("plotX"), r.getInt("plotZ"));
final String name = r.getString("owner");
final String world = LikePlotMeConverter.getWorld(r.getString("world"));
if (!plots.containsKey(world))
{
if (merge)
{
if (!plots.containsKey(world)) {
if (merge) {
final int plot = PS.get().config.getInt("worlds." + world + ".plot.size");
final int path = PS.get().config.getInt("worlds." + world + ".road.width");
plotWidth.put(world, plot);
@ -81,8 +71,7 @@ public class PlotMeConnector_017 extends APlotMeConnector
merges.put(world, new HashMap<PlotId, boolean[]>());
}
}
if (merge)
{
if (merge) {
final int tx = r.getInt("topX");
final int tz = r.getInt("topZ");
final int bx = r.getInt("bottomX") - 1;
@ -91,108 +80,83 @@ public class PlotMeConnector_017 extends APlotMeConnector
final int plot = plotWidth.get(world);
final Location top = getPlotTopLocAbs(path, plot, id);
final Location bot = getPlotBottomLocAbs(path, plot, id);
if (tx > top.getX())
{
if (tx > top.getX()) {
setMerged(merges, world, id, 1);
}
if (tz > top.getZ())
{
if (tz > top.getZ()) {
setMerged(merges, world, id, 2);
}
if (bx < bot.getX())
{
if (bx < bot.getX()) {
setMerged(merges, world, id, 3);
}
if (bz > bot.getZ())
{
if (bz > bot.getZ()) {
setMerged(merges, world, id, 0);
}
}
UUID owner = UUIDHandler.getUUID(name, null);
if (owner == null)
{
if (name.equals("*"))
{
if (owner == null) {
if (name.equals("*")) {
owner = DBFunc.everyone;
}
else
{
if (checkUUID)
{
try
{
} else {
if (checkUUID) {
try {
final byte[] bytes = r.getBytes("ownerid");
if (bytes != null)
{
if (bytes != null) {
owner = UUID.nameUUIDFromBytes(bytes);
if (owner != null)
{
if (owner != null) {
UUIDHandler.add(new StringWrapper(name), owner);
}
}
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
}
}
if (owner == null)
{
if (owner == null) {
MainUtil.sendConsoleMessage("&cCould not identify owner for plot: " + id + " -> '" + name + "'");
continue;
}
}
}
else
{
} else {
UUIDHandler.add(new StringWrapper(name), owner);
}
final Plot plot = new Plot(world, id, owner);
plots.put(key, plot);
}
for (final Entry<Integer, Plot> entry : plots.entrySet())
{
for (final Entry<Integer, Plot> entry : plots.entrySet()) {
final Plot plot = entry.getValue();
final HashMap<PlotId, boolean[]> mergeMap = merges.get(plot.world);
if (mergeMap != null)
{
if (mergeMap.containsKey(plot.id))
{
if (mergeMap != null) {
if (mergeMap.containsKey(plot.id)) {
plot.getSettings().setMerged(mergeMap.get(plot.id));
}
}
}
r.close();
stmt.close();
try
{
try {
MainUtil.sendConsoleMessage(" - " + plugin + "core_denied");
stmt = connection.prepareStatement("SELECT * FROM `" + plugin + "core_denied`");
r = stmt.executeQuery();
while (r.next())
{
while (r.next()) {
final int key = r.getInt("plot_id");
final Plot plot = plots.get(key);
if (plot == null)
{
if (plot == null) {
MainUtil.sendConsoleMessage("&6Denied (" + key + ") references deleted plot; ignoring entry.");
continue;
}
final UUID denied = UUID.fromString(r.getString("player"));
plot.getDenied().add(denied);
}
MainUtil.sendConsoleMessage(" - " + plugin + "core_allowed");
stmt = connection.prepareStatement("SELECT * FROM `" + plugin + "core_allowed`");
r = stmt.executeQuery();
while (r.next())
{
while (r.next()) {
final int key = r.getInt("plot_id");
final Plot plot = plots.get(key);
if (plot == null)
{
if (plot == null) {
MainUtil.sendConsoleMessage("&6Allowed (" + key + ") references deleted plot; ignoring entry.");
continue;
}
@ -201,20 +165,16 @@ public class PlotMeConnector_017 extends APlotMeConnector
}
r.close();
stmt.close();
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
}
final HashMap<String, HashMap<PlotId, Plot>> processed = new HashMap<>();
for (final Entry<Integer, Plot> entry : plots.entrySet())
{
for (final Entry<Integer, Plot> entry : plots.entrySet()) {
final Plot plot = entry.getValue();
HashMap<PlotId, Plot> map = processed.get(plot.world);
if (map == null)
{
if (map == null) {
map = new HashMap<>();
processed.put(plot.world, map);
}
@ -222,11 +182,12 @@ public class PlotMeConnector_017 extends APlotMeConnector
}
return processed;
}
@Override
public boolean accepts(final String version)
{
if (version == null) { return false; }
public boolean accepts(final String version) {
if (version == null) {
return false;
}
return !PS.get().canUpdate(version, "0.17");
}
}

View File

@ -31,65 +31,57 @@ import com.intellectualcrafters.plot.object.PlotCluster;
* Called when a flag is removed from a plot
*
*/
*/
public class ClusterFlagRemoveEvent extends Event implements Cancellable {
private static HandlerList handlers = new HandlerList();
private final PlotCluster cluster;
private final Flag flag;
private final Flag flag;
private boolean cancelled;
/**
* PlotFlagRemoveEvent: Called when a flag is removed from a plot
*
* @param flag Flag that was removed
* @param plot Plot from which the flag was removed
*/
* @param plot Plot from which the flag was removed
*/
public ClusterFlagRemoveEvent(final Flag flag, final PlotCluster cluster) {
this.cluster = cluster;
this.flag = flag;
}
this.flag = flag;
}
public static HandlerList getHandlerList() {
return handlers;
return handlers;
}
/**
* Get the cluster involved
*
* @return PlotCluster
*/
* @return PlotCluster
*/
public PlotCluster getCluster() {
return cluster;
return cluster;
}
/**
* Get the flag involved
*
* @return Flag
*/
* @return Flag
*/
public Flag getFlag() {
return flag;
return flag;
}
@Override
@Override
public HandlerList getHandlers() {
return handlers;
return handlers;
}
@Override
@Override
public boolean isCancelled() {
return cancelled;
return cancelled;
}
@Override
@Override
public void setCancelled(final boolean b) {
cancelled = b;

View File

@ -29,64 +29,56 @@ import com.intellectualcrafters.plot.object.Plot;
/**
*/
*/
public class PlayerClaimPlotEvent extends PlayerEvent implements Cancellable {
private static HandlerList handlers = new HandlerList();
private final Plot plot;
private final boolean auto;
private final boolean auto;
private boolean cancelled;
/**
* PlayerClaimPlotEvent: Called when a plot is claimed
*
* @param player Player that claimed the plot
* @param plot Plot that was claimed
*/
* @param plot Plot that was claimed
*/
public PlayerClaimPlotEvent(final Player player, final Plot plot, final boolean auto) {
super(player);
this.plot = plot;
this.auto = auto;
}
this.auto = auto;
}
public static HandlerList getHandlerList() {
return handlers;
return handlers;
}
/**
* Get the plot involved
*
* @return Plot
*/
* @return Plot
*/
public Plot getPlot() {
return plot;
return plot;
}
/**
* @return true if it was an automated claim, else false
*/
* @return true if it was an automated claim, else false
*/
public boolean wasAuto() {
return auto;
return auto;
}
@Override
@Override
public HandlerList getHandlers() {
return handlers;
return handlers;
}
@Override
@Override
public boolean isCancelled() {
return cancelled;
return cancelled;
}
@Override
@Override
public void setCancelled(final boolean b) {
cancelled = b;

View File

@ -28,41 +28,36 @@ import com.intellectualcrafters.plot.object.Plot;
/**
*/
*/
public class PlayerEnterPlotEvent extends PlayerEvent {
private static HandlerList handlers = new HandlerList();
private static HandlerList handlers = new HandlerList();
private final Plot plot;
/**
* PlayerEnterPlotEvent: Called when a player leaves a plot
*
* @param player Player that entered the plot
* @param plot Plot that was entered
*/
* @param plot Plot that was entered
*/
public PlayerEnterPlotEvent(final Player player, final Plot plot) {
super(player);
this.plot = plot;
}
this.plot = plot;
}
public static HandlerList getHandlerList() {
return handlers;
return handlers;
}
/**
* Get the plot involved
*
* @return Plot
*/
* @return Plot
*/
public Plot getPlot() {
return plot;
return plot;
}
@Override
@Override
public HandlerList getHandlers() {
return handlers;

View File

@ -28,42 +28,37 @@ import com.intellectualcrafters.plot.object.Plot;
/**
*/
public class PlayerLeavePlotEvent extends PlayerEvent
*/
public class PlayerLeavePlotEvent extends PlayerEvent {
private static HandlerList handlers = new HandlerList();
private static HandlerList handlers = new HandlerList();
private final Plot plot;
/**
* PlayerLeavePlotEvent: Called when a player leaves a plot
*
* @param player Player that left the plot
* @param plot Plot that was left
*/
* @param plot Plot that was left
*/
public PlayerLeavePlotEvent(final Player player, final Plot plot) {
super(player);
this.plot = plot;
}
this.plot = plot;
}
public static HandlerList getHandlerList() {
return handlers;
return handlers;
}
/**
* Get the plot involved
*
* @return Plot
*/
* @return Plot
*/
public Plot getPlot() {
return plot;
return plot;
}
@Override
@Override
public HandlerList getHandlers() {
return handlers;

View File

@ -29,14 +29,13 @@ import com.intellectualcrafters.plot.object.Plot;
/**
*/
public class PlayerPlotDeniedEvent extends PlotEvent
*/
public class PlayerPlotDeniedEvent extends PlotEvent {
private static HandlerList handlers = new HandlerList();
private final Player initiator;
private final boolean added;
private final boolean added;
private final UUID player;
/**
@ -45,52 +44,46 @@ public class PlayerPlotDeniedEvent extends PlotEvent
* @param initiator Player that initiated the event
* @param plot Plot in which the event occurred
* @param player Player that was denied/un-denied
* @param added true of add to deny list, false if removed
*/
* @param added true of add to deny list, false if removed
*/
public PlayerPlotDeniedEvent(final Player initiator, final Plot plot, final UUID player, final boolean added) {
super(plot);
this.initiator = initiator;
this.added = added;
this.player = player;
}
this.player = player;
}
public static HandlerList getHandlerList() {
return handlers;
return handlers;
}
/**
* If a user was added
*
* @return boolean
*/
* @return boolean
*/
public boolean wasAdded() {
return added;
return added;
}
/**
* The player added/removed
*
* @return UUID
*/
* @return UUID
*/
public UUID getPlayer() {
return player;
return player;
}
/**
* The player initiating the action
*
* @return Player
*/
* @return Player
*/
public Player getInitiator() {
return initiator;
return initiator;
}
@Override
@Override
public HandlerList getHandlers() {
return handlers;

View File

@ -29,14 +29,13 @@ import com.intellectualcrafters.plot.object.Plot;
/**
*/
public class PlayerPlotHelperEvent extends PlotEvent
*/
public class PlayerPlotHelperEvent extends PlotEvent {
private static HandlerList handlers = new HandlerList();
private final Player initiator;
private final boolean added;
private final boolean added;
private final UUID player;
/**
@ -45,52 +44,46 @@ public class PlayerPlotHelperEvent extends PlotEvent
* @param initiator Player that initiated the event
* @param plot Plot in which the event occurred
* @param player Player that was added/removed from the helper list
* @param added true of the player was added, false if the player was removed
*/
* @param added true of the player was added, false if the player was removed
*/
public PlayerPlotHelperEvent(final Player initiator, final Plot plot, final UUID player, final boolean added) {
super(plot);
this.initiator = initiator;
this.added = added;
this.player = player;
}
this.player = player;
}
public static HandlerList getHandlerList() {
return handlers;
return handlers;
}
/**
* If a player was added
*
* @return boolean
*/
* @return boolean
*/
public boolean wasAdded() {
return added;
return added;
}
/**
* The UUID added/removed
*
* @return UUID
*/
* @return UUID
*/
public UUID getPlayer() {
return player;
return player;
}
/**
* The player initiating the action
*
* @return Player
*/
* @return Player
*/
public Player getInitiator() {
return initiator;
return initiator;
}
@Override
@Override
public HandlerList getHandlers() {
return handlers;

View File

@ -29,14 +29,13 @@ import com.intellectualcrafters.plot.object.Plot;
/**
*/
public class PlayerPlotTrustedEvent extends PlotEvent
*/
public class PlayerPlotTrustedEvent extends PlotEvent {
private static HandlerList handlers = new HandlerList();
private final Player initiator;
private final boolean added;
private final boolean added;
private final UUID player;
/**
@ -45,52 +44,46 @@ public class PlayerPlotTrustedEvent extends PlotEvent
* @param initiator Player that initiated the event
* @param plot Plot in which the event occurred
* @param player Player that was added/removed from the trusted list
* @param added true of the player was added, false if the player was removed
*/
* @param added true of the player was added, false if the player was removed
*/
public PlayerPlotTrustedEvent(final Player initiator, final Plot plot, final UUID player, final boolean added) {
super(plot);
this.initiator = initiator;
this.added = added;
this.player = player;
}
this.player = player;
}
public static HandlerList getHandlerList() {
return handlers;
return handlers;
}
/**
* If a player was added
*
* @return boolean
*/
* @return boolean
*/
public boolean wasAdded() {
return added;
return added;
}
/**
* The UUID added/removed
*
* @return UUID
*/
* @return UUID
*/
public UUID getPlayer() {
return player;
return player;
}
/**
* The player initiating the action
*
* @return Player
*/
* @return Player
*/
public Player getInitiator() {
return initiator;
return initiator;
}
@Override
@Override
public HandlerList getHandlers() {
return handlers;

View File

@ -32,13 +32,12 @@ import com.intellectualcrafters.plot.object.Plot;
* Called when a player teleports to a plot
*
*/
*/
public class PlayerTeleportToPlotEvent extends PlayerEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final Location from;
private final Plot plot;
private final Plot plot;
private boolean cancelled;
/**
@ -46,53 +45,46 @@ public class PlayerTeleportToPlotEvent extends PlayerEvent implements Cancellabl
*
* @param player That was teleported
* @param from Start location
* @param plot Plot to which the player was teleported
*/
* @param plot Plot to which the player was teleported
*/
public PlayerTeleportToPlotEvent(final Player player, final Location from, final Plot plot) {
super(player);
this.from = from;
this.plot = plot;
}
this.plot = plot;
}
public static HandlerList getHandlerList() {
return handlers;
return handlers;
}
@Override
@Override
public HandlerList getHandlers() {
return handlers;
return handlers;
}
/**
* Get the from location
*
* @return Location
*/
* @return Location
*/
public Location getFrom() {
return from;
return from;
}
/**
* Get the plot involved
*
* @return Plot
*/
* @return Plot
*/
public Plot getPlot() {
return plot;
return plot;
}
@Override
@Override
public boolean isCancelled() {
return cancelled;
return cancelled;
}
@Override
@Override
public void setCancelled(final boolean cancelled) {
this.cancelled = cancelled;

View File

@ -30,65 +30,57 @@ import com.intellectualcrafters.plot.object.PlotId;
* Called when a plot is cleared
*
*/
*/
public class PlotClearEvent extends Event implements Cancellable {
private static HandlerList handlers = new HandlerList();
private final PlotId id;
private final String world;
private final String world;
private boolean cancelled;
/**
* PlotClearEvent: Called when a plot is cleared
*
* @param world The world in which the plot was cleared
* @param id The plot that was cleared
*/
* @param id The plot that was cleared
*/
public PlotClearEvent(final String world, final PlotId id) {
this.id = id;
this.world = world;
}
this.world = world;
}
public static HandlerList getHandlerList() {
return handlers;
return handlers;
}
/**
* Get the PlotId
*
* @return PlotId
*/
* @return PlotId
*/
public PlotId getPlotId() {
return id;
return id;
}
/**
* Get the world name
*
* @return String
*/
* @return String
*/
public String getWorld() {
return world;
return world;
}
@Override
@Override
public HandlerList getHandlers() {
return handlers;
return handlers;
}
@Override
@Override
public boolean isCancelled() {
return cancelled;
return cancelled;
}
@Override
@Override
public void setCancelled(final boolean b) {
cancelled = b;

View File

@ -29,52 +29,46 @@ import com.intellectualcrafters.plot.object.PlotId;
* Called when a plot is deleted
*
*/
*/
public class PlotDeleteEvent extends Event {
private static HandlerList handlers = new HandlerList();
private final PlotId id;
private final PlotId id;
private final String world;
/**
* PlotDeleteEvent: Called when a plot is deleted
*
* @param world The world in which the plot was deleted
* @param id The ID of the plot that was deleted
*/
* @param id The ID of the plot that was deleted
*/
public PlotDeleteEvent(final String world, final PlotId id) {
this.id = id;
this.world = world;
}
this.world = world;
}
public static HandlerList getHandlerList() {
return handlers;
return handlers;
}
/**
* Get the PlotId
*
* @return PlotId
*/
* @return PlotId
*/
public PlotId getPlotId() {
return id;
return id;
}
/**
* Get the world name
*
* @return String
*/
* @return String
*/
public String getWorld() {
return world;
return world;
}
@Override
@Override
public HandlerList getHandlers() {
return handlers;

View File

@ -4,19 +4,16 @@ import org.bukkit.event.Event;
import com.intellectualcrafters.plot.object.Plot;
public abstract class PlotEvent extends Event
{
public abstract class PlotEvent extends Event {
private final Plot plot;
public PlotEvent(final Plot plot)
{
public PlotEvent(final Plot plot) {
this.plot = plot;
}
public final Plot getPlot()
{
public final Plot getPlot() {
return plot;
}
}

View File

@ -30,55 +30,48 @@ import com.intellectualcrafters.plot.object.Plot;
* Called when a Flag is added to a plot
*
*/
public class PlotFlagAddEvent extends PlotEvent implements Cancellable
*/
public class PlotFlagAddEvent extends PlotEvent implements Cancellable {
private static HandlerList handlers = new HandlerList();
private final Flag flag;
private final Flag flag;
private boolean cancelled;
/**
* PlotFlagAddEvent: Called when a Flag is added to a plot
*
* @param flag Flag that was added
* @param plot Plot to which the flag was added
*/
* @param plot Plot to which the flag was added
*/
public PlotFlagAddEvent(final Flag flag, final Plot plot) {
super(plot);
this.flag = flag;
}
this.flag = flag;
}
public static HandlerList getHandlerList() {
return handlers;
return handlers;
}
/**
* Get the flag involved
*
* @return Flag
*/
* @return Flag
*/
public Flag getFlag() {
return flag;
return flag;
}
@Override
@Override
public HandlerList getHandlers() {
return handlers;
return handlers;
}
@Override
@Override
public final boolean isCancelled() {
return cancelled;
return cancelled;
}
@Override
@Override
public final void setCancelled(final boolean cancelled) {
this.cancelled = cancelled;

View File

@ -30,55 +30,48 @@ import com.intellectualcrafters.plot.object.Plot;
* Called when a flag is removed from a plot
*
*/
public class PlotFlagRemoveEvent extends PlotEvent implements Cancellable
*/
public class PlotFlagRemoveEvent extends PlotEvent implements Cancellable {
private static HandlerList handlers = new HandlerList();
private final Flag flag;
private final Flag flag;
private boolean cancelled;
/**
* PlotFlagRemoveEvent: Called when a flag is removed from a plot
*
* @param flag Flag that was removed
* @param plot Plot from which the flag was removed
*/
* @param plot Plot from which the flag was removed
*/
public PlotFlagRemoveEvent(final Flag flag, final Plot plot) {
super(plot);
this.flag = flag;
}
this.flag = flag;
}
public static HandlerList getHandlerList() {
return handlers;
return handlers;
}
/**
* Get the flag involved
*
* @return Flag
*/
* @return Flag
*/
public Flag getFlag() {
return flag;
return flag;
}
@Override
@Override
public HandlerList getHandlers() {
return handlers;
return handlers;
}
@Override
@Override
public final boolean isCancelled() {
return cancelled;
return cancelled;
}
@Override
@Override
public final void setCancelled(final boolean cancelled) {
this.cancelled = cancelled;

View File

@ -32,14 +32,13 @@ import com.intellectualcrafters.plot.object.PlotId;
/**
*/
public class PlotMergeEvent extends Event implements Cancellable
*/
public class PlotMergeEvent extends Event implements Cancellable {
private static HandlerList handlers = new HandlerList();
private final ArrayList<PlotId> plots;
private boolean cancelled;
private Plot plot;
private World world;
private World world;
/**
* PlotMergeEvent: Called when plots are merged
@ -47,56 +46,48 @@ public class PlotMergeEvent extends Event implements Cancellable
* @param world World in which the event occurred
* @param plot Plot that was merged
* @param plots A list of plots involved in the event
*/
public PlotMergeEvent(final World world, final Plot plot, final ArrayList<PlotId> plots)
*/
public PlotMergeEvent(final World world, final Plot plot, final ArrayList<PlotId> plots) {
this.plots = plots;
}
public static HandlerList getHandlerList()
}
public static HandlerList getHandlerList() {
return handlers;
}
}
/**
* Get the plots being added;
*
* @return Plot
*/
public ArrayList<PlotId> getPlots()
*/
public ArrayList<PlotId> getPlots() {
return plots;
}
}
/**
* Get the main plot
*
* @return Plot
*/
public Plot getPlot()
*/
public Plot getPlot() {
return plot;
}
public World getWorld()
}
public World getWorld() {
return world;
}
}
@Override
public HandlerList getHandlers()
@Override
public HandlerList getHandlers() {
return handlers;
}
}
@Override
public boolean isCancelled()
@Override
public boolean isCancelled() {
return cancelled;
}
}
@Override
public void setCancelled(final boolean b)
@Override
public void setCancelled(final boolean b) {
cancelled = b;
}

View File

@ -10,44 +10,37 @@ import com.intellectualcrafters.plot.object.Rating;
* Created 2015-07-13 for PlotSquaredGit
*
*/
public class PlotRateEvent extends PlotEvent
{
*/
public class PlotRateEvent extends PlotEvent {
private static HandlerList handlers = new HandlerList();
private final PlotPlayer rater;
private Rating rating;
public PlotRateEvent(final PlotPlayer rater, final Rating rating, final Plot plot)
private Rating rating;
public PlotRateEvent(final PlotPlayer rater, final Rating rating, final Plot plot) {
super(plot);
this.rater = rater;
this.rating = rating;
}
public static HandlerList getHandlerList()
}
public static HandlerList getHandlerList() {
return handlers;
}
public PlotPlayer getRater()
}
public PlotPlayer getRater() {
return rater;
}
public void setRating(final Rating rating)
}
public void setRating(final Rating rating) {
this.rating = rating;
}
public Rating getRating()
}
public Rating getRating() {
return rating;
}
}
@Override
public HandlerList getHandlers()
@Override
public HandlerList getHandlers() {
return handlers;
}
}

View File

@ -31,60 +31,52 @@ import com.intellectualcrafters.plot.object.PlotId;
/**
*/
public class PlotUnlinkEvent extends Event implements Cancellable
*/
public class PlotUnlinkEvent extends Event implements Cancellable {
private static HandlerList handlers = new HandlerList();
private final ArrayList<PlotId> plots;
private final World world;
private boolean cancelled;
private boolean cancelled;
/**
* Called when a mega-plot is unlinked.
*
* @param world World in which the event occurred
* @param plots Plots that are involved in the event
*/
public PlotUnlinkEvent(final World world, final ArrayList<PlotId> plots)
*/
public PlotUnlinkEvent(final World world, final ArrayList<PlotId> plots) {
this.plots = plots;
this.world = world;
}
public static HandlerList getHandlerList()
}
public static HandlerList getHandlerList() {
return handlers;
}
}
/**
* Get the plots involved
*
* @return PlotId
*/
public ArrayList<PlotId> getPlots()
*/
public ArrayList<PlotId> getPlots() {
return plots;
}
public World getWorld()
}
public World getWorld() {
return world;
}
}
@Override
public HandlerList getHandlers()
@Override
public HandlerList getHandlers() {
return handlers;
}
}
@Override
public boolean isCancelled()
@Override
public boolean isCancelled() {
return cancelled;
}
}
@Override
public void setCancelled(final boolean b)
@Override
public void setCancelled(final boolean b) {
cancelled = b;
}

View File

@ -25,8 +25,7 @@ import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.bukkit.util.BukkitChunkManager;
import com.plotsquared.bukkit.util.BukkitSetBlockManager;
public class AugmentedPopulator extends BlockPopulator
{
public class AugmentedPopulator extends BlockPopulator {
public final PlotWorld plotworld;
public final PlotManager manager;
public final BukkitPlotGenerator generator;
@ -39,9 +38,8 @@ public class AugmentedPopulator extends BlockPopulator
private final int bz;
private final int tx;
private final int tz;
public AugmentedPopulator(final String world, final BukkitPlotGenerator generator, final PlotCluster cluster, final boolean p, final boolean b)
{
public AugmentedPopulator(final String world, final BukkitPlotGenerator generator, final PlotCluster cluster, final boolean p, final boolean b) {
MainUtil.initCache();
PS.log("== NEW AUGMENTED POPULATOR FOR: " + world);
this.cluster = cluster;
@ -52,68 +50,53 @@ public class AugmentedPopulator extends BlockPopulator
this.b = b;
o = (plotworld.TERRAIN == 1) || (plotworld.TERRAIN == 2);
final World bukkitWorld = Bukkit.getWorld(world);
if (cluster != null)
{
if (cluster != null) {
final Location bl = manager.getPlotBottomLocAbs(plotworld, cluster.getP1());
final Location tl = manager.getPlotTopLocAbs(plotworld, cluster.getP2()).add(1, 0, 1);
bx = bl.getX();
bz = bl.getZ();
tx = tl.getX();
tz = tl.getZ();
}
else
{
} else {
bx = Integer.MIN_VALUE;
bz = Integer.MIN_VALUE;
tx = Integer.MAX_VALUE;
tz = Integer.MAX_VALUE;
}
// Add the populator
if (o)
{
if (o) {
bukkitWorld.getPopulators().add(0, this);
}
else
{
} else {
bukkitWorld.getPopulators().add(this);
}
}
public static void removePopulator(final String worldname, final PlotCluster cluster)
{
public static void removePopulator(final String worldname, final PlotCluster cluster) {
final World world = Bukkit.getWorld(worldname);
for (final Iterator<BlockPopulator> iterator = world.getPopulators().iterator(); iterator.hasNext();)
{
for (final Iterator<BlockPopulator> iterator = world.getPopulators().iterator(); iterator.hasNext();) {
final BlockPopulator populator = iterator.next();
if (populator instanceof AugmentedPopulator)
{
if (((AugmentedPopulator) populator).cluster.equals(cluster))
{
if (populator instanceof AugmentedPopulator) {
if (((AugmentedPopulator) populator).cluster.equals(cluster)) {
iterator.remove();
}
}
}
}
public BlockWrapper get(final int x, final int z, final int i, final int j, final short[][] r, final boolean c)
{
public BlockWrapper get(final int x, final int z, final int i, final int j, final short[][] r, final boolean c) {
final int y = (i << 4) + (j >> 8);
final int a = (j - ((y & 0xF) << 8));
final int z1 = (a >> 4);
final int x1 = a - (z1 << 4);
if (r[i] == null)
{
if (r[i] == null) {
return (c && (((z + z1) < bz) || ((z + z1) > tz) || ((x + x1) < bx) || ((x + x1) > tx))) ? null : new BlockWrapper(x1, y, z1, (short) 0, (byte) 0);
}
else
{
} else {
return (c && (((z + z1) < bz) || ((z + z1) > tz) || ((x + x1) < bx) || ((x + x1) > tx))) ? null : new BlockWrapper(x1, y, z1, r[i][j], (byte) 0);
}
}
@Override
public void populate(final World world, final Random rand, final Chunk chunk)
{
public void populate(final World world, final Random rand, final Chunk chunk) {
final int cx = chunk.getX();
final int cz = chunk.getZ();
final int bx = cx << 4;
@ -126,30 +109,24 @@ public class AugmentedPopulator extends BlockPopulator
final boolean inZ2 = ((tz >= this.bz) && (tz <= this.tz));
final boolean inX = inX1 || inX2;
final boolean inZ = inZ1 || inZ2;
if (!inX || !inZ) { return; }
if (plotworld.TERRAIN == 3)
{
if (!inX || !inZ) {
return;
}
if (plotworld.TERRAIN == 3) {
final int X = chunk.getX() << 4;
final int Z = chunk.getZ() << 4;
if (ChunkManager.FORCE_PASTE)
{
for (short x = 0; x < 16; x++)
{
for (short z = 0; z < 16; z++)
{
if (ChunkManager.FORCE_PASTE) {
for (short x = 0; x < 16; x++) {
for (short z = 0; z < 16; z++) {
final PlotLoc loc = new PlotLoc((short) (X + x), (short) (Z + z));
final HashMap<Short, Short> blocks = ChunkManager.GENERATE_BLOCKS.get(loc);
final HashMap<Short, Byte> datas = ChunkManager.GENERATE_DATA.get(loc);
for (final Entry<Short, Short> entry : blocks.entrySet())
{
for (final Entry<Short, Short> entry : blocks.entrySet()) {
final int y = entry.getKey();
byte data;
if (datas != null)
{
if (datas != null) {
data = datas.get(y);
}
else
{
} else {
data = 0;
}
BukkitSetBlockManager.setBlockManager.set(world, x, y, z, blocks.get(y), data);
@ -158,31 +135,23 @@ public class AugmentedPopulator extends BlockPopulator
}
return;
}
if (ChunkManager.CURRENT_PLOT_CLEAR != null)
{
if (ChunkManager.CURRENT_PLOT_CLEAR != null) {
PlotLoc loc;
for (final Entry<PlotLoc, HashMap<Short, Byte>> entry : ChunkManager.GENERATE_DATA.entrySet())
{
for (final Entry<PlotLoc, HashMap<Short, Byte>> entry : ChunkManager.GENERATE_DATA.entrySet()) {
final HashMap<Short, Byte> datas = ChunkManager.GENERATE_DATA.get(entry.getKey());
for (final Entry<Short, Byte> entry2 : entry.getValue().entrySet())
{
for (final Entry<Short, Byte> entry2 : entry.getValue().entrySet()) {
final Short y = entry2.getKey();
byte data;
if (datas != null)
{
if (datas != null) {
data = datas.get(y);
}
else
{
} else {
data = 0;
}
loc = entry.getKey();
final int xx = loc.x - X;
final int zz = loc.z - Z;
if ((xx >= 0) && (xx < 16))
{
if ((zz >= 0) && (zz < 16))
{
if ((xx >= 0) && (xx < 16)) {
if ((zz >= 0) && (zz < 16)) {
BukkitSetBlockManager.setBlockManager.set(world, xx, y, zz, entry2.getValue(), data);
}
}
@ -193,118 +162,86 @@ public class AugmentedPopulator extends BlockPopulator
}
final boolean check;
check = !inX1 || !inX2 || !inZ1 || !inZ2;
if (plotworld.TERRAIN > 1)
{
if (plotworld.TERRAIN > 1) {
final PlotId plot1 = manager.getPlotIdAbs(plotworld, bx, 0, bz);
final PlotId plot2 = manager.getPlotIdAbs(plotworld, tx, 0, tz);
if ((plot1 != null) && (plot2 != null) && plot1.equals(plot2)) { return; }
if ((plot1 != null) && (plot2 != null) && plot1.equals(plot2)) {
return;
}
}
if (o)
{
if (o) {
populateBlocks(world, rand, cx, cz, bx, bz, check);
}
else
{
TaskManager.runTaskLater(new Runnable()
{
} else {
TaskManager.runTaskLater(new Runnable() {
@Override
public void run()
{
public void run() {
populateBiome(world, bx, bz);
}
}, 20 + rand.nextInt(10));
TaskManager.runTaskLater(new Runnable()
{
TaskManager.runTaskLater(new Runnable() {
@Override
public void run()
{
public void run() {
chunk.load(true);
populateBlocks(world, rand, cx, cz, bx, bz, check);
}
}, 40 + rand.nextInt(40));
}
}
private void populateBiome(final World world, final int x, final int z)
{
private void populateBiome(final World world, final int x, final int z) {
final Biome biome = Biome.valueOf(plotworld.PLOT_BIOME);
if (b)
{
for (int i = 0; i < 16; i++)
{
for (int j = 0; j < 16; j++)
{
if (b) {
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 16; j++) {
world.setBiome(x + i, z + j, biome);
}
}
}
}
private void populateBlocks(final World world, final Random rand, final int X, final int Z, final int x, final int z, final boolean check)
{
private void populateBlocks(final World world, final Random rand, final int X, final int Z, final int x, final int z, final boolean check) {
final short[][] result = generator.generateExtBlockSections(world, rand, X, Z, null);
for (int i = 0; i < result.length; i++)
{
if (result[i] != null)
{
for (int j = 0; j < 4096; j++)
{
for (int i = 0; i < result.length; i++) {
if (result[i] != null) {
for (int j = 0; j < 4096; j++) {
final int x1 = MainUtil.x_loc[i][j];
final int y = MainUtil.y_loc[i][j];
final int z1 = MainUtil.z_loc[i][j];
final short id = result[i][j];
final int xx = x + x1;
final int zz = z + z1;
if (check && (((zz) < bz) || ((zz) > tz) || ((xx) < bx) || ((xx) > tx)))
{
if (check && (((zz) < bz) || ((zz) > tz) || ((xx) < bx) || ((xx) > tx))) {
continue;
}
if (p)
{
if (ChunkManager.CURRENT_PLOT_CLEAR != null)
{
if (BukkitChunkManager.isIn(ChunkManager.CURRENT_PLOT_CLEAR, xx, zz))
{
if (p) {
if (ChunkManager.CURRENT_PLOT_CLEAR != null) {
if (BukkitChunkManager.isIn(ChunkManager.CURRENT_PLOT_CLEAR, xx, zz)) {
continue;
}
}
else if (manager.getPlotIdAbs(plotworld, xx, 0, zz) != null)
{
} else if (manager.getPlotIdAbs(plotworld, xx, 0, zz) != null) {
continue;
}
}
BukkitSetBlockManager.setBlockManager.set(world, xx, y, zz, id, (byte) 0);
}
}
else
{
} else {
final short y_min = MainUtil.y_loc[i][0];
if (y_min < 128)
{
for (int x1 = x; x1 < (x + 16); x1++)
{
for (int z1 = z; z1 < (z + 16); z1++)
{
if (check && (((z1) < bz) || ((z1) > tz) || ((x1) < bx) || ((x1) > tx)))
{
if (y_min < 128) {
for (int x1 = x; x1 < (x + 16); x1++) {
for (int z1 = z; z1 < (z + 16); z1++) {
if (check && (((z1) < bz) || ((z1) > tz) || ((x1) < bx) || ((x1) > tx))) {
continue;
}
if (p)
{
if (ChunkManager.CURRENT_PLOT_CLEAR != null)
{
if (BukkitChunkManager.isIn(ChunkManager.CURRENT_PLOT_CLEAR, x1, z1))
{
if (p) {
if (ChunkManager.CURRENT_PLOT_CLEAR != null) {
if (BukkitChunkManager.isIn(ChunkManager.CURRENT_PLOT_CLEAR, x1, z1)) {
continue;
}
}
else if (manager.getPlotIdAbs(plotworld, x1, 0, z1) != null)
{
} else if (manager.getPlotIdAbs(plotworld, x1, 0, z1) != null) {
continue;
}
}
for (int y = y_min; y < (y_min + 16); y++)
{
for (int y = y_min; y < (y_min + 16); y++) {
BukkitSetBlockManager.setBlockManager.set(world, x1, y, z1, 0, (byte) 0);
}
}
@ -312,8 +249,7 @@ public class AugmentedPopulator extends BlockPopulator
}
}
}
for (final BlockPopulator populator : generator.getPopulators(world.getName()))
{
for (final BlockPopulator populator : generator.getPopulators(world.getName())) {
final Chunk chunk = world.getChunkAt(X, Z);
populator.populate(world, r, chunk);
}

View File

@ -9,94 +9,80 @@ import com.intellectualcrafters.plot.object.PlotManager;
import com.intellectualcrafters.plot.object.PlotWorld;
import com.intellectualcrafters.plot.object.SetupObject;
public class BukkitGeneratorWrapper extends PlotGenerator<ChunkGenerator>
{
public class BukkitGeneratorWrapper extends PlotGenerator<ChunkGenerator> {
public final boolean full;
public BukkitGeneratorWrapper(final String world, final ChunkGenerator generator)
{
public BukkitGeneratorWrapper(final String world, final ChunkGenerator generator) {
super(world, generator);
full = (generator instanceof BukkitPlotGenerator);
}
@Override
public void initialize(final PlotWorld plotworld)
{
if (generator instanceof BukkitPlotGenerator)
{
public void initialize(final PlotWorld plotworld) {
if (generator instanceof BukkitPlotGenerator) {
((BukkitPlotGenerator) generator).init(plotworld);
}
}
@Override
public void augment(final PlotCluster cluster, final PlotWorld plotworld)
{
if (generator instanceof BukkitPlotGenerator)
{
public void augment(final PlotCluster cluster, final PlotWorld plotworld) {
if (generator instanceof BukkitPlotGenerator) {
final BukkitPlotGenerator plotgen = (BukkitPlotGenerator) generator;
if (cluster != null)
{
if (cluster != null) {
new AugmentedPopulator(world, plotgen, cluster, plotworld.TERRAIN == 2, plotworld.TERRAIN != 2);
}
else
{
} else {
new AugmentedPopulator(world, plotgen, null, plotworld.TERRAIN == 2, plotworld.TERRAIN != 2);
}
}
}
@Override
public void setGenerator(final String gen_string)
{
if (gen_string == null)
{
public void setGenerator(final String gen_string) {
if (gen_string == null) {
generator = new HybridGen(world);
}
else
{
} else {
final PlotGenerator<ChunkGenerator> gen_wrapper = (PlotGenerator<ChunkGenerator>) PS.get().IMP.getGenerator(world, gen_string);
if (gen_wrapper != null)
{
if (gen_wrapper != null) {
generator = gen_wrapper.generator;
}
}
}
@Override
public PlotWorld getNewPlotWorld(final String world)
{
if (!(generator instanceof BukkitPlotGenerator)) { return null; }
public PlotWorld getNewPlotWorld(final String world) {
if (!(generator instanceof BukkitPlotGenerator)) {
return null;
}
return ((BukkitPlotGenerator) generator).getNewPlotWorld(world);
}
@Override
public PlotManager getPlotManager()
{
if (!(generator instanceof BukkitPlotGenerator)) { return null; }
public PlotManager getPlotManager() {
if (!(generator instanceof BukkitPlotGenerator)) {
return null;
}
return ((BukkitPlotGenerator) generator).getPlotManager();
}
@Override
public boolean isFull()
{
public boolean isFull() {
return full;
}
@Override
public String getName()
{
if (generator == null) { return "Null"; }
public String getName() {
if (generator == null) {
return "Null";
}
return generator.getClass().getName();
}
@Override
public void processSetup(final SetupObject object)
{
if (generator instanceof BukkitPlotGenerator)
{
public void processSetup(final SetupObject object) {
if (generator instanceof BukkitPlotGenerator) {
((BukkitPlotGenerator) generator).processSetup(object);
}
}
}

View File

@ -41,9 +41,8 @@ import com.intellectualcrafters.plot.object.SetupObject;
import com.intellectualcrafters.plot.util.ChunkManager;
import com.plotsquared.bukkit.listeners.WorldEvents;
public abstract class BukkitPlotGenerator extends ChunkGenerator
{
public abstract class BukkitPlotGenerator extends ChunkGenerator {
public static short[][][] CACHE_I = null;
public static short[][][] CACHE_J = null;
public int X;
@ -51,25 +50,19 @@ public abstract class BukkitPlotGenerator extends ChunkGenerator
private boolean loaded = false;
private short[][] result;
private final PseudoRandom random = new PseudoRandom();
public BukkitPlotGenerator(final String world)
{
public BukkitPlotGenerator(final String world) {
WorldEvents.lastWorld = world;
initCache();
}
public void initCache()
{
if (CACHE_I == null)
{
public void initCache() {
if (CACHE_I == null) {
CACHE_I = new short[256][16][16];
CACHE_J = new short[256][16][16];
for (int x = 0; x < 16; x++)
{
for (int z = 0; z < 16; z++)
{
for (int y = 0; y < 256; y++)
{
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
for (int y = 0; y < 256; y++) {
final short i = (short) (y >> 4);
final short j = (short) (((y & 0xF) << 8) | (z << 4) | x);
CACHE_I[y][x][z] = i;
@ -79,31 +72,24 @@ public abstract class BukkitPlotGenerator extends ChunkGenerator
}
}
}
@SuppressWarnings("unchecked")
@Override
public List<BlockPopulator> getDefaultPopulators(final World world)
{
try
{
if (!loaded)
{
public List<BlockPopulator> getDefaultPopulators(final World world) {
try {
if (!loaded) {
final String name = WorldEvents.getName(world);
PS.get().loadWorld(name, new BukkitGeneratorWrapper(name, this));
final PlotWorld plotworld = PS.get().getPlotWorld(WorldEvents.getName(world));
if (!plotworld.MOB_SPAWNING)
{
if (!plotworld.SPAWN_EGGS)
{
if (!plotworld.MOB_SPAWNING) {
if (!plotworld.SPAWN_EGGS) {
world.setSpawnFlags(false, false);
}
world.setAmbientSpawnLimit(0);
world.setAnimalSpawnLimit(0);
world.setMonsterSpawnLimit(0);
world.setWaterAnimalSpawnLimit(0);
}
else
{
} else {
world.setSpawnFlags(true, true);
world.setAmbientSpawnLimit(-1);
world.setAnimalSpawnLimit(-1);
@ -113,30 +99,24 @@ public abstract class BukkitPlotGenerator extends ChunkGenerator
loaded = true;
return (List<BlockPopulator>) (List<?>) getPopulators(WorldEvents.getName(world));
}
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
}
return new ArrayList<BlockPopulator>();
}
/**
* Set the result;
* @param result
*/
public void setResult(final short[][] result)
{
public void setResult(final short[][] result) {
this.result = result;
}
@Override
public short[][] generateExtBlockSections(final World world, final Random r, final int cx, final int cz, final BiomeGrid biomes)
{
try
{
if (!loaded)
{
public short[][] generateExtBlockSections(final World world, final Random r, final int cx, final int cz, final BiomeGrid biomes) {
try {
if (!loaded) {
final String name = WorldEvents.getName(world);
PS.get().loadWorld(name, new BukkitGeneratorWrapper(name, this));
loaded = true;
@ -149,22 +129,17 @@ public abstract class BukkitPlotGenerator extends ChunkGenerator
result = new short[16][];
X = cx << 4;
Z = cz << 4;
if (ChunkManager.FORCE_PASTE)
{
if (ChunkManager.FORCE_PASTE) {
final PlotWorld plotworld = PS.get().getPlotWorld(world.getName());
final Biome biome = Biome.valueOf(plotworld.PLOT_BIOME);
for (short x = 0; x < 16; x++)
{
for (short z = 0; z < 16; z++)
{
if (biomes != null)
{
for (short x = 0; x < 16; x++) {
for (short z = 0; z < 16; z++) {
if (biomes != null) {
biomes.setBiome(x, z, biome);
}
final PlotLoc loc = new PlotLoc((X + x), (Z + z));
final HashMap<Short, Short> blocks = ChunkManager.GENERATE_BLOCKS.get(loc);
for (final Entry<Short, Short> entry : blocks.entrySet())
{
for (final Entry<Short, Short> entry : blocks.entrySet()) {
setBlock(x, entry.getKey(), z, entry.getValue());
}
}
@ -172,57 +147,45 @@ public abstract class BukkitPlotGenerator extends ChunkGenerator
return result;
}
generateChunk(world, ChunkManager.CURRENT_PLOT_CLEAR, random, cx, cz, biomes);
if (ChunkManager.CURRENT_PLOT_CLEAR != null)
{
if (ChunkManager.CURRENT_PLOT_CLEAR != null) {
PlotLoc loc;
for (final Entry<PlotLoc, HashMap<Short, Short>> entry : ChunkManager.GENERATE_BLOCKS.entrySet())
{
for (final Entry<Short, Short> entry2 : entry.getValue().entrySet())
{
for (final Entry<PlotLoc, HashMap<Short, Short>> entry : ChunkManager.GENERATE_BLOCKS.entrySet()) {
for (final Entry<Short, Short> entry2 : entry.getValue().entrySet()) {
loc = entry.getKey();
final int xx = loc.x - X;
final int zz = loc.z - Z;
if ((xx >= 0) && (xx < 16))
{
if ((zz >= 0) && (zz < 16))
{
if ((xx >= 0) && (xx < 16)) {
if ((zz >= 0) && (zz < 16)) {
setBlock(xx, entry2.getKey(), zz, entry2.getValue());
}
}
}
}
}
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
}
return result;
}
public void setBlock(final int x, final int y, final int z, final short blkid)
{
if (result[CACHE_I[y][x][z]] == null)
{
public void setBlock(final int x, final int y, final int z, final short blkid) {
if (result[CACHE_I[y][x][z]] == null) {
result[CACHE_I[y][x][z]] = new short[4096];
}
result[CACHE_I[y][x][z]][CACHE_J[y][x][z]] = blkid;
}
public void setBlock(final int x, final int y, final int z, final short[] blkid)
{
if (blkid.length == 1)
{
public void setBlock(final int x, final int y, final int z, final short[] blkid) {
if (blkid.length == 1) {
setBlock(x, y, z, blkid[0]);
}
final short id = blkid[random.random(blkid.length)];
if (result[CACHE_I[y][x][z]] == null)
{
if (result[CACHE_I[y][x][z]] == null) {
result[CACHE_I[y][x][z]] = new short[4096];
}
result[CACHE_I[y][x][z]][CACHE_J[y][x][z]] = id;
}
/**
* check if a region contains a location. (x, z) must be between [0,15], [0,15]
* @param plot
@ -230,22 +193,20 @@ public abstract class BukkitPlotGenerator extends ChunkGenerator
* @param z
* @return
*/
public boolean contains(final RegionWrapper plot, final int x, final int z)
{
public boolean contains(final RegionWrapper plot, final int x, final int z) {
final int xx = X + x;
final int zz = Z + z;
return ((xx >= plot.minX) && (xx <= plot.maxX) && (zz >= plot.minZ) && (zz <= plot.maxZ));
}
/**
* Allow spawning everywhere
*/
@Override
public boolean canSpawn(final World world, final int x, final int z)
{
public boolean canSpawn(final World world, final int x, final int z) {
return true;
}
/**
* <b>random</b> is an optimized random number generator.<br>
* - Change the state to have the same chunk random each time it generates<br>
@ -266,35 +227,34 @@ public abstract class BukkitPlotGenerator extends ChunkGenerator
* @return
*/
public abstract void generateChunk(final World world, final RegionWrapper requiredRegion, final PseudoRandom random, final int cx, final int cz, final BiomeGrid biomes);
public abstract List<BukkitPlotPopulator> getPopulators(final String world);
/**
* This is called when the generator is initialized.
* You don't need to do anything with it necessarily.
* @param plotworld
*/
public abstract void init(final PlotWorld plotworld);
/**
* Return a new instance of the PlotWorld for a world
* @param world
* @return
*/
public abstract PlotWorld getNewPlotWorld(final String world);
/**
* Get the PlotManager class for this generator
* @return
*/
public abstract PlotManager getPlotManager();
/**
* If you need to do anything fancy for /plot setup<br>
* - Otherwise it will just use the PlotWorld configuration<br>
* Feel free to extend BukkitSetupUtils and customize world creation
* @param object
*/
public void processSetup(final SetupObject object)
{}
public void processSetup(final SetupObject object) {}
}

View File

@ -15,33 +15,27 @@ import com.intellectualcrafters.plot.object.RegionWrapper;
import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.SetBlockQueue;
public abstract class BukkitPlotPopulator extends BlockPopulator
{
public abstract class BukkitPlotPopulator extends BlockPopulator {
private final PseudoRandom random = new PseudoRandom();
public int X;
public int Z;
public String worldname;
private World world;
@Override
public void populate(final World world, final Random rand, final Chunk chunk)
{
public void populate(final World world, final Random rand, final Chunk chunk) {
this.world = world;
worldname = world.getName();
X = chunk.getX() << 4;
Z = chunk.getZ() << 4;
if (ChunkManager.FORCE_PASTE)
{
for (short x = 0; x < 16; x++)
{
for (short z = 0; z < 16; z++)
{
if (ChunkManager.FORCE_PASTE) {
for (short x = 0; x < 16; x++) {
for (short z = 0; z < 16; z++) {
final PlotLoc loc = new PlotLoc((short) (X + x), (short) (Z + z));
final HashMap<Short, Byte> blocks = ChunkManager.GENERATE_DATA.get(loc);
for (final Entry<Short, Byte> entry : blocks.entrySet())
{
for (final Entry<Short, Byte> entry : blocks.entrySet()) {
setBlock(x, entry.getKey(), z, entry.getValue());
}
}
@ -49,20 +43,15 @@ public abstract class BukkitPlotPopulator extends BlockPopulator
return;
}
populate(world, ChunkManager.CURRENT_PLOT_CLEAR, random, X, Z);
if (ChunkManager.CURRENT_PLOT_CLEAR != null)
{
if (ChunkManager.CURRENT_PLOT_CLEAR != null) {
PlotLoc loc;
for (final Entry<PlotLoc, HashMap<Short, Byte>> entry : ChunkManager.GENERATE_DATA.entrySet())
{
for (final Entry<Short, Byte> entry2 : entry.getValue().entrySet())
{
for (final Entry<PlotLoc, HashMap<Short, Byte>> entry : ChunkManager.GENERATE_DATA.entrySet()) {
for (final Entry<Short, Byte> entry2 : entry.getValue().entrySet()) {
loc = entry.getKey();
final int xx = loc.x - X;
final int zz = loc.z - Z;
if ((xx >= 0) && (xx < 16))
{
if ((zz >= 0) && (zz < 16))
{
if ((xx >= 0) && (xx < 16)) {
if ((zz >= 0) && (zz < 16)) {
setBlock(xx, entry2.getKey(), zz, entry2.getValue());
}
}
@ -70,9 +59,9 @@ public abstract class BukkitPlotPopulator extends BlockPopulator
}
}
}
public abstract void populate(final World world, final RegionWrapper requiredRegion, final PseudoRandom random, final int cx, final int cz);
/**
* Set the id and data at a location. (x, y, z) must be between [0,15], [0,255], [0,15]
* @param x
@ -81,18 +70,14 @@ public abstract class BukkitPlotPopulator extends BlockPopulator
* @param id
* @param data
*/
public void setBlock(final int x, final int y, final int z, final short id, final byte data)
{
if (data == 0)
{
public void setBlock(final int x, final int y, final int z, final short id, final byte data) {
if (data == 0) {
SetBlockQueue.setBlock(worldname, x, y, z, id);
}
else
{
} else {
SetBlockQueue.setBlock(worldname, x, y, z, new PlotBlock(id, data));
}
}
/**
* Set the data at a location. (x, y, z) must be between [0,15], [0,255], [0,15]
* @param x
@ -100,14 +85,12 @@ public abstract class BukkitPlotPopulator extends BlockPopulator
* @param z
* @param data
*/
public void setBlock(final int x, final int y, final int z, final byte data)
{
if (data != 0)
{
public void setBlock(final int x, final int y, final int z, final byte data) {
if (data != 0) {
world.getBlockAt(X + x, y, Z + z).setData(data);
}
}
/**
* Like setblock, but lacks the data != 0 check
* @param x
@ -115,11 +98,10 @@ public abstract class BukkitPlotPopulator extends BlockPopulator
* @param z
* @param data
*/
public void setBlockAbs(final int x, final int y, final int z, final byte data)
{
public void setBlockAbs(final int x, final int y, final int z, final byte data) {
world.getBlockAt(X + x, y, Z + z).setData(data);
}
/**
* check if a region contains a location. (x, z) must be between [0,15], [0,15]
* @param plot
@ -127,11 +109,10 @@ public abstract class BukkitPlotPopulator extends BlockPopulator
* @param z
* @return
*/
public boolean contains(final RegionWrapper plot, final int x, final int z)
{
public boolean contains(final RegionWrapper plot, final int x, final int z) {
final int xx = X + x;
final int zz = Z + z;
return ((xx >= plot.minX) && (xx <= plot.maxX) && (zz >= plot.minZ) && (zz <= plot.maxZ));
}
}

View File

@ -43,14 +43,12 @@ import com.intellectualcrafters.plot.object.RegionWrapper;
* mean world generation may take somewhat longer
*
*/
public class HybridGen extends BukkitPlotGenerator
{
*/
public class HybridGen extends BukkitPlotGenerator {
public HybridGen(final String world) {
super(world);
super(world);
}
/**
@ -79,15 +77,13 @@ public class HybridGen extends BukkitPlotGenerator
short pathWidthLower;
short pathWidthUpper;
boolean doState = false;
int maxY = 0;
int maxY = 0;
short[][] cached;
/**
* Initialize variables, and create plotworld object used in calculations
*/
@Override
public void init(final PlotWorld plotworld)
{
*/
@Override
public void init(final PlotWorld plotworld) {
if (plotworld != null) {
this.plotworld = (HybridPlotWorld) plotworld;
@ -97,185 +93,143 @@ public class HybridGen extends BukkitPlotGenerator
roadblock = this.plotworld.ROAD_BLOCK.id;
wallfilling = this.plotworld.WALL_FILLING.id;
size = pathsize + plotsize;
wall = this.plotworld.WALL_BLOCK.id;
plotfloors = new short[this.plotworld.TOP_BLOCK.length];
wall = this.plotworld.WALL_BLOCK.id;
plotfloors = new short[this.plotworld.TOP_BLOCK.length];
for (int i = 0; i < this.plotworld.TOP_BLOCK.length; i++) {
plotfloors[i] = this.plotworld.TOP_BLOCK[i].id;
}
filling = new short[this.plotworld.MAIN_BLOCK.length];
}
filling = new short[this.plotworld.MAIN_BLOCK.length];
for (int i = 0; i < this.plotworld.MAIN_BLOCK.length; i++) {
filling[i] = this.plotworld.MAIN_BLOCK[i].id;
}
filling[i] = this.plotworld.MAIN_BLOCK[i].id;
}
if ((filling.length > 1) || (plotfloors.length > 1)) {
doState = true;
}
wallheight = this.plotworld.WALL_HEIGHT;
roadheight = this.plotworld.ROAD_HEIGHT;
plotheight = this.plotworld.PLOT_HEIGHT;
roadheight = this.plotworld.ROAD_HEIGHT;
plotheight = this.plotworld.PLOT_HEIGHT;
if (pathsize == 0) {
pathWidthLower = (short) -1;
pathWidthUpper = (short) (plotsize + 1);
}
else
{
pathWidthLower = (short) -1;
pathWidthUpper = (short) (plotsize + 1);
} else {
{
pathWidthLower = (short) (Math.floor(pathsize / 2) - 1);
}
if ((pathsize % 2) == 0) {
pathWidthLower = (short) (Math.floor(pathsize / 2) - 1);
} else {
pathWidthLower = (short) (Math.floor(pathsize / 2));
}
pathWidthUpper = (short) (pathWidthLower + plotsize + 1);
}
biome = Biome.valueOf(this.plotworld.PLOT_BIOME);
}
biome = Biome.valueOf(this.plotworld.PLOT_BIOME);
{
maxY = Bukkit.getWorld(plotworld.worldname).getMaxHeight();
}
catch (final NullPointerException e)
{}
try {
maxY = Bukkit.getWorld(plotworld.worldname).getMaxHeight();
} catch (final NullPointerException e) {}
if (maxY == 0) {
maxY = 256;
maxY = 256;
}
// create cached chunk (for optimized chunk generation)
// create cached chunk (for optimized chunk generation)
{
cached = new short[(plotheight + 16) / 16][];
if (!this.plotworld.PLOT_SCHEMATIC) {
cached = new short[(plotheight + 16) / 16][];
for (int i = 0; i < cached.length; i++) {
cached[i] = new short[4096];
}
final PseudoRandom random = new PseudoRandom();
for (int x = 0; x < 16; x++)
{
}
final PseudoRandom random = new PseudoRandom();
for (int x = 0; x < 16; x++) {
{
cached[CACHE_I[plotheight][x][z]][CACHE_J[plotheight][x][z]] = plotfloors[random.random(plotfloors.length)];
for (int z = 0; z < 16; z++) {
cached[CACHE_I[plotheight][x][z]][CACHE_J[plotheight][x][z]] = plotfloors[random.random(plotfloors.length)];
if (this.plotworld.PLOT_BEDROCK) {
cached[CACHE_I[0][x][z]][CACHE_J[0][x][z]] = 7;
}
cached[CACHE_I[0][x][z]][CACHE_J[0][x][z]] = 7;
}
for (int y = 1; y < plotheight; y++) {
cached[CACHE_I[y][x][z]][CACHE_J[y][x][z]] = filling[random.random(filling.length)];
}
}
}
}
}
}
/**
* Return the plot manager for this type of generator, or create one For square plots you may as well use the
* default plot manager which comes with PlotSquared
*/
@Override
public PlotManager getPlotManager()
{
*/
@Override
public PlotManager getPlotManager() {
if (HybridGen.manager == null) {
HybridGen.manager = new HybridPlotManager();
}
return HybridGen.manager;
return HybridGen.manager;
}
/**
* Get a new plotworld class For square plots you can use the DefaultPlotWorld class which comes with PlotSquared
*/
@Override
public PlotWorld getNewPlotWorld(final String world)
{
*/
@Override
public PlotWorld getNewPlotWorld(final String world) {
if (plotworld == null) {
plotworld = new HybridPlotWorld(world);
}
return plotworld;
return plotworld;
}
/**
* Return the block populator
*/
@Override
*/
@Override
public List<BukkitPlotPopulator> getPopulators(final String world) {
// You can have as many populators as you would like, e.g. tree
// populator, ore populator
return Arrays.asList((BukkitPlotPopulator) new HybridPop(plotworld));
return Arrays.asList((BukkitPlotPopulator) new HybridPop(plotworld));
}
/**
* This part is a fucking mess. - Refer to a proper tutorial if you would like to learn how to make a world
* generator
*/
@Override
*/
@Override
public void generateChunk(final World world, final RegionWrapper region, final PseudoRandom random, final int cx, final int cz, final BiomeGrid biomes) {
int sx = (short) ((X - plotworld.ROAD_OFFSET_X) % size);
int sz = (short) ((Z - plotworld.ROAD_OFFSET_Z) % size);
int sx = (short) ((X - plotworld.ROAD_OFFSET_X) % size);
int sz = (short) ((Z - plotworld.ROAD_OFFSET_Z) % size);
if (sx < 0) {
sx += size;
}
sx += size;
}
if (sz < 0) {
sz += size;
}
if (biomes != null)
{
for (short x = 0; x < 16; x++)
{
sz += size;
}
if (biomes != null) {
for (short x = 0; x < 16; x++) {
for (short z = 0; z < 16; z++) {
biomes.setBiome(x, z, biome);
}
}
}
if (cached != null)
{
}
}
if (cached != null) {
if ((sx > pathWidthLower) && (sz > pathWidthLower) && ((sx + 15) < pathWidthUpper) && ((sz + 15) < pathWidthUpper)) {
setResult(cached);
return;
}
}
if (plotworld.PLOT_BEDROCK)
{
for (short x = 0; x < 16; x++)
{
}
}
if (plotworld.PLOT_BEDROCK) {
for (short x = 0; x < 16; x++) {
for (short z = 0; z < 16; z++) {
setBlock(x, 0, z, (short) 7);
}
}
}
if (region != null)
{
}
}
if (region != null) {
{
final int absX = ((sx + x) % size);
for (short z = 0; z < 16; z++)
{
if (contains(region, x, z))
{
for (short x = 0; x < 16; x++) {
final int absX = ((sx + x) % size);
for (short z = 0; z < 16; z++) {
if (contains(region, x, z)) {
for (short y = 1; y < plotheight; y++) {
setBlock(x, y, z, filling);
}
setBlock(x, plotheight, z, plotfloors);
final int absZ = ((sz + z) % size);
final PlotLoc loc = new PlotLoc(absX, absZ);
final HashMap<Short, Short> blocks = plotworld.G_SCH.get(loc);
if (blocks != null)
{
final PlotLoc loc = new PlotLoc(absX, absZ);
final HashMap<Short, Short> blocks = plotworld.G_SCH.get(loc);
if (blocks != null) {
for (final Entry<Short, Short> entry : blocks.entrySet()) {
setBlock(x, plotheight + entry.getKey(), z, entry.getValue());
@ -284,68 +238,51 @@ public class HybridGen extends BukkitPlotGenerator
}
}
}
return;
}
return;
}
for (short x = 0; x < 16; x++) {
final int absX = ((sx + x) % size);
final boolean gx = absX > pathWidthLower;
final boolean lx = absX < pathWidthUpper;
final boolean gx = absX > pathWidthLower;
final boolean lx = absX < pathWidthUpper;
for (short z = 0; z < 16; z++) {
final int absZ = ((sz + z) % size);
final boolean gz = absZ > pathWidthLower;
final boolean lz = absZ < pathWidthUpper;
// inside plot
if (gx && gz && lx && lz)
{
final boolean lz = absZ < pathWidthUpper;
// inside plot
if (gx && gz && lx && lz) {
for (short y = 1; y < plotheight; y++) {
setBlock(x, y, z, filling);
}
setBlock(x, plotheight, z, plotfloors);
}
setBlock(x, plotheight, z, plotfloors);
if (plotworld.PLOT_SCHEMATIC) {
final PlotLoc loc = new PlotLoc(absX, absZ);
final HashMap<Short, Short> blocks = plotworld.G_SCH.get(loc);
if (blocks != null)
{
final PlotLoc loc = new PlotLoc(absX, absZ);
final HashMap<Short, Short> blocks = plotworld.G_SCH.get(loc);
if (blocks != null) {
for (final Entry<Short, Short> entry : blocks.entrySet()) {
setBlock(x, plotheight + entry.getKey(), z, entry.getValue());
}
}
}
}
}
}
{
// wall
if (((absX >= pathWidthLower) && (absX <= pathWidthUpper) && (absZ >= pathWidthLower) && (absZ <= pathWidthUpper)))
{
} else if (pathsize != 0) {
// wall
if (((absX >= pathWidthLower) && (absX <= pathWidthUpper) && (absZ >= pathWidthLower) && (absZ <= pathWidthUpper))) {
for (short y = 1; y <= wallheight; y++) {
setBlock(x, y, z, wallfilling);
}
setBlock(x, y, z, wallfilling);
}
if (!plotworld.ROAD_SCHEMATIC_ENABLED) {
setBlock(x, wallheight + 1, z, wall);
}
}
// road
else
{
}
// road
else {
for (short y = 1; y <= roadheight; y++) {
setBlock(x, y, z, roadblock);
}
}
}
}
if (plotworld.ROAD_SCHEMATIC_ENABLED) {
final PlotLoc loc = new PlotLoc(absX, absZ);
final HashMap<Short, Short> blocks = plotworld.G_SCH.get(loc);
if (blocks != null)
{
final PlotLoc loc = new PlotLoc(absX, absZ);
final HashMap<Short, Short> blocks = plotworld.G_SCH.get(loc);
if (blocks != null) {
for (final Entry<Short, Short> entry : blocks.entrySet()) {
setBlock(x, roadheight + entry.getKey(), z, entry.getValue());

View File

@ -17,8 +17,7 @@ import com.intellectualcrafters.plot.util.BlockManager;
/**
*/
public class HybridPop extends BukkitPlotPopulator
*/
public class HybridPop extends BukkitPlotPopulator {
/*
* Sorry, this isn't well documented at the moment.
@ -42,9 +41,8 @@ public class HybridPop extends BukkitPlotPopulator
Biome biome;
private long state;
private boolean doFilling = false;
private boolean doFloor = false;
public HybridPop(final PlotWorld pw)
private boolean doFloor = false;
public HybridPop(final PlotWorld pw) {
plotworld = (HybridPlotWorld) pw;
// save configuration
@ -56,125 +54,95 @@ public class HybridPop extends BukkitPlotPopulator
wall = plotworld.WALL_BLOCK.data;
int count1 = 0;
int count2 = 0;
plotfloors = new byte[plotworld.TOP_BLOCK.length];
for (int i = 0; i < plotworld.TOP_BLOCK.length; i++)
plotfloors = new byte[plotworld.TOP_BLOCK.length];
for (int i = 0; i < plotworld.TOP_BLOCK.length; i++) {
count1++;
plotfloors[i] = plotworld.TOP_BLOCK[i].data;
if (plotworld.TOP_BLOCK[i].data != 0)
plotfloors[i] = plotworld.TOP_BLOCK[i].data;
if (plotworld.TOP_BLOCK[i].data != 0) {
doFloor = true;
}
}
filling = new byte[plotworld.MAIN_BLOCK.length];
for (int i = 0; i < plotworld.MAIN_BLOCK.length; i++)
filling = new byte[plotworld.MAIN_BLOCK.length];
for (int i = 0; i < plotworld.MAIN_BLOCK.length; i++) {
count2++;
filling[i] = plotworld.MAIN_BLOCK[i].data;
if (plotworld.MAIN_BLOCK[i].data != 0)
filling[i] = plotworld.MAIN_BLOCK[i].data;
if (plotworld.MAIN_BLOCK[i].data != 0) {
doFilling = true;
}
}
if (((count1 > 0) && doFloor) || ((count2 > 0) && doFilling))
}
if (((count1 > 0) && doFloor) || ((count2 > 0) && doFilling)) {}
wallheight = plotworld.WALL_HEIGHT;
roadheight = plotworld.ROAD_HEIGHT;
plotheight = plotworld.PLOT_HEIGHT;
if (pathsize == 0)
plotheight = plotworld.PLOT_HEIGHT;
if (pathsize == 0) {
pathWidthLower = (short) -1;
pathWidthUpper = (short) (plotsize + 1);
}
else
{
if ((pathsize % 2) == 0)
pathWidthUpper = (short) (plotsize + 1);
} else {
if ((pathsize % 2) == 0) {
pathWidthLower = (short) (Math.floor(pathsize / 2) - 1);
}
else
pathWidthLower = (short) (Math.floor(pathsize / 2) - 1);
} else {
pathWidthLower = (short) (Math.floor(pathsize / 2));
}
pathWidthUpper = (short) (pathWidthLower + plotsize + 1);
}
}
public final long nextLong()
}
public final long nextLong() {
final long a = state;
state = xorShift64(a);
return a;
}
public final long xorShift64(long a)
}
public final long xorShift64(long a) {
a ^= (a << 21);
a ^= (a >>> 35);
a ^= (a << 4);
return a;
}
public final int random(final int n)
}
public final int random(final int n) {
final long result = ((nextLong() >>> 32) * n) >> 32;
return (int) result;
}
}
@Override
public void populate(final World world, final RegionWrapper requiredRegion, final PseudoRandom random, final int cx, final int cz)
@Override
public void populate(final World world, final RegionWrapper requiredRegion, final PseudoRandom random, final int cx, final int cz) {
PS.get().getPlotManager(world.getName());
PS.get().getPlotManager(world.getName());
int sx = (short) ((X - plotworld.ROAD_OFFSET_X) % size);
int sz = (short) ((Z - plotworld.ROAD_OFFSET_Z) % size);
if (sx < 0)
int sz = (short) ((Z - plotworld.ROAD_OFFSET_Z) % size);
if (sx < 0) {
sx += size;
}
if (sz < 0)
}
if (sz < 0) {
sz += size;
}
if (requiredRegion != null)
{
for (short x = 0; x < 16; x++)
{
for (short z = 0; z < 16; z++)
{
if (contains(requiredRegion, x, z))
{
if (doFilling)
{
for (short y = 1; y < plotheight; y++)
}
if (requiredRegion != null) {
for (short x = 0; x < 16; x++) {
for (short z = 0; z < 16; z++) {
if (contains(requiredRegion, x, z)) {
if (doFilling) {
for (short y = 1; y < plotheight; y++) {
setBlock(x, y, z, filling);
}
}
if (doFloor)
}
if (doFloor) {
setBlock(x, (short) plotheight, z, plotfloors);
}
if (plotworld.PLOT_SCHEMATIC)
}
if (plotworld.PLOT_SCHEMATIC) {
final int absX = ((sx + x) % size);
final int absZ = ((sz + z) % size);
final PlotLoc loc = new PlotLoc(absX, absZ);
final HashMap<Short, Byte> blocks = plotworld.G_SCH_DATA.get(loc);
if (blocks != null)
{
for (final short y : blocks.keySet())
final HashMap<Short, Byte> blocks = plotworld.G_SCH_DATA.get(loc);
if (blocks != null) {
for (final short y : blocks.keySet()) {
setBlockAbs(x, (short) (plotheight + y), z, blocks.get(y));
}
}
if (plotworld.G_SCH_STATE != null)
}
if (plotworld.G_SCH_STATE != null) {
final HashSet<PlotItem> states = plotworld.G_SCH_STATE.get(loc);
if (states != null)
{
for (final PlotItem items : states)
final HashSet<PlotItem> states = plotworld.G_SCH_STATE.get(loc);
if (states != null) {
for (final PlotItem items : states) {
BlockManager.manager.addItems(plotworld.worldname, items);
}
@ -185,11 +153,9 @@ public class HybridPop extends BukkitPlotPopulator
}
}
return;
}
for (short x = 0; x < 16; x++)
{
for (short z = 0; z < 16; z++)
}
for (short x = 0; x < 16; x++) {
for (short z = 0; z < 16; z++) {
final int absX = ((sx + x) % size);
final int absZ = ((sz + z) % size);
@ -197,31 +163,23 @@ public class HybridPop extends BukkitPlotPopulator
final boolean gz = absZ > pathWidthLower;
final boolean lx = absX < pathWidthUpper;
final boolean lz = absZ < pathWidthUpper;
// inside plot
if (gx && gz && lx && lz)
{
for (short y = 1; y < plotheight; y++)
// inside plot
if (gx && gz && lx && lz) {
for (short y = 1; y < plotheight; y++) {
setBlock(x, y, z, filling);
}
setBlock(x, (short) plotheight, z, plotfloors);
if (plotworld.PLOT_SCHEMATIC)
setBlock(x, (short) plotheight, z, plotfloors);
if (plotworld.PLOT_SCHEMATIC) {
final PlotLoc loc = new PlotLoc(absX, absZ);
final HashMap<Short, Byte> blocks = plotworld.G_SCH_DATA.get(loc);
if (blocks != null)
{
for (final short y : blocks.keySet())
final HashMap<Short, Byte> blocks = plotworld.G_SCH_DATA.get(loc);
if (blocks != null) {
for (final short y : blocks.keySet()) {
setBlockAbs(x, (short) (plotheight + y), z, blocks.get(y));
}
}
if (plotworld.G_SCH_STATE != null)
}
if (plotworld.G_SCH_STATE != null) {
final HashSet<PlotItem> states = plotworld.G_SCH_STATE.get(loc);
if (states != null)
{
for (final PlotItem items : states)
final HashSet<PlotItem> states = plotworld.G_SCH_STATE.get(loc);
if (states != null) {
for (final PlotItem items : states) {
items.x = X + x;
items.z = Z + z;
@ -229,37 +187,27 @@ public class HybridPop extends BukkitPlotPopulator
}
}
}
}
}
else if (pathsize != 0)
}
} else if (pathsize != 0) {
// wall
if (((absX >= pathWidthLower) && (absX <= pathWidthUpper) && (absZ >= pathWidthLower) && (absZ <= pathWidthUpper)))
{
for (short y = 1; y <= wallheight; y++)
// wall
if (((absX >= pathWidthLower) && (absX <= pathWidthUpper) && (absZ >= pathWidthLower) && (absZ <= pathWidthUpper))) {
for (short y = 1; y <= wallheight; y++) {
setBlock(x, y, z, wallfilling);
}
if (!plotworld.ROAD_SCHEMATIC_ENABLED)
}
if (!plotworld.ROAD_SCHEMATIC_ENABLED) {
setBlock(x, wallheight + 1, z, wall);
}
}
// road
else
{
for (short y = 1; y <= roadheight; y++)
// road
else {
for (short y = 1; y <= roadheight; y++) {
setBlock(x, y, z, roadblock);
}
}
if (plotworld.ROAD_SCHEMATIC_ENABLED)
}
if (plotworld.ROAD_SCHEMATIC_ENABLED) {
final PlotLoc loc = new PlotLoc(absX, absZ);
final HashMap<Short, Byte> blocks = plotworld.G_SCH_DATA.get(loc);
if (blocks != null)
{
for (final short y : blocks.keySet())
final HashMap<Short, Byte> blocks = plotworld.G_SCH_DATA.get(loc);
if (blocks != null) {
for (final short y : blocks.keySet()) {
setBlockAbs(x, (short) (roadheight + y), z, blocks.get(y));
}
@ -268,15 +216,11 @@ public class HybridPop extends BukkitPlotPopulator
}
}
}
}
private void setBlock(final short x, final short y, final short z, final byte[] blkids)
{
if (blkids.length == 1)
}
private void setBlock(final short x, final short y, final short z, final byte[] blkids) {
if (blkids.length == 1) {
setBlock(x, y, z, blkids[0]);
}
else
setBlock(x, y, z, blkids[0]);
} else {
final int i = random(blkids.length);
setBlock(x, y, z, blkids[i]);

View File

@ -36,132 +36,106 @@ import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
public class ChunkListener implements Listener
{
public class ChunkListener implements Listener {
private Chunk lastChunk = null;
final RefClass classChunk = getRefClass("{nms}.Chunk");
final RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
final RefMethod methodGetHandleChunk;
final RefField mustSave = classChunk.getField("mustSave");
public ChunkListener()
{
public ChunkListener() {
RefMethod method;
try
{
try {
method = classCraftChunk.getMethod("getHandle");
}
catch (final Exception e)
{
} catch (final Exception e) {
method = null;
e.printStackTrace();
}
methodGetHandleChunk = method;
if (!Settings.CHUNK_PROCESSOR_GC) { return; }
TaskManager.runTaskRepeat(new Runnable()
{
if (!Settings.CHUNK_PROCESSOR_GC) {
return;
}
TaskManager.runTaskRepeat(new Runnable() {
@Override
public void run()
{
public void run() {
final int distance = Bukkit.getViewDistance() + 1;
final HashMap<String, HashMap<ChunkLoc, Integer>> players = new HashMap<>();
for (final Entry<String, PlotPlayer> entry : UUIDHandler.getPlayers().entrySet())
{
for (final Entry<String, PlotPlayer> entry : UUIDHandler.getPlayers().entrySet()) {
final PlotPlayer pp = entry.getValue();
final Location loc = pp.getLocation();
final String world = loc.getWorld();
if (!PS.get().isPlotWorld(world))
{
if (!PS.get().isPlotWorld(world)) {
continue;
}
HashMap<ChunkLoc, Integer> map = players.get(world);
if (map == null)
{
if (map == null) {
map = new HashMap<>();
players.put(world, map);
}
final ChunkLoc origin = new ChunkLoc(loc.getX() >> 4, loc.getZ() >> 4);
Integer val = map.get(origin);
int check;
if (val != null)
{
if (val == distance)
{
if (val != null) {
if (val == distance) {
continue;
}
check = distance - val;
}
else
{
} else {
check = distance;
map.put(origin, distance);
}
for (int x = -distance; x <= distance; x++)
{
if ((x >= check) || (-x >= check))
{
for (int x = -distance; x <= distance; x++) {
if ((x >= check) || (-x >= check)) {
continue;
}
for (int z = -distance; z <= distance; z++)
{
if ((z >= check) || (-z >= check))
{
for (int z = -distance; z <= distance; z++) {
if ((z >= check) || (-z >= check)) {
continue;
}
final int weight = distance - Math.max(Math.abs(x), Math.abs(z));
final ChunkLoc chunk = new ChunkLoc(x + origin.x, z + origin.z);
val = map.get(chunk);
if ((val == null) || (val < weight))
{
if ((val == null) || (val < weight)) {
map.put(chunk, weight);
}
}
}
}
for (final World world : Bukkit.getWorlds())
{
for (final World world : Bukkit.getWorlds()) {
final String name = world.getName();
final boolean autosave = world.isAutoSave();
if (!PS.get().isPlotWorld(name))
{
if (!PS.get().isPlotWorld(name)) {
continue;
}
if (!Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE && autosave)
{
if (!Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE && autosave) {
world.setAutoSave(false);
}
final HashMap<ChunkLoc, Integer> map = players.get(name);
if ((map == null) || (map.size() == 0))
{
if ((map == null) || (map.size() == 0)) {
continue;
}
for (final Chunk chunk : world.getLoadedChunks())
{
for (final Chunk chunk : world.getLoadedChunks()) {
final int x = chunk.getX();
final int z = chunk.getZ();
if (!map.containsKey(new ChunkLoc(x, z)))
{
if (!Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE || !unloadChunk(name, chunk))
{
if (!map.containsKey(new ChunkLoc(x, z))) {
if (!Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE || !unloadChunk(name, chunk)) {
chunk.unload(true, false);
}
}
}
if (!Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE && autosave)
{
if (!Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE && autosave) {
world.setAutoSave(true);
}
}
}
}, 300);
}
public boolean unloadChunk(final String world, final Chunk chunk)
{
public boolean unloadChunk(final String world, final Chunk chunk) {
final int X = chunk.getX();
final int Z = chunk.getZ();
final int x = X << 4;
@ -170,115 +144,110 @@ public class ChunkListener implements Listener
final int z2 = z + 15;
Plot plot;
plot = MainUtil.getPlot(new Location(world, x, 1, z));
if ((plot != null) && (plot.owner != null)) { return false; }
if ((plot != null) && (plot.owner != null)) {
return false;
}
plot = MainUtil.getPlot(new Location(world, x2, 1, z2));
if ((plot != null) && (plot.owner != null)) { return false; }
if ((plot != null) && (plot.owner != null)) {
return false;
}
plot = MainUtil.getPlot(new Location(world, x2, 1, z));
if ((plot != null) && (plot.owner != null)) { return false; }
if ((plot != null) && (plot.owner != null)) {
return false;
}
plot = MainUtil.getPlot(new Location(world, x, 1, z2));
if ((plot != null) && (plot.owner != null)) { return false; }
if ((plot != null) && (plot.owner != null)) {
return false;
}
plot = MainUtil.getPlot(new Location(world, x + 7, 1, z + 7));
if ((plot != null) && (plot.owner != null)) { return false; }
if ((plot != null) && (plot.owner != null)) {
return false;
}
final Object c = methodGetHandleChunk.of(chunk).call();
mustSave.of(c).set(false);
chunk.unload(false, false);
return true;
}
@EventHandler
public void onChunkUnload(final ChunkUnloadEvent event)
{
if (Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE)
{
public void onChunkUnload(final ChunkUnloadEvent event) {
if (Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE) {
final Chunk chunk = event.getChunk();
final String world = chunk.getWorld().getName();
if (PS.get().isPlotWorld(world))
{
if (unloadChunk(world, chunk)) { return; }
if (PS.get().isPlotWorld(world)) {
if (unloadChunk(world, chunk)) {
return;
}
}
}
if (processChunk(event.getChunk(), true))
{
if (processChunk(event.getChunk(), true)) {
event.setCancelled(true);
}
}
@EventHandler
public void onChunkLoad(final ChunkLoadEvent event)
{
public void onChunkLoad(final ChunkLoadEvent event) {
processChunk(event.getChunk(), false);
}
@EventHandler(priority = EventPriority.LOWEST)
public void onItemSpawn(final ItemSpawnEvent event)
{
public void onItemSpawn(final ItemSpawnEvent event) {
final Item entity = event.getEntity();
final Chunk chunk = entity.getLocation().getChunk();
if (chunk == lastChunk)
{
if (chunk == lastChunk) {
event.getEntity().remove();
event.setCancelled(true);
return;
}
if (!PS.get().isPlotWorld(chunk.getWorld().getName())) { return; }
if (!PS.get().isPlotWorld(chunk.getWorld().getName())) {
return;
}
final Entity[] entities = chunk.getEntities();
if (entities.length > Settings.CHUNK_PROCESSOR_MAX_ENTITIES)
{
if (entities.length > Settings.CHUNK_PROCESSOR_MAX_ENTITIES) {
event.getEntity().remove();
event.setCancelled(true);
lastChunk = chunk;
}
else
{
} else {
lastChunk = null;
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockPhysics(final BlockPhysicsEvent event)
{
if (Settings.CHUNK_PROCESSOR_DISABLE_PHYSICS)
{
public void onBlockPhysics(final BlockPhysicsEvent event) {
if (Settings.CHUNK_PROCESSOR_DISABLE_PHYSICS) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onEntitySpawn(final CreatureSpawnEvent event)
{
public void onEntitySpawn(final CreatureSpawnEvent event) {
final LivingEntity entity = event.getEntity();
final Chunk chunk = entity.getLocation().getChunk();
if (chunk == lastChunk)
{
if (chunk == lastChunk) {
event.getEntity().remove();
event.setCancelled(true);
return;
}
if (!PS.get().isPlotWorld(chunk.getWorld().getName())) { return; }
if (!PS.get().isPlotWorld(chunk.getWorld().getName())) {
return;
}
final Entity[] entities = chunk.getEntities();
if (entities.length > Settings.CHUNK_PROCESSOR_MAX_ENTITIES)
{
if (entities.length > Settings.CHUNK_PROCESSOR_MAX_ENTITIES) {
event.getEntity().remove();
event.setCancelled(true);
lastChunk = chunk;
}
else
{
} else {
lastChunk = null;
}
}
public void cleanChunk(final Chunk chunk)
{
public void cleanChunk(final Chunk chunk) {
TaskManager.index.incrementAndGet();
final Integer currentIndex = TaskManager.index.get();
final Integer task = TaskManager.runTaskRepeat(new Runnable()
{
final Integer task = TaskManager.runTaskRepeat(new Runnable() {
@Override
public void run()
{
if (!chunk.isLoaded())
{
public void run() {
if (!chunk.isLoaded()) {
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex);
PS.debug("[PlotSquared] &aSuccessfully processed and unloaded chunk!");
@ -286,8 +255,7 @@ public class ChunkListener implements Listener
return;
}
final BlockState[] tiles = chunk.getTileEntities();
if (tiles.length == 0)
{
if (tiles.length == 0) {
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex);
PS.debug("[PlotSquared] &aSuccessfully processed and unloaded chunk!");
@ -296,10 +264,8 @@ public class ChunkListener implements Listener
}
final long start = System.currentTimeMillis();
int i = 0;
while ((System.currentTimeMillis() - start) < 250)
{
if (i >= tiles.length)
{
while ((System.currentTimeMillis() - start) < 250) {
if (i >= tiles.length) {
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex);
PS.debug("[PlotSquared] &aSuccessfully processed and unloaded chunk!");
@ -313,33 +279,28 @@ public class ChunkListener implements Listener
}, 5);
TaskManager.tasks.put(currentIndex, task);
}
public boolean processChunk(final Chunk chunk, final boolean unload)
{
if (!PS.get().isPlotWorld(chunk.getWorld().getName())) { return false; }
public boolean processChunk(final Chunk chunk, final boolean unload) {
if (!PS.get().isPlotWorld(chunk.getWorld().getName())) {
return false;
}
final Entity[] entities = chunk.getEntities();
final BlockState[] tiles = chunk.getTileEntities();
if (entities.length > Settings.CHUNK_PROCESSOR_MAX_ENTITIES)
{
for (final Entity ent : entities)
{
if (!(ent instanceof Player))
{
if (entities.length > Settings.CHUNK_PROCESSOR_MAX_ENTITIES) {
for (final Entity ent : entities) {
if (!(ent instanceof Player)) {
ent.remove();
}
}
PS.debug("[PlotSquared] &a detected unsafe chunk and processed: " + (chunk.getX() << 4) + "," + (chunk.getX() << 4));
}
if (tiles.length > Settings.CHUNK_PROCESSOR_MAX_BLOCKSTATES)
{
if (unload)
{
if (tiles.length > Settings.CHUNK_PROCESSOR_MAX_BLOCKSTATES) {
if (unload) {
PS.debug("[PlotSquared] &c detected unsafe chunk: " + (chunk.getX() << 4) + "," + (chunk.getX() << 4));
cleanChunk(chunk);
return true;
}
for (final BlockState tile : tiles)
{
for (final BlockState tile : tiles) {
tile.getBlock().setType(Material.AIR, false);
}
}

View File

@ -40,101 +40,82 @@ import com.plotsquared.bukkit.util.BukkitUtil;
/**
*/
public class ForceFieldListener implements Listener
{
private Set<Player> getNearbyPlayers(final Player player, final Plot plot)
*/
public class ForceFieldListener implements Listener {
private Set<Player> getNearbyPlayers(final Player player, final Plot plot) {
final Set<Player> players = new HashSet<>();
Player oPlayer;
for (final Entity entity : player.getNearbyEntities(5d, 5d, 5d))
{
if (!(entity instanceof Player) || ((oPlayer = (Player) entity) == null) || !BukkitPlayerFunctions.isInPlot(oPlayer) || !BukkitPlayerFunctions.getCurrentPlot(oPlayer).equals(plot))
Player oPlayer;
for (final Entity entity : player.getNearbyEntities(5d, 5d, 5d)) {
if (!(entity instanceof Player) || ((oPlayer = (Player) entity) == null) || !BukkitPlayerFunctions.isInPlot(oPlayer) || !BukkitPlayerFunctions.getCurrentPlot(oPlayer).equals(plot)) {
continue;
}
final UUID uuid = UUIDHandler.getUUID(BukkitUtil.getPlayer(oPlayer));
if (!plot.isAdded(uuid))
final UUID uuid = UUIDHandler.getUUID(BukkitUtil.getPlayer(oPlayer));
if (!plot.isAdded(uuid)) {
players.add(oPlayer);
}
}
return players;
}
private Player hasNearbyPermitted(final Player player, final Plot plot)
}
private Player hasNearbyPermitted(final Player player, final Plot plot) {
Player oPlayer;
for (final Entity entity : player.getNearbyEntities(5d, 5d, 5d))
{
if (!(entity instanceof Player) || ((oPlayer = (Player) entity) == null) || !BukkitPlayerFunctions.isInPlot(oPlayer) || !BukkitPlayerFunctions.getCurrentPlot(oPlayer).equals(plot))
Player oPlayer;
for (final Entity entity : player.getNearbyEntities(5d, 5d, 5d)) {
if (!(entity instanceof Player) || ((oPlayer = (Player) entity) == null) || !BukkitPlayerFunctions.isInPlot(oPlayer) || !BukkitPlayerFunctions.getCurrentPlot(oPlayer).equals(plot)) {
continue;
}
final UUID uuid = UUIDHandler.getUUID(BukkitUtil.getPlayer(oPlayer));
final UUID uuid = UUIDHandler.getUUID(BukkitUtil.getPlayer(oPlayer));
if (plot.isAdded(uuid)) {
return oPlayer;
}
}
return null;
}
public Vector calculateVelocity(final Player p, final Player e)
}
public Vector calculateVelocity(final Player p, final Player e) {
final org.bukkit.Location playerLocation = p.getLocation();
final org.bukkit.Location oPlayerLocation = e.getLocation();
final double playerX = playerLocation.getX(), playerY = playerLocation.getY(), playerZ = playerLocation.getZ(), oPlayerX = oPlayerLocation.getX(), oPlayerY = oPlayerLocation.getY(), oPlayerZ = oPlayerLocation
.getZ();
double x = 0d, y = 0d, z = 0d;
if (playerX < oPlayerX)
double x = 0d, y = 0d, z = 0d;
if (playerX < oPlayerX) {
x = 1.0d;
}
else if (playerX > oPlayerX)
x = 1.0d;
} else if (playerX > oPlayerX) {
x = -1.0d;
}
if (playerY < oPlayerY)
}
if (playerY < oPlayerY) {
y = 0.5d;
}
else if (playerY > oPlayerY)
y = 0.5d;
} else if (playerY > oPlayerY) {
y = -0.5d;
}
if (playerZ < oPlayerZ)
}
if (playerZ < oPlayerZ) {
z = 1.0d;
}
else if (playerZ > oPlayerZ)
z = 1.0d;
} else if (playerZ > oPlayerZ) {
z = -1.0d;
}
return new Vector(x, y, z);
}
}
@EventHandler
public void onPlotEntry(final PlayerEnterPlotEvent event)
@EventHandler
public void onPlotEntry(final PlayerEnterPlotEvent event) {
final Player player = event.getPlayer();
final PlotPlayer pp = BukkitUtil.getPlayer(player);
pp.getLocation();
final Plot plot = event.getPlot();
if (plot == null) { return; }
if ((FlagManager.getPlotFlag(plot, "forcefield") != null) && FlagManager.getPlotFlag(plot, "forcefield").getValue().equals("true"))
{
if (!FlagManager.isBooleanFlag(plot, "forcefield", false))
final Plot plot = event.getPlot();
if (plot == null) {
return;
}
if ((FlagManager.getPlotFlag(plot, "forcefield") != null) && FlagManager.getPlotFlag(plot, "forcefield").getValue().equals("true")) {
if (!FlagManager.isBooleanFlag(plot, "forcefield", false)) {
final UUID uuid = pp.getUUID();
if (plot.isAdded(uuid))
final UUID uuid = pp.getUUID();
if (plot.isAdded(uuid)) {
final Set<Player> players = getNearbyPlayers(player, plot);
for (final Player oPlayer : players)
final Set<Player> players = getNearbyPlayers(player, plot);
for (final Player oPlayer : players) {
oPlayer.setVelocity(calculateVelocity(player, oPlayer));
}
}
else
}
} else {
final Player oPlayer = hasNearbyPermitted(player, plot);
final Player oPlayer = hasNearbyPermitted(player, plot);
if (oPlayer == null) {
return;
}
player.setVelocity(calculateVelocity(oPlayer, player));
}

View File

@ -1,17 +1,16 @@
package com.plotsquared.bukkit.listeners;
public enum PlayerBlockEventType
{
public enum PlayerBlockEventType {
// Non interactive
EAT,
READ,
// Right click with monster egg
SPAWN_MOB,
// Dragon egg
TELEPORT_OBJECT,
// armor stands
PLACE_MISC,
// blocks
@ -20,7 +19,7 @@ public enum PlayerBlockEventType
PLACE_HANGING,
// vehicles
PLACE_VEHICLE,
// armor stands
BREAK_MISC,
// blocks
@ -28,7 +27,7 @@ public enum PlayerBlockEventType
// paintings / item frames
BREAK_HANGING,
BREAK_VEHICLE,
// armor stands
INTERACT_MISC,
// blocks
@ -37,7 +36,7 @@ public enum PlayerBlockEventType
INTERACT_VEHICLE,
// item frame / painting
INTERACT_HANGING,
// Pressure plate, tripwire etc
TRIGGER_PHYSICAL,
}

View File

@ -30,87 +30,83 @@ import com.intellectualcrafters.plot.util.Permissions;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.listener.PlotListener;
public class PlayerEvents_1_8 extends PlotListener implements Listener
{
public class PlayerEvents_1_8 extends PlotListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onInventoryClick(final InventoryClickEvent event)
{
if (!event.isLeftClick() || (event.getAction() != InventoryAction.PLACE_ALL) || event.isShiftClick()) { return; }
public void onInventoryClick(final InventoryClickEvent event) {
if (!event.isLeftClick() || (event.getAction() != InventoryAction.PLACE_ALL) || event.isShiftClick()) {
return;
}
final HumanEntity entity = event.getWhoClicked();
if (!(entity instanceof Player) || !PS.get().isPlotWorld(entity.getWorld().getName())) { return; }
if (!(entity instanceof Player) || !PS.get().isPlotWorld(entity.getWorld().getName())) {
return;
}
final Player player = (Player) entity;
final PlayerInventory inv = player.getInventory();
final int slot = inv.getHeldItemSlot();
if ((slot != event.getSlot()) || (slot > 8) || !event.getEventName().equals("InventoryCreativeEvent")) { return; }
if ((slot != event.getSlot()) || (slot > 8) || !event.getEventName().equals("InventoryCreativeEvent")) {
return;
}
final ItemStack current = inv.getItemInHand();
final ItemStack newItem = event.getCursor();
final ItemMeta newMeta = newItem.getItemMeta();
final ItemMeta oldMeta = newItem.getItemMeta();
String newLore = "";
if (newMeta != null)
{
if (newMeta != null) {
final List<String> lore = newMeta.getLore();
if (lore != null)
{
if (lore != null) {
newLore = lore.toString();
}
}
String oldLore = "";
if (oldMeta != null)
{
if (oldMeta != null) {
final List<String> lore = oldMeta.getLore();
if (lore != null)
{
if (lore != null) {
oldLore = lore.toString();
}
}
if (!newLore.equals("[(+NBT)]") || (current.equals(newItem) && newLore.equals(oldLore))) { return; }
if (!newLore.equals("[(+NBT)]") || (current.equals(newItem) && newLore.equals(oldLore))) {
return;
}
final HashSet<Byte> blocks = null;
final Block block = player.getTargetBlock(blocks, 7);
final BlockState state = block.getState();
if (state == null) { return; }
if (state.getType() != newItem.getType()) { return; }
if (state == null) {
return;
}
if (state.getType() != newItem.getType()) {
return;
}
final Location l = BukkitUtil.getLocation(state.getLocation());
final Plot plot = MainUtil.getPlot(l);
final PlotPlayer pp = BukkitUtil.getPlayer(player);
boolean cancelled = false;
if (plot == null)
{
if (!MainUtil.isPlotArea(l)) { return; }
if (!Permissions.hasPermission(pp, "plots.admin.interact.road"))
{
if (plot == null) {
if (!MainUtil.isPlotArea(l)) {
return;
}
if (!Permissions.hasPermission(pp, "plots.admin.interact.road")) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.road");
cancelled = true;
}
}
else
{
if (!plot.hasOwner())
{
if (!Permissions.hasPermission(pp, "plots.admin.interact.unowned"))
{
} else {
if (!plot.hasOwner()) {
if (!Permissions.hasPermission(pp, "plots.admin.interact.unowned")) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.unowned");
cancelled = true;
}
}
else
{
} else {
final UUID uuid = pp.getUUID();
if (!plot.isAdded(uuid))
{
if (!Permissions.hasPermission(pp, "plots.admin.interact.other"))
{
if (!plot.isAdded(uuid)) {
if (!Permissions.hasPermission(pp, "plots.admin.interact.other")) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.other");
cancelled = true;
}
}
}
}
if (cancelled)
{
if ((current.getTypeId() == newItem.getTypeId()) && (current.getDurability() == newItem.getDurability()))
{
if (cancelled) {
if ((current.getTypeId() == newItem.getTypeId()) && (current.getDurability() == newItem.getDurability())) {
event.setCursor(new ItemStack(newItem.getTypeId(), newItem.getAmount(), newItem.getDurability()));
event.setCancelled(true);
return;
@ -118,43 +114,38 @@ public class PlayerEvents_1_8 extends PlotListener implements Listener
event.setCursor(new ItemStack(newItem.getTypeId(), newItem.getAmount(), newItem.getDurability()));
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onInteract(final PlayerInteractAtEntityEvent e)
{
public void onInteract(final PlayerInteractAtEntityEvent e) {
final Entity entity = e.getRightClicked();
if (!(entity instanceof ArmorStand)) { return; }
if (!(entity instanceof ArmorStand)) {
return;
}
final Location l = BukkitUtil.getLocation(e.getRightClicked().getLocation());
final String world = l.getWorld();
if (!PS.get().isPlotWorld(world)) { return; }
if (!PS.get().isPlotWorld(world)) {
return;
}
final Plot plot = MainUtil.getPlot(l);
final PlotPlayer pp = BukkitUtil.getPlayer(e.getPlayer());
if (plot == null)
{
if (!MainUtil.isPlotArea(l)) { return; }
if (!Permissions.hasPermission(pp, "plots.admin.interact.road"))
{
if (plot == null) {
if (!MainUtil.isPlotArea(l)) {
return;
}
if (!Permissions.hasPermission(pp, "plots.admin.interact.road")) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.road");
e.setCancelled(true);
}
}
else
{
if (!plot.hasOwner())
{
if (!Permissions.hasPermission(pp, "plots.admin.interact.unowned"))
{
} else {
if (!plot.hasOwner()) {
if (!Permissions.hasPermission(pp, "plots.admin.interact.unowned")) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.unowned");
e.setCancelled(true);
}
}
else
{
} else {
final UUID uuid = pp.getUUID();
if (!plot.isAdded(uuid))
{
if (!Permissions.hasPermission(pp, "plots.admin.interact.other"))
{
if (!plot.isAdded(uuid)) {
if (!Permissions.hasPermission(pp, "plots.admin.interact.other")) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.other");
e.setCancelled(true);
}

View File

@ -15,44 +15,35 @@ import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.util.MainUtil;
import com.plotsquared.bukkit.util.BukkitUtil;
public class PlayerEvents_1_8_3 implements Listener
{
public class PlayerEvents_1_8_3 implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBigBoom(final BlockExplodeEvent event)
{
public void onBigBoom(final BlockExplodeEvent event) {
final Block block = event.getBlock();
final Location loc = BukkitUtil.getLocation(block.getLocation());
final String world = loc.getWorld();
if (!PS.get().isPlotWorld(world)) { return; }
if (!PS.get().isPlotWorld(world)) {
return;
}
final Plot plot = MainUtil.getPlot(loc);
if ((plot != null) && plot.hasOwner())
{
if (FlagManager.isPlotFlagTrue(plot, "explosion"))
{
if ((plot != null) && plot.hasOwner()) {
if (FlagManager.isPlotFlagTrue(plot, "explosion")) {
final Iterator<Block> iter = event.blockList().iterator();
while (iter.hasNext())
{
while (iter.hasNext()) {
final Block b = iter.next();
if (!plot.equals(MainUtil.getPlot(BukkitUtil.getLocation(b.getLocation()))))
{
if (!plot.equals(MainUtil.getPlot(BukkitUtil.getLocation(b.getLocation())))) {
iter.remove();
}
}
return;
}
}
if (MainUtil.isPlotArea(loc))
{
if (MainUtil.isPlotArea(loc)) {
event.setCancelled(true);
}
else
{
} else {
final Iterator<Block> iter = event.blockList().iterator();
while (iter.hasNext())
{
while (iter.hasNext()) {
iter.next();
if (MainUtil.isPlotArea(loc))
{
if (MainUtil.isPlotArea(loc)) {
iter.remove();
}
}

View File

@ -57,56 +57,44 @@ import com.plotsquared.listener.PlotListener;
*
*/
@SuppressWarnings({ "deprecation" })
public class PlotPlusListener extends PlotListener implements Listener
@SuppressWarnings({ "deprecation" })
public class PlotPlusListener extends PlotListener implements Listener {
private final static HashMap<String, Interval> feedRunnable = new HashMap<>();
private final static HashMap<String, Interval> healRunnable = new HashMap<>();
public static void startRunnable(final JavaPlugin plugin)
{
plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable()
private final static HashMap<String, Interval> healRunnable = new HashMap<>();
public static void startRunnable(final JavaPlugin plugin) {
plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
@Override
public void run()
{
for (final Iterator<Entry<String, Interval>> iter = healRunnable.entrySet().iterator(); iter.hasNext();)
@Override
public void run() {
for (final Iterator<Entry<String, Interval>> iter = healRunnable.entrySet().iterator(); iter.hasNext();) {
final Entry<String, Interval> entry = iter.next();
final Interval value = entry.getValue();
++value.count;
if (value.count == value.interval)
++value.count;
if (value.count == value.interval) {
value.count = 0;
final Player player = Bukkit.getPlayer(entry.getKey());
if (player == null)
final Player player = Bukkit.getPlayer(entry.getKey());
if (player == null) {
iter.remove();
continue;
}
final double level = player.getHealth();
if (level != value.max)
final double level = player.getHealth();
if (level != value.max) {
player.setHealth(Math.min(level + value.amount, value.max));
}
}
}
for (final Iterator<Entry<String, Interval>> iter = feedRunnable.entrySet().iterator(); iter.hasNext();)
}
for (final Iterator<Entry<String, Interval>> iter = feedRunnable.entrySet().iterator(); iter.hasNext();) {
final Entry<String, Interval> entry = iter.next();
final Interval value = entry.getValue();
++value.count;
if (value.count == value.interval)
++value.count;
if (value.count == value.interval) {
value.count = 0;
final Player player = Bukkit.getPlayer(entry.getKey());
if (player == null)
final Player player = Bukkit.getPlayer(entry.getKey());
if (player == null) {
iter.remove();
continue;
}
final int level = player.getFoodLevel();
if (level != value.max)
final int level = player.getFoodLevel();
if (level != value.max) {
player.setFoodLevel(Math.min(level + value.amount, value.max));
}
@ -114,153 +102,145 @@ public class PlotPlusListener extends PlotListener implements Listener
}
}
}, 0l, 20l);
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onInteract(final BlockDamageEvent event)
@EventHandler(priority = EventPriority.HIGH)
public void onInteract(final BlockDamageEvent event) {
final Player player = event.getPlayer();
final Player player = event.getPlayer();
if (player.getGameMode() != GameMode.SURVIVAL) {
return;
}
final Plot plot = MainUtil.getPlot(BukkitUtil.getLocation(player));
if (plot == null) { return; }
if (FlagManager.isBooleanFlag(plot, "instabreak", false))
final Plot plot = MainUtil.getPlot(BukkitUtil.getLocation(player));
if (plot == null) {
return;
}
if (FlagManager.isBooleanFlag(plot, "instabreak", false)) {
event.getBlock().breakNaturally();
}
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onDamage(final EntityDamageEvent event)
{
@EventHandler(priority = EventPriority.HIGH)
public void onDamage(final EntityDamageEvent event) {
if (event.getEntityType() != EntityType.PLAYER) {
return;
}
final Player player = (Player) event.getEntity();
final Plot plot = MainUtil.getPlot(BukkitUtil.getLocation(player));
if (plot == null) { return; }
if (FlagManager.isBooleanFlag(plot, "invincible", false))
final Plot plot = MainUtil.getPlot(BukkitUtil.getLocation(player));
if (plot == null) {
return;
}
if (FlagManager.isBooleanFlag(plot, "invincible", false)) {
event.setCancelled(true);
}
}
}
@EventHandler
public void onItemPickup(final PlayerPickupItemEvent event)
@EventHandler
public void onItemPickup(final PlayerPickupItemEvent event) {
final Player player = event.getPlayer();
final PlotPlayer pp = BukkitUtil.getPlayer(player);
final Plot plot = MainUtil.getPlot(pp.getLocation());
final Plot plot = MainUtil.getPlot(pp.getLocation());
if (plot == null) {
return;
}
final UUID uuid = pp.getUUID();
if (plot.isAdded(uuid) && FlagManager.isBooleanFlag(plot, "drop-protection", false))
final UUID uuid = pp.getUUID();
if (plot.isAdded(uuid) && FlagManager.isBooleanFlag(plot, "drop-protection", false)) {
event.setCancelled(true);
}
}
}
@EventHandler
public void onItemDrop(final PlayerDropItemEvent event)
@EventHandler
public void onItemDrop(final PlayerDropItemEvent event) {
final Player player = event.getPlayer();
final PlotPlayer pp = BukkitUtil.getPlayer(player);
final Plot plot = MainUtil.getPlot(pp.getLocation());
final Plot plot = MainUtil.getPlot(pp.getLocation());
if (plot == null) {
return;
}
final UUID uuid = pp.getUUID();
if (plot.isAdded(uuid) && FlagManager.isBooleanFlag(plot, "item-drop", false))
final UUID uuid = pp.getUUID();
if (plot.isAdded(uuid) && FlagManager.isBooleanFlag(plot, "item-drop", false)) {
event.setCancelled(true);
}
}
}
@EventHandler
public void onPlotEnter(final PlayerEnterPlotEvent event)
@EventHandler
public void onPlotEnter(final PlayerEnterPlotEvent event) {
final Player player = event.getPlayer();
final Plot plot = event.getPlot();
final Flag feed = FlagManager.getPlotFlag(plot, "feed");
if (feed != null)
final Flag feed = FlagManager.getPlotFlag(plot, "feed");
if (feed != null) {
final Integer[] value = (Integer[]) feed.getValue();
feedRunnable.put(player.getName(), new Interval(value[0], value[1], 20));
}
final Flag heal = FlagManager.getPlotFlag(plot, "heal");
if (heal != null)
final Flag heal = FlagManager.getPlotFlag(plot, "heal");
if (heal != null) {
final Integer[] value = (Integer[]) heal.getValue();
healRunnable.put(player.getName(), new Interval(value[0], value[1], 20));
}
}
}
@EventHandler
public void onPlayerQuit(final PlayerQuitEvent event)
@EventHandler
public void onPlayerQuit(final PlayerQuitEvent event) {
final Player player = event.getPlayer();
final String name = player.getName();
feedRunnable.remove(name);
healRunnable.remove(name);
}
}
@EventHandler
public void onPlotLeave(final PlayerLeavePlotEvent event)
@EventHandler
public void onPlotLeave(final PlayerLeavePlotEvent event) {
final Player leaver = event.getPlayer();
final Plot plot = event.getPlot();
final Plot plot = event.getPlot();
if (!plot.hasOwner()) {
return;
}
BukkitUtil.getPlayer(leaver);
final String name = leaver.getName();
feedRunnable.remove(name);
healRunnable.remove(name);
}
public static class Interval
}
public static class Interval {
public final int interval;
public final int amount;
public final int max;
public int count = 0;
public Interval(final int interval, final int amount, final int max)
public int count = 0;
public Interval(final int interval, final int amount, final int max) {
this.interval = interval;
this.amount = amount;
this.max = max;
}
}
}
/**
* Record Meta Class
*
*/
*/
{
public final static List<RecordMeta> metaList = new ArrayList<>();
static
{
public static class RecordMeta {
public final static List<RecordMeta> metaList = new ArrayList<>();
static {
for (int x = 3; x < 12; x++) {
metaList.add(new RecordMeta(x + "", Material.valueOf("RECORD_" + x)));
}
}
private final String name;
private final Material material;
private final String name;
private final Material material;
public RecordMeta(final String name, final Material material) {
this.name = name;
this.material = material;
this.material = material;
}
@Override
@Override
public String toString() {
return name;
return name;
}
@Override
@Override
public int hashCode() {
return name.hashCode();
}
return name.hashCode();
}
public Material getMaterial() {
return material;

View File

@ -19,108 +19,98 @@ import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.util.MainUtil;
import com.plotsquared.bukkit.util.BukkitUtil;
public class TNTListener implements Listener
{
public class TNTListener implements Listener {
private double lastRadius;
@EventHandler
public void onPrime(final ExplosionPrimeEvent event)
{
public void onPrime(final ExplosionPrimeEvent event) {
lastRadius = event.getRadius() + 1;
}
@EventHandler
public void onExplode(final EntityExplodeEvent event)
{
public void onExplode(final EntityExplodeEvent event) {
final Entity entity = event.getEntity();
if (entity == null) { return; }
if (entity == null) {
return;
}
final World world = entity.getWorld();
final String worldname = world.getName();
if (!PS.get().isPlotWorld(worldname)) { return; }
if (!PS.get().isPlotWorld(worldname)) {
return;
}
final Plot plot = MainUtil.getPlot(BukkitUtil.getLocation(entity));
if (plot == null) { return; }
if (!FlagManager.isPlotFlagTrue(plot, "explosion")) { return; }
if (plot == null) {
return;
}
if (!FlagManager.isPlotFlagTrue(plot, "explosion")) {
return;
}
final Location bot = MainUtil.getPlotBottomLoc(plot.world, plot.id);
final Location top = MainUtil.getPlotTopLoc(plot.world, plot.id);
final List<Entity> nearby = entity.getNearbyEntities(lastRadius, lastRadius, lastRadius);
for (final Entity near : nearby)
{
if ((near instanceof TNTPrimed) || (near.getType() == EntityType.MINECART_TNT))
{
for (final Entity near : nearby) {
if ((near instanceof TNTPrimed) || (near.getType() == EntityType.MINECART_TNT)) {
final Vector velocity = near.getVelocity();
final Location loc = BukkitUtil.getLocation(near);
final Plot nearPlot = MainUtil.getPlot(loc);
if (!plot.equals(nearPlot))
{
if (!plot.equals(nearPlot)) {
near.setVelocity(new Vector(0, 0, 0));
continue;
}
final double vx = velocity.getX();
velocity.getX();
final double vz = velocity.getX();
int dx;
int dz;
if (vx > 0)
{
if (vx > 0) {
dx = top.getX() - loc.getX();
}
else
{
} else {
dx = bot.getX() - loc.getX();
}
if (vz > 0)
{
if (vz > 0) {
dz = top.getZ() - loc.getZ();
}
else
{
} else {
dz = bot.getZ() - loc.getZ();
}
final double s1 = dx / vx;
final double s2 = dz / vz;
final Vector v1 = new Vector(dx, 0, vz * s1);
final Vector v2 = new Vector(vx * s2, 0, dz);
Vector shortest;
if (v1.length() < v2.length())
{
if (v1.length() < v2.length()) {
shortest = v1;
}
else
{
} else {
shortest = v2;
}
final Location landing = loc.add(shortest.getBlockX() + 1, 0, shortest.getBlockZ() + 1);
final int ty = MainUtil.getHeighestBlock(worldname, landing.getX(), landing.getZ());
final int diff = ty - loc.getY();
final double calcDiff = getY(velocity, Math.sqrt((shortest.getBlockX() * shortest.getBlockX()) + (shortest.getBlockZ() * shortest.getBlockZ())));
if (calcDiff > diff)
{
if (calcDiff > diff) {
near.setVelocity(new Vector(0, 0, 0));
}
}
}
event.getEntity().setVelocity(new Vector(0, 0, 0));
}
public double getY(final Vector velocity, final double x)
{
public double getY(final Vector velocity, final double x) {
final double g = 16;
final double l1 = velocity.length();
final double l2 = Math.sqrt((velocity.getX() * velocity.getX()) + (velocity.getZ() * velocity.getZ()));
final double v = l1 * 20;
double theta = Math.acos(l2 / l1);
if (velocity.getY() < 0)
{
if (velocity.getY() < 0) {
theta = -theta;
}
final double cos = Math.cos(theta);

View File

@ -11,37 +11,27 @@ import com.intellectualcrafters.plot.PS;
import com.plotsquared.bukkit.generator.BukkitGeneratorWrapper;
import com.plotsquared.bukkit.generator.BukkitPlotGenerator;
public class WorldEvents implements Listener
{
public class WorldEvents implements Listener {
public static String lastWorld = null;
public static String getName(final World world)
{
if ((lastWorld != null) && !lastWorld.equals("CheckingPlotSquaredGenerator"))
{
public static String getName(final World world) {
if ((lastWorld != null) && !lastWorld.equals("CheckingPlotSquaredGenerator")) {
return lastWorld;
}
else
{
} else {
return world.getName();
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public static void onWorldInit(final WorldInitEvent event)
{
public static void onWorldInit(final WorldInitEvent event) {
final World world = event.getWorld();
final String name = getName(world);
final ChunkGenerator gen = world.getGenerator();
if (gen instanceof BukkitPlotGenerator)
{
if (gen instanceof BukkitPlotGenerator) {
PS.get().loadWorld(name, new BukkitGeneratorWrapper(name, gen));
}
else
{
if (PS.get().config.contains("worlds." + name))
{
} else {
if (PS.get().config.contains("worlds." + name)) {
PS.get().loadWorld(name, new BukkitGeneratorWrapper(name, null));
}
}

View File

@ -29,9 +29,8 @@ import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.bukkit.selections.Selection;
public class WEListener implements Listener
{
public class WEListener implements Listener {
public final HashSet<String> rad1 = new HashSet<>(Arrays.asList("forestgen", "pumpkins", "drain", "fixwater", "fixlava", "replacenear", "snow", "thaw", "ex", "butcher", "size"));
public final HashSet<String> rad2 = new HashSet<>(Arrays.asList("fill", "fillr", "removenear", "remove"));
public final HashSet<String> rad2_1 = new HashSet<>(Arrays.asList("hcyl", "cyl"));
@ -39,7 +38,7 @@ public class WEListener implements Listener
public final HashSet<String> rad2_3 = new HashSet<>(Arrays.asList("brush smooth"));
public final HashSet<String> rad3_1 = new HashSet<>(Arrays.asList("brush gravity"));
public final HashSet<String> rad3_2 = new HashSet<>(Arrays.asList("brush sphere", "brush cylinder"));
public final HashSet<String> region = new HashSet<>(Arrays.asList("move", "set", "replace", "overlay", "walls", "outline", "deform", "hollow", "smooth", "naturalize", "paste", "count", "distr",
"regen", "copy", "cut", "green", "setbiome"));
public final HashSet<String> regionExtend = new HashSet<>(Arrays.asList("stack"));
@ -47,100 +46,89 @@ public class WEListener implements Listener
public final HashSet<String> unsafe1 = new HashSet<>(Arrays.asList("cs", ".s", "restore", "snapshot", "delchunks", "listchunks"));
public final HashSet<String> restricted = new HashSet<>(Arrays.asList("up"));
public final HashSet<String> other = new HashSet<>(Arrays.asList("undo", "redo"));
public boolean checkCommand(final List<String> list, final String cmd)
{
for (final String identifier : list)
{
if (("/" + identifier).equals(cmd) || ("//" + identifier).equals(cmd) || ("/worldedit:/" + identifier).equals(cmd) || ("/worldedit:" + identifier).equals(cmd)) { return true; }
public boolean checkCommand(final List<String> list, final String cmd) {
for (final String identifier : list) {
if (("/" + identifier).equals(cmd) || ("//" + identifier).equals(cmd) || ("/worldedit:/" + identifier).equals(cmd) || ("/worldedit:" + identifier).equals(cmd)) {
return true;
}
}
return false;
}
public String reduceCmd(final String cmd, final boolean single)
{
if (cmd.startsWith("/worldedit:/")) { return cmd.substring(12); }
if (cmd.startsWith("/worldedit:")) { return cmd.substring(11); }
if (cmd.startsWith("//")) { return cmd.substring(2); }
if (single && cmd.startsWith("/")) { return cmd.substring(1); }
public String reduceCmd(final String cmd, final boolean single) {
if (cmd.startsWith("/worldedit:/")) {
return cmd.substring(12);
}
if (cmd.startsWith("/worldedit:")) {
return cmd.substring(11);
}
if (cmd.startsWith("//")) {
return cmd.substring(2);
}
if (single && cmd.startsWith("/")) {
return cmd.substring(1);
}
return cmd;
}
public int getInt(final String s)
{
try
{
public int getInt(final String s) {
try {
int max = 0;
final String[] split = s.split(",");
for (final String rad : split)
{
for (final String rad : split) {
final int val = Integer.parseInt(rad);
if (val > max)
{
if (val > max) {
max = val;
}
}
return max;
}
catch (final NumberFormatException e)
{
} catch (final NumberFormatException e) {
return 0;
}
}
public boolean checkVolume(final PlotPlayer player, final long volume, final long max, final Cancellable e)
{
if (volume > max)
{
public boolean checkVolume(final PlotPlayer player, final long volume, final long max, final Cancellable e) {
if (volume > max) {
MainUtil.sendMessage(player, C.WORLDEDIT_VOLUME.s().replaceAll("%current%", volume + "").replaceAll("%max%", max + ""));
e.setCancelled(true);
}
if (Permissions.hasPermission(player, "plots.worldedit.bypass"))
{
if (Permissions.hasPermission(player, "plots.worldedit.bypass")) {
MainUtil.sendMessage(player, C.WORLDEDIT_BYPASS);
}
return true;
}
public boolean checkSelection(final Player p, final PlotPlayer pp, final int modifier, final long max, final Cancellable e)
{
public boolean checkSelection(final Player p, final PlotPlayer pp, final int modifier, final long max, final Cancellable e) {
final Selection selection = BukkitMain.worldEdit.getSelection(p);
if (selection == null) { return true; }
if (selection == null) {
return true;
}
final BlockVector pos1 = selection.getNativeMinimumPoint().toBlockVector();
final BlockVector pos2 = selection.getNativeMaximumPoint().toBlockVector();
final HashSet<RegionWrapper> mask = WEManager.getMask(pp);
final RegionWrapper region = new RegionWrapper(pos1.getBlockX(), pos2.getBlockX(), pos1.getBlockZ(), pos2.getBlockZ());
if (Settings.REQUIRE_SELECTION)
{
if (Settings.REQUIRE_SELECTION) {
String arg = null;
if (!WEManager.regionContains(region, mask))
{
if (!WEManager.regionContains(region, mask)) {
arg = "pos1 + pos2";
}
else if (!WEManager.maskContains(mask, pos1.getBlockX(), pos1.getBlockY(), pos1.getBlockZ()))
{
} else if (!WEManager.maskContains(mask, pos1.getBlockX(), pos1.getBlockY(), pos1.getBlockZ())) {
arg = "pos1";
}
else if (!WEManager.maskContains(mask, pos2.getBlockX(), pos2.getBlockY(), pos2.getBlockZ()))
{
} else if (!WEManager.maskContains(mask, pos2.getBlockX(), pos2.getBlockY(), pos2.getBlockZ())) {
arg = "pos2";
}
if (arg != null)
{
if (arg != null) {
e.setCancelled(true);
MainUtil.sendMessage(pp, C.REQUIRE_SELECTION_IN_MASK, arg);
if (Permissions.hasPermission(pp, "plots.worldedit.bypass"))
{
if (Permissions.hasPermission(pp, "plots.worldedit.bypass")) {
MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASS);
}
return true;
}
if (!WEManager.regionContains(region, mask))
{
if (!WEManager.regionContains(region, mask)) {
MainUtil.sendMessage(pp, C.REQUIRE_SELECTION_IN_MASK, "pos1 + pos2");
e.setCancelled(true);
if (Permissions.hasPermission(pp, "plots.worldedit.bypass"))
{
if (Permissions.hasPermission(pp, "plots.worldedit.bypass")) {
MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASS);
}
return true;
@ -149,138 +137,114 @@ public class WEListener implements Listener
final long volume = Math.abs((pos1.getBlockX() - pos2.getBlockX()) * (pos1.getBlockY() - pos2.getBlockY()) * (pos1.getBlockZ() - pos2.getBlockZ())) * modifier;
return checkVolume(pp, volume, max, e);
}
private final boolean set = false;
public boolean delay(final Player player, final String command, final boolean delayed)
{
if (!Settings.QUEUE_COMMANDS || !Settings.EXPERIMENTAL_FAST_ASYNC_WORLDEDIT || set) { return false; }
public boolean delay(final Player player, final String command, final boolean delayed) {
if (!Settings.QUEUE_COMMANDS || !Settings.EXPERIMENTAL_FAST_ASYNC_WORLDEDIT || set) {
return false;
}
final boolean free = SetBlockQueue.addNotify(null);
if (free)
{
if (delayed)
{
if (free) {
if (delayed) {
MainUtil.sendMessage(BukkitUtil.getPlayer(player), C.WORLDEDIT_RUN, command);
Bukkit.getServer().dispatchCommand(player, command.substring(1));
}
else
{
} else {
return false;
}
}
else
{
if (!delayed)
{
} else {
if (!delayed) {
MainUtil.sendMessage(BukkitUtil.getPlayer(player), C.WORLDEDIT_DELAYED);
}
SetBlockQueue.addNotify(new Runnable()
{
SetBlockQueue.addNotify(new Runnable() {
@Override
public void run()
{
public void run() {
delay(player, command, true);
}
});
}
return true;
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public boolean onPlayerCommand(final PlayerCommandPreprocessEvent e)
{
public boolean onPlayerCommand(final PlayerCommandPreprocessEvent e) {
final WorldEditPlugin worldedit = BukkitMain.worldEdit;
if (worldedit == null)
{
if (worldedit == null) {
HandlerList.unregisterAll(this);
return true;
}
final Player p = e.getPlayer();
final PlotPlayer pp = BukkitUtil.getPlayer(p);
if (!PS.get().isPlotWorld(p.getWorld().getName())) { return true; }
if (!PS.get().isPlotWorld(p.getWorld().getName())) {
return true;
}
final String message = e.getMessage();
final String cmd = message.toLowerCase();
final boolean single = true;
final String[] split = cmd.split(" ");
final long maxVolume = Settings.WE_MAX_VOLUME;
final long maxIterations = Settings.WE_MAX_ITERATIONS;
if (pp.getAttribute("worldedit")) { return true; }
if (split.length >= 2)
{
if (pp.getAttribute("worldedit")) {
return true;
}
if (split.length >= 2) {
final String reduced = reduceCmd(split[0], single);
final String reduced2 = reduceCmd(split[0] + " " + split[1], single);
if (rad1.contains(reduced))
{
if (delay(p, message, false))
{
if (rad1.contains(reduced)) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
final long volume = getInt(split[1]) * 256;
return checkVolume(pp, volume, maxVolume, e);
}
if (rad2.contains(reduced))
{
if (delay(p, message, false))
{
if (rad2.contains(reduced)) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
if (split.length >= 3)
{
if (split.length >= 3) {
final long volume = getInt(split[2]) * 256;
return checkVolume(pp, volume, maxVolume, e);
}
return true;
}
if (rad2_1.contains(reduced))
{
if (delay(p, message, false))
{
if (rad2_1.contains(reduced)) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
if (split.length >= 4)
{
if (split.length >= 4) {
final long volume = getInt(split[2]) * getInt(split[3]);
return checkVolume(pp, volume, maxVolume, e);
}
return true;
}
if (rad2_2.contains(reduced))
{
if (delay(p, message, false))
{
if (rad2_2.contains(reduced)) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
if (split.length >= 3)
{
if (split.length >= 3) {
final long radius = getInt(split[2]);
final long volume = radius * radius;
return checkVolume(pp, volume, maxVolume, e);
}
return true;
}
if (rad2_3.contains(reduced2))
{
if (delay(p, message, false))
{
if (rad2_3.contains(reduced2)) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
if (split.length >= 3)
{
if (split.length == 4)
{
if (split.length >= 3) {
if (split.length == 4) {
final int iterations = getInt(split[3]);
if (iterations > maxIterations)
{
if (iterations > maxIterations) {
MainUtil.sendMessage(pp, C.WORLDEDIT_ITERATIONS.s().replaceAll("%current%", iterations + "").replaceAll("%max%", maxIterations + ""));
e.setCancelled(true);
if (Permissions.hasPermission(pp, "plots.worldedit.bypass"))
{
if (Permissions.hasPermission(pp, "plots.worldedit.bypass")) {
MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASS);
}
return true;
@ -292,18 +256,14 @@ public class WEListener implements Listener
}
return true;
}
if (rad3_1.contains(reduced2))
{
if (delay(p, message, false))
{
if (rad3_1.contains(reduced2)) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
if (split.length >= 3)
{
if (split.length >= 3) {
int i = 2;
if (split[i].equalsIgnoreCase("-h"))
{
if (split[i].equalsIgnoreCase("-h")) {
i = 3;
}
final long radius = getInt(split[i]);
@ -312,18 +272,14 @@ public class WEListener implements Listener
}
return true;
}
if (rad3_2.contains(reduced2))
{
if (delay(p, message, false))
{
if (rad3_2.contains(reduced2)) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
if (split.length >= 4)
{
if (split.length >= 4) {
int i = 3;
if (split[i].equalsIgnoreCase("-h"))
{
if (split[i].equalsIgnoreCase("-h")) {
i = 4;
}
final long radius = getInt(split[i]);
@ -332,10 +288,8 @@ public class WEListener implements Listener
}
return true;
}
if (regionExtend.contains(reduced))
{
if (delay(p, message, false))
{
if (regionExtend.contains(reduced)) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
@ -343,22 +297,17 @@ public class WEListener implements Listener
}
}
final String reduced = reduceCmd(split[0], single);
if (Settings.WE_BLACKLIST.contains(reduced))
{
if (Settings.WE_BLACKLIST.contains(reduced)) {
MainUtil.sendMessage(pp, C.WORLDEDIT_UNSAFE);
e.setCancelled(true);
if (Permissions.hasPermission(pp, "plots.worldedit.bypass"))
{
if (Permissions.hasPermission(pp, "plots.worldedit.bypass")) {
MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASS);
}
}
if (restricted.contains(reduced))
{
if (restricted.contains(reduced)) {
final Plot plot = MainUtil.getPlot(pp.getLocation());
if ((plot != null) && plot.isAdded(pp.getUUID()))
{
if (delay(p, message, false))
{
if ((plot != null) && plot.isAdded(pp.getUUID())) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
@ -366,25 +315,20 @@ public class WEListener implements Listener
}
e.setCancelled(true);
MainUtil.sendMessage(pp, C.NO_PLOT_PERMS);
if (Permissions.hasPermission(pp, "plots.worldedit.bypass"))
{
if (Permissions.hasPermission(pp, "plots.worldedit.bypass")) {
MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASS);
}
return true;
}
if (region.contains(reduced))
{
if (delay(p, message, false))
{
if (region.contains(reduced)) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
return checkSelection(p, pp, 1, maxVolume, e);
}
if (other.contains(reduced))
{
if (delay(p, message, false))
{
if (other.contains(reduced)) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}

View File

@ -5,41 +5,36 @@ import org.bukkit.block.Block;
import com.intellectualcrafters.plot.object.LazyBlock;
import com.intellectualcrafters.plot.object.PlotBlock;
public class BukkitLazyBlock extends LazyBlock
{
public class BukkitLazyBlock extends LazyBlock {
private int id = -1;
private Block block;
private PlotBlock pb;
public BukkitLazyBlock(final int id, final Block block)
{
public BukkitLazyBlock(final int id, final Block block) {
this.id = id;
this.block = block;
}
public BukkitLazyBlock(final PlotBlock pb)
{
public BukkitLazyBlock(final PlotBlock pb) {
id = pb.id;
this.pb = pb;
}
public BukkitLazyBlock(final Block block)
{
public BukkitLazyBlock(final Block block) {
this.block = block;
}
@Override
public PlotBlock getPlotBlock()
{
if (pb != null) { return pb; }
if (id == -1)
{
public PlotBlock getPlotBlock() {
if (pb != null) {
return pb;
}
if (id == -1) {
id = block.getTypeId();
}
byte data;
switch (id)
{
switch (id) {
case 0:
case 2:
case 4:
@ -131,17 +126,15 @@ public class BukkitLazyBlock extends LazyBlock
}
pb = new PlotBlock((short) id, data);
return pb;
}
@Override
public int getId()
{
if (id == -1)
{
public int getId() {
if (id == -1) {
id = block.getTypeId();
}
return id;
}
}

View File

@ -6,41 +6,35 @@ import org.bukkit.OfflinePlayer;
import com.intellectualcrafters.plot.object.OfflinePlotPlayer;
public class BukkitOfflinePlayer implements OfflinePlotPlayer
{
public class BukkitOfflinePlayer implements OfflinePlotPlayer {
public final OfflinePlayer player;
/**
* Please do not use this method. Instead use BukkitUtil.getPlayer(Player), as it caches player objects.
* @param player
*/
public BukkitOfflinePlayer(final OfflinePlayer player)
{
public BukkitOfflinePlayer(final OfflinePlayer player) {
this.player = player;
}
@Override
public UUID getUUID()
{
public UUID getUUID() {
return player.getUniqueId();
}
@Override
public long getLastPlayed()
{
public long getLastPlayed() {
return player.getLastPlayed();
}
@Override
public boolean isOnline()
{
public boolean isOnline() {
return player.isOnline();
}
@Override
public String getName()
{
public String getName() {
return player.getName();
}
}

View File

@ -24,9 +24,8 @@ import com.intellectualcrafters.plot.util.PlotWeather;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.bukkit.util.BukkitUtil;
public class BukkitPlayer extends PlotPlayer
{
public class BukkitPlayer extends PlotPlayer {
public final Player player;
private UUID uuid;
private String name;
@ -34,90 +33,78 @@ public class BukkitPlayer extends PlotPlayer
public HashSet<String> hasPerm = new HashSet<>();
public HashSet<String> noPerm = new HashSet<>();
public boolean offline;
/**
* Please do not use this method. Instead use BukkitUtil.getPlayer(Player), as it caches player objects.
* @param player
*/
public BukkitPlayer(final Player player)
{
public BukkitPlayer(final Player player) {
this.player = player;
}
public BukkitPlayer(final Player player, final boolean offline)
{
public BukkitPlayer(final Player player, final boolean offline) {
this.player = player;
this.offline = offline;
}
@Override
public long getPreviousLogin()
{
if (last == 0)
{
public long getPreviousLogin() {
if (last == 0) {
last = player.getLastPlayed();
}
return last;
}
@Override
public Location getLocation()
{
public Location getLocation() {
final Location loc = super.getLocation();
return loc == null ? BukkitUtil.getLocation(player) : loc;
}
@Override
public UUID getUUID()
{
if (uuid == null)
{
public UUID getUUID() {
if (uuid == null) {
uuid = UUIDHandler.getUUID(this);
}
return uuid;
}
@Override
public boolean hasPermission(final String node)
{
if (Settings.PERMISSION_CACHING)
{
if (noPerm.contains(node)) { return false; }
if (hasPerm.contains(node)) { return true; }
}
if (offline && (EconHandler.manager != null)) { return EconHandler.manager.hasPermission(getName(), node); }
final boolean value = player.hasPermission(node);
if (Settings.PERMISSION_CACHING)
{
if (value)
{
hasPerm.add(node);
public boolean hasPermission(final String node) {
if (Settings.PERMISSION_CACHING) {
if (noPerm.contains(node)) {
return false;
}
else
{
if (hasPerm.contains(node)) {
return true;
}
}
if (offline && (EconHandler.manager != null)) {
return EconHandler.manager.hasPermission(getName(), node);
}
final boolean value = player.hasPermission(node);
if (Settings.PERMISSION_CACHING) {
if (value) {
hasPerm.add(node);
} else {
noPerm.add(node);
}
}
return value;
}
public Permission getPermission(final String node)
{
public Permission getPermission(final String node) {
final PluginManager manager = Bukkit.getPluginManager();
Permission perm = manager.getPermission(node);
if (perm == null)
{
if (perm == null) {
final String[] nodes = node.split("\\.");
perm = new Permission(node);
final StringBuilder n = new StringBuilder();
for (int i = 0; i < (nodes.length - 1); i++)
{
for (int i = 0; i < (nodes.length - 1); i++) {
n.append(nodes[i] + ("."));
if (!node.equals(n + C.PERMISSION_STAR.s()))
{
if (!node.equals(n + C.PERMISSION_STAR.s())) {
final Permission parent = getPermission(n + C.PERMISSION_STAR.s());
if (parent != null)
{
if (parent != null) {
perm.addParent(parent, true);
}
}
@ -128,123 +115,104 @@ public class BukkitPlayer extends PlotPlayer
perm.recalculatePermissibles();
return perm;
}
@Override
public void sendMessage(final String message)
{
public void sendMessage(final String message) {
player.sendMessage(message);
}
@Override
public void sendMessage(final C c, final String... args)
{
public void sendMessage(final C c, final String... args) {
MainUtil.sendMessage(this, c, args);
}
@Override
public void teleport(final Location loc)
{
if ((Math.abs(loc.getX()) >= 30000000) || (Math.abs(loc.getZ()) >= 30000000)) { return; }
public void teleport(final Location loc) {
if ((Math.abs(loc.getX()) >= 30000000) || (Math.abs(loc.getZ()) >= 30000000)) {
return;
}
player.teleport(new org.bukkit.Location(BukkitUtil.getWorld(loc.getWorld()), loc.getX() + 0.5, loc.getY(), loc.getZ() + 0.5, loc.getYaw(), loc.getPitch()), TeleportCause.COMMAND);
}
@Override
public String getName()
{
if (name == null)
{
public String getName() {
if (name == null) {
name = player.getName();
}
return name;
}
@Override
public boolean isOnline()
{
public boolean isOnline() {
return !offline && player.isOnline();
}
@Override
public void setCompassTarget(final Location loc)
{
public void setCompassTarget(final Location loc) {
player.setCompassTarget(new org.bukkit.Location(BukkitUtil.getWorld(loc.getWorld()), loc.getX(), loc.getY(), loc.getZ()));
}
@Override
public Location getLocationFull()
{
public Location getLocationFull() {
return BukkitUtil.getLocationFull(player);
}
@Override
public void setAttribute(String key)
{
public void setAttribute(String key) {
key = "plotsquared_user_attributes." + key;
if ((EconHandler.manager == null) || player.hasPermission("plotsquared_user_attributes.*"))
{
if ((EconHandler.manager == null) || player.hasPermission("plotsquared_user_attributes.*")) {
setMeta(key, true);
return;
}
EconHandler.manager.setPermission(getName(), key, true);
}
@Override
public boolean getAttribute(String key)
{
public boolean getAttribute(String key) {
key = "plotsquared_user_attributes." + key;
if ((EconHandler.manager == null) || player.hasPermission("plotsquared_user_attributes.*"))
{
if ((EconHandler.manager == null) || player.hasPermission("plotsquared_user_attributes.*")) {
final Object v = getMeta(key);
return v == null ? false : (Boolean) v;
}
Permission perm = Bukkit.getServer().getPluginManager().getPermission(key);
if (perm == null)
{
if (perm == null) {
perm = new Permission(key, PermissionDefault.FALSE);
Bukkit.getServer().getPluginManager().addPermission(perm);
Bukkit.getServer().getPluginManager().recalculatePermissionDefaults(perm);
}
return player.hasPermission(key);
}
@Override
public void removeAttribute(String key)
{
public void removeAttribute(String key) {
key = "plotsquared_user_attributes." + key;
if ((EconHandler.manager == null) || player.hasPermission("plotsquared_user_attributes.*"))
{
if ((EconHandler.manager == null) || player.hasPermission("plotsquared_user_attributes.*")) {
deleteMeta(key);
return;
}
EconHandler.manager.setPermission(getName(), key, false);
}
@Override
public void loadData()
{
if (!player.isOnline())
{
public void loadData() {
if (!player.isOnline()) {
player.loadData();
}
}
@Override
public void saveData()
{
public void saveData() {
player.saveData();
}
@Override
public void setWeather(final PlotWeather weather)
{
switch (weather)
{
public void setWeather(final PlotWeather weather) {
switch (weather) {
case CLEAR:
player.setPlayerWeather(WeatherType.CLEAR);
return;
case RAIN:
{
case RAIN: {
player.setPlayerWeather(WeatherType.DOWNFALL);
return;
}
@ -253,12 +221,10 @@ public class BukkitPlayer extends PlotPlayer
return;
}
}
@Override
public PlotGamemode getGamemode()
{
switch (player.getGameMode())
{
public PlotGamemode getGamemode() {
switch (player.getGameMode()) {
case ADVENTURE:
return PlotGamemode.ADVENTURE;
case CREATIVE:
@ -270,12 +236,10 @@ public class BukkitPlayer extends PlotPlayer
}
return null;
}
@Override
public void setGamemode(final PlotGamemode gamemode)
{
switch (gamemode)
{
public void setGamemode(final PlotGamemode gamemode) {
switch (gamemode) {
case ADVENTURE:
player.setGameMode(GameMode.ADVENTURE);
return;
@ -290,28 +254,24 @@ public class BukkitPlayer extends PlotPlayer
return;
}
}
@Override
public void setTime(final long time)
{
public void setTime(final long time) {
player.setPlayerTime(time, false);
}
@Override
public void setFlight(final boolean fly)
{
public void setFlight(final boolean fly) {
player.setAllowFlight(fly);
}
@Override
public void playMusic(final Location loc, final int id)
{
public void playMusic(final Location loc, final int id) {
player.playEffect(BukkitUtil.getLocation(loc), Effect.RECORD_PLAY, id);
}
@Override
public void kick(final String message)
{
public void kick(final String message) {
player.kickPlayer(message);
}
}

View File

@ -37,8 +37,7 @@ import com.intellectualcrafters.plot.object.entity.ArmorStandStats;
import com.intellectualcrafters.plot.object.entity.EntityBaseStats;
import com.intellectualcrafters.plot.object.entity.HorseStats;
public class EntityWrapper
{
public class EntityWrapper {
public short id;
public float yaw;
public float pitch;
@ -58,45 +57,37 @@ public class EntityWrapper
public TameableStats tamed;
private HorseStats horse;
private ArmorStandStats stand;
private int hash;
@Override
public boolean equals(final Object obj)
{
public boolean equals(final Object obj) {
return hash == obj.hashCode();
}
@Override
public int hashCode()
{
public int hashCode() {
return hash;
}
public void storeInventory(final InventoryHolder held)
{
public void storeInventory(final InventoryHolder held) {
inventory = held.getInventory().getContents().clone();
}
private void restoreLiving(final LivingEntity entity)
{
if (lived.loot)
{
private void restoreLiving(final LivingEntity entity) {
if (lived.loot) {
entity.setCanPickupItems(lived.loot);
}
if (lived.name != null)
{
if (lived.name != null) {
entity.setCustomName(lived.name);
entity.setCustomNameVisible(lived.visible);
}
if ((lived.potions != null) && (lived.potions.size() > 0))
{
if ((lived.potions != null) && (lived.potions.size() > 0)) {
entity.addPotionEffects(lived.potions);
}
entity.setRemainingAir(lived.air);
entity.setRemoveWhenFarAway(lived.persistent);
if (lived.equipped)
{
if (lived.equipped) {
final EntityEquipment equipment = entity.getEquipment();
equipment.setItemInHand(lived.hands);
equipment.setHelmet(lived.helmet);
@ -104,22 +95,19 @@ public class EntityWrapper
equipment.setLeggings(lived.leggings);
equipment.setBoots(lived.boots);
}
if (lived.leashed)
{
if (lived.leashed) {
// TODO leashes
// World world = entity.getWorld();
// Entity leash = world.spawnEntity(new Location(world, Math.floor(x) + lived.leash_x, Math.floor(y) + lived.leash_y, Math.floor(z) + lived.leash_z), EntityType.LEASH_HITCH);
// entity.setLeashHolder(leash);
}
}
private void restoreInventory(final InventoryHolder entity)
{
private void restoreInventory(final InventoryHolder entity) {
entity.getInventory().setContents(inventory);
}
public void storeLiving(final LivingEntity lived)
{
public void storeLiving(final LivingEntity lived) {
this.lived = new LivingEntityStats();
this.lived.potions = lived.getActivePotionEffects();
this.lived.loot = lived.getCanPickupItems();
@ -129,8 +117,7 @@ public class EntityWrapper
this.lived.air = (short) lived.getRemainingAir();
this.lived.persistent = lived.getRemoveWhenFarAway();
this.lived.leashed = lived.isLeashed();
if (this.lived.leashed)
{
if (this.lived.leashed) {
final Location loc = lived.getLeashHolder().getLocation();
this.lived.leash_x = (short) (x - loc.getBlockX());
this.lived.leash_y = (short) (y - loc.getBlockY());
@ -138,8 +125,7 @@ public class EntityWrapper
}
final EntityEquipment equipment = lived.getEquipment();
this.lived.equipped = equipment != null;
if (this.lived.equipped)
{
if (this.lived.equipped) {
this.lived.hands = equipment.getItemInHand().clone();
this.lived.boots = equipment.getBoots().clone();
this.lived.leggings = equipment.getLeggings().clone();
@ -147,53 +133,43 @@ public class EntityWrapper
this.lived.helmet = equipment.getHelmet().clone();
}
}
private void restoreTameable(final Tameable entity)
{
if (tamed.tamed)
{
if (tamed.owner != null)
{
private void restoreTameable(final Tameable entity) {
if (tamed.tamed) {
if (tamed.owner != null) {
entity.setTamed(true);
entity.setOwner(tamed.owner);
}
}
}
private void restoreAgeable(final Ageable entity)
{
if (!aged.adult)
{
private void restoreAgeable(final Ageable entity) {
if (!aged.adult) {
entity.setBaby();
}
if (aged.locked)
{
if (aged.locked) {
entity.setAgeLock(aged.locked);
}
if (aged.age > 0)
{
if (aged.age > 0) {
entity.setAge(aged.age);
}
}
public void storeAgeable(final Ageable aged)
{
public void storeAgeable(final Ageable aged) {
this.aged = new AgeableStats();
this.aged.age = aged.getAge();
this.aged.locked = aged.getAgeLock();
this.aged.adult = aged.isAdult();
}
public void storeTameable(final Tameable tamed)
{
public void storeTameable(final Tameable tamed) {
this.tamed = new TameableStats();
this.tamed.owner = tamed.getOwner();
this.tamed.tamed = tamed.isTamed();
}
@SuppressWarnings("deprecation")
public EntityWrapper(final org.bukkit.entity.Entity entity, final short depth)
{
public EntityWrapper(final org.bukkit.entity.Entity entity, final short depth) {
hash = entity.getEntityId();
this.depth = depth;
final Location loc = entity.getLocation();
@ -203,11 +179,12 @@ public class EntityWrapper
y = loc.getY();
z = loc.getZ();
id = entity.getType().getTypeId();
if (depth == 0) { return; }
if (depth == 0) {
return;
}
base = new EntityBaseStats();
final Entity p = entity.getPassenger();
if (p != null)
{
if (p != null) {
base.passenger = new EntityWrapper(p, depth);
}
base.fall = entity.getFallDistance();
@ -217,9 +194,10 @@ public class EntityWrapper
base.v_x = velocity.getX();
base.v_y = velocity.getY();
base.v_z = velocity.getZ();
if (depth == 1) { return; }
switch (entity.getType())
{
if (depth == 1) {
return;
}
switch (entity.getType()) {
case ARROW:
case BOAT:
case COMPLEX_PART:
@ -248,25 +226,21 @@ public class EntityWrapper
case THROWN_EXP_BOTTLE:
case WEATHER:
case WITHER_SKULL:
case UNKNOWN:
{
case UNKNOWN: {
// Do this stuff later
return;
}
default:
{
default: {
PS.debug("&cCOULD NOT IDENTIFY ENTITY: " + entity.getType());
return;
}
// MISC //
case DROPPED_ITEM:
{
case DROPPED_ITEM: {
final Item item = (Item) entity;
stack = item.getItemStack();
return;
}
case ITEM_FRAME:
{
case ITEM_FRAME: {
final ItemFrame itemframe = (ItemFrame) entity;
x = Math.floor(x);
y = Math.floor(y);
@ -275,8 +249,7 @@ public class EntityWrapper
stack = itemframe.getItem().clone();
return;
}
case PAINTING:
{
case PAINTING: {
final Painting painting = (Painting) entity;
x = Math.floor(x);
y = Math.floor(y);
@ -284,8 +257,7 @@ public class EntityWrapper
final Art a = painting.getArt();
dataByte = getOrdinal(BlockFace.values(), painting.getFacing());
final int h = a.getBlockHeight();
if ((h % 2) == 0)
{
if ((h % 2) == 0) {
y -= 1;
}
dataString = a.name();
@ -293,21 +265,18 @@ public class EntityWrapper
}
// END MISC //
// INVENTORY HOLDER //
case MINECART_CHEST:
{
case MINECART_CHEST: {
storeInventory((InventoryHolder) entity);
return;
}
case MINECART_HOPPER:
{
case MINECART_HOPPER: {
storeInventory((InventoryHolder) entity);
return;
}
// START LIVING ENTITY //
// START AGEABLE //
// START TAMEABLE //
case HORSE:
{
case HORSE: {
final Horse horse = (Horse) entity;
this.horse = new HorseStats();
this.horse.jump = horse.getJumpStrength();
@ -323,16 +292,14 @@ public class EntityWrapper
}
// END INVENTORY HOLDER //
case WOLF:
case OCELOT:
{
case OCELOT: {
storeTameable((Tameable) entity);
storeAgeable((Ageable) entity);
storeLiving((LivingEntity) entity);
return;
}
// END AMEABLE //
case SHEEP:
{
case SHEEP: {
final Sheep sheep = (Sheep) entity;
dataByte = (byte) ((sheep).isSheared() ? 1 : 0);
dataByte2 = sheep.getColor().getDyeData();
@ -344,88 +311,78 @@ public class EntityWrapper
case CHICKEN:
case COW:
case MUSHROOM_COW:
case PIG:
{
case PIG: {
storeAgeable((Ageable) entity);
storeLiving((LivingEntity) entity);
return;
}
// END AGEABLE //
case RABBIT:
{ // NEW
case RABBIT: { // NEW
dataByte = getOrdinal(Type.values(), ((Rabbit) entity).getRabbitType());
storeAgeable((Ageable) entity);
storeLiving((LivingEntity) entity);
return;
}
case GUARDIAN:
{ // NEW
case GUARDIAN: { // NEW
dataByte = (byte) (((Guardian) entity).isElder() ? 1 : 0);
storeLiving((LivingEntity) entity);
return;
}
case SKELETON:
{ // NEW
case SKELETON: { // NEW
dataByte = (byte) ((Skeleton) entity).getSkeletonType().getId();
storeLiving((LivingEntity) entity);
return;
}
case ARMOR_STAND:
{ // NEW
// CHECK positions
case ARMOR_STAND: { // NEW
// CHECK positions
final ArmorStand stand = (ArmorStand) entity;
inventory = new ItemStack[] { stand.getItemInHand().clone(), stand.getHelmet().clone(), stand.getChestplate().clone(), stand.getLeggings().clone(), stand.getBoots().clone() };
storeLiving((LivingEntity) entity);
this.stand = new ArmorStandStats();
final EulerAngle head = stand.getHeadPose();
this.stand.head[0] = (float) head.getX();
this.stand.head[1] = (float) head.getY();
this.stand.head[2] = (float) head.getZ();
final EulerAngle body = stand.getBodyPose();
this.stand.body[0] = (float) body.getX();
this.stand.body[1] = (float) body.getY();
this.stand.body[2] = (float) body.getZ();
final EulerAngle leftLeg = stand.getLeftLegPose();
this.stand.leftLeg[0] = (float) leftLeg.getX();
this.stand.leftLeg[1] = (float) leftLeg.getY();
this.stand.leftLeg[2] = (float) leftLeg.getZ();
final EulerAngle rightLeg = stand.getRightLegPose();
this.stand.rightLeg[0] = (float) rightLeg.getX();
this.stand.rightLeg[1] = (float) rightLeg.getY();
this.stand.rightLeg[2] = (float) rightLeg.getZ();
final EulerAngle leftArm = stand.getLeftArmPose();
this.stand.leftArm[0] = (float) leftArm.getX();
this.stand.leftArm[1] = (float) leftArm.getY();
this.stand.leftArm[2] = (float) leftArm.getZ();
final EulerAngle rightArm = stand.getRightArmPose();
this.stand.rightArm[0] = (float) rightArm.getX();
this.stand.rightArm[1] = (float) rightArm.getY();
this.stand.rightArm[2] = (float) rightArm.getZ();
if (stand.hasArms())
{
if (stand.hasArms()) {
this.stand.arms = true;
}
if (!stand.hasBasePlate())
{
if (!stand.hasBasePlate()) {
this.stand.noplate = true;
}
if (!stand.hasGravity())
{
if (!stand.hasGravity()) {
this.stand.nogravity = true;
}
if (!stand.isVisible())
{
if (!stand.isVisible()) {
this.stand.invisible = true;
}
if (stand.isSmall())
{
if (stand.isSmall()) {
this.stand.small = true;
}
return;
@ -448,42 +405,37 @@ public class EntityWrapper
case CREEPER:
case BLAZE:
case SNOWMAN:
case IRON_GOLEM:
{
case IRON_GOLEM: {
storeLiving((LivingEntity) entity);
return;
}
// END LIVING //
}
}
@SuppressWarnings("deprecation")
public Entity spawn(final World world, final int x_offset, final int z_offset)
{
public Entity spawn(final World world, final int x_offset, final int z_offset) {
final Location loc = new Location(world, x + x_offset, y, z + z_offset);
loc.setYaw(yaw);
loc.setPitch(pitch);
if (id == -1) { return null; }
if (id == -1) {
return null;
}
final EntityType type = EntityType.fromId(id);
Entity entity;
switch (type)
{
case DROPPED_ITEM:
{
switch (type) {
case DROPPED_ITEM: {
return world.dropItem(loc, stack);
}
case PLAYER:
case LEASH_HITCH:
{
case LEASH_HITCH: {
return null;
}
case ITEM_FRAME:
{
case ITEM_FRAME: {
entity = world.spawn(loc, ItemFrame.class);
break;
}
case PAINTING:
{
case PAINTING: {
entity = world.spawn(loc, Painting.class);
break;
}
@ -491,32 +443,28 @@ public class EntityWrapper
entity = world.spawnEntity(loc, type);
break;
}
if (depth == 0) { return entity; }
if (base.passenger != null)
{
try
{
entity.setPassenger(base.passenger.spawn(world, x_offset, z_offset));
}
catch (final Exception e)
{}
if (depth == 0) {
return entity;
}
if (base.fall != 0)
{
if (base.passenger != null) {
try {
entity.setPassenger(base.passenger.spawn(world, x_offset, z_offset));
} catch (final Exception e) {}
}
if (base.fall != 0) {
entity.setFallDistance(base.fall);
}
if (base.fire != 0)
{
if (base.fire != 0) {
entity.setFireTicks(base.fire);
}
if (base.age != 0)
{
if (base.age != 0) {
entity.setTicksLived(base.age);
}
entity.setVelocity(new Vector(base.v_x, base.v_y, base.v_z));
if (depth == 1) { return entity; }
switch (entity.getType())
{
if (depth == 1) {
return entity;
}
switch (entity.getType()) {
case ARROW:
case BOAT:
case COMPLEX_PART:
@ -545,26 +493,22 @@ public class EntityWrapper
case WEATHER:
case WITHER_SKULL:
case MINECART_FURNACE:
case UNKNOWN:
{
case UNKNOWN: {
// Do this stuff later
return entity;
}
default:
{
default: {
PS.debug("&cCOULD NOT IDENTIFY ENTITY: " + entity.getType());
return entity;
}
// MISC //
case ITEM_FRAME:
{
case ITEM_FRAME: {
final ItemFrame itemframe = (ItemFrame) entity;
itemframe.setRotation(Rotation.values()[dataByte]);
itemframe.setItem(stack);
return entity;
}
case PAINTING:
{
case PAINTING: {
final Painting painting = (Painting) entity;
painting.setFacingDirection(BlockFace.values()[dataByte], true);
painting.setArt(Art.getByName(dataString), true);
@ -572,21 +516,18 @@ public class EntityWrapper
}
// END MISC //
// INVENTORY HOLDER //
case MINECART_CHEST:
{
case MINECART_CHEST: {
restoreInventory((InventoryHolder) entity);
return entity;
}
case MINECART_HOPPER:
{
case MINECART_HOPPER: {
restoreInventory((InventoryHolder) entity);
return entity;
}
// START LIVING ENTITY //
// START AGEABLE //
// START TAMEABLE //
case HORSE:
{
case HORSE: {
final Horse horse = (Horse) entity;
horse.setJumpStrength(this.horse.jump);
horse.setCarryingChest(this.horse.chest);
@ -601,23 +542,19 @@ public class EntityWrapper
}
// END INVENTORY HOLDER //
case WOLF:
case OCELOT:
{
case OCELOT: {
restoreTameable((Tameable) entity);
restoreAgeable((Ageable) entity);
restoreLiving((LivingEntity) entity);
return entity;
}
// END AMEABLE //
case SHEEP:
{
case SHEEP: {
final Sheep sheep = (Sheep) entity;
if (dataByte == 1)
{
if (dataByte == 1) {
sheep.setSheared(true);
}
if (dataByte2 != 0)
{
if (dataByte2 != 0) {
sheep.setColor(DyeColor.getByDyeData(dataByte2));
}
restoreAgeable((Ageable) entity);
@ -628,113 +565,89 @@ public class EntityWrapper
case CHICKEN:
case COW:
case MUSHROOM_COW:
case PIG:
{
case PIG: {
restoreAgeable((Ageable) entity);
restoreLiving((LivingEntity) entity);
return entity;
}
// END AGEABLE //
case RABBIT:
{ // NEW
if (dataByte != 0)
{
case RABBIT: { // NEW
if (dataByte != 0) {
((Rabbit) entity).setRabbitType(Type.values()[dataByte]);
}
restoreAgeable((Ageable) entity);
restoreLiving((LivingEntity) entity);
return entity;
}
case GUARDIAN:
{ // NEW
if (dataByte != 0)
{
case GUARDIAN: { // NEW
if (dataByte != 0) {
((Guardian) entity).setElder(true);
}
restoreLiving((LivingEntity) entity);
return entity;
}
case SKELETON:
{ // NEW
if (dataByte != 0)
{
case SKELETON: { // NEW
if (dataByte != 0) {
((Skeleton) entity).setSkeletonType(SkeletonType.values()[dataByte]);
}
storeLiving((LivingEntity) entity);
return entity;
}
case ARMOR_STAND:
{ // NEW
// CHECK positions
case ARMOR_STAND: { // NEW
// CHECK positions
final ArmorStand stand = (ArmorStand) entity;
if (inventory[0] != null)
{
if (inventory[0] != null) {
stand.setItemInHand(inventory[0]);
}
if (inventory[1] != null)
{
if (inventory[1] != null) {
stand.setHelmet(inventory[1]);
}
if (inventory[2] != null)
{
if (inventory[2] != null) {
stand.setChestplate(inventory[2]);
}
if (inventory[3] != null)
{
if (inventory[3] != null) {
stand.setLeggings(inventory[3]);
}
if (inventory[4] != null)
{
if (inventory[4] != null) {
stand.setBoots(inventory[4]);
}
if ((this.stand.head[0] != 0) || (this.stand.head[1] != 0) || (this.stand.head[2] != 0))
{
if ((this.stand.head[0] != 0) || (this.stand.head[1] != 0) || (this.stand.head[2] != 0)) {
final 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))
{
if ((this.stand.body[0] != 0) || (this.stand.body[1] != 0) || (this.stand.body[2] != 0)) {
final 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))
{
if ((this.stand.leftLeg[0] != 0) || (this.stand.leftLeg[1] != 0) || (this.stand.leftLeg[2] != 0)) {
final 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))
{
if ((this.stand.rightLeg[0] != 0) || (this.stand.rightLeg[1] != 0) || (this.stand.rightLeg[2] != 0)) {
final 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))
{
if ((this.stand.leftArm[0] != 0) || (this.stand.leftArm[1] != 0) || (this.stand.leftArm[2] != 0)) {
final 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))
{
if ((this.stand.rightArm[0] != 0) || (this.stand.rightArm[1] != 0) || (this.stand.rightArm[2] != 0)) {
final EulerAngle pose = new EulerAngle(this.stand.rightArm[0], this.stand.rightArm[1], this.stand.rightArm[2]);
stand.setRightArmPose(pose);
}
if (this.stand.invisible)
{
if (this.stand.invisible) {
stand.setVisible(false);
}
if (this.stand.arms)
{
if (this.stand.arms) {
stand.setArms(true);
}
if (this.stand.nogravity)
{
if (this.stand.nogravity) {
stand.setGravity(false);
}
if (this.stand.noplate)
{
if (this.stand.noplate) {
stand.setBasePlate(false);
}
if (this.stand.small)
{
if (this.stand.small) {
stand.setSmall(true);
}
restoreLiving((LivingEntity) entity);
@ -758,20 +671,19 @@ public class EntityWrapper
case CREEPER:
case BLAZE:
case SNOWMAN:
case IRON_GOLEM:
{
case IRON_GOLEM: {
restoreLiving((LivingEntity) entity);
return entity;
}
// END LIVING //
}
}
private byte getOrdinal(final Object[] list, final Object value)
{
for (byte i = 0; i < list.length; i++)
{
if (list[i].equals(value)) { return i; }
private byte getOrdinal(final Object[] list, final Object value) {
for (byte i = 0; i < list.length; i++) {
if (list[i].equals(value)) {
return i;
}
}
return 0;
}

View File

@ -5,8 +5,7 @@ import java.util.Collection;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
public class LivingEntityStats
{
public class LivingEntityStats {
public boolean loot;
public String name;
public boolean visible;

View File

@ -2,8 +2,7 @@ package com.plotsquared.bukkit.object.entity;
import org.bukkit.entity.AnimalTamer;
public class TameableStats
{
public class TameableStats {
public AnimalTamer owner;
public boolean tamed;
}

View File

@ -4,18 +4,13 @@ import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.AbstractTitle;
import com.plotsquared.bukkit.object.BukkitPlayer;
public class DefaultTitle extends AbstractTitle
{
public class DefaultTitle extends AbstractTitle {
@Override
public void sendTitle(final PlotPlayer player, final String head, final String sub, final int in, final int delay, final int out)
{
try
{
public void sendTitle(final PlotPlayer player, final String head, final String sub, final int in, final int delay, final int out) {
try {
final DefaultTitleManager title = new DefaultTitleManager(head, sub, in, delay, out);
title.send(((BukkitPlayer) player).player);
}
catch (final Throwable e)
{
} catch (final Throwable e) {
AbstractTitle.TITLE_CLASS = new DefaultTitle_183();
AbstractTitle.TITLE_CLASS.sendTitle(player, head, sub, in, delay, out);
}

View File

@ -17,8 +17,7 @@ import org.bukkit.entity.Player;
* @author Maxim Van de Wynckel
*
*/
public class DefaultTitleManager
{
public class DefaultTitleManager {
/* Title packet */
private Class<?> packetTitle;
/* Title packet actions ENUM */
@ -38,7 +37,7 @@ public class DefaultTitleManager
private int fadeOutTime = -1;
private boolean ticks = false;
private static final Map<Class<?>, Class<?>> CORRESPONDING_TYPES = new HashMap<Class<?>, Class<?>>();
/**
* Create a new 1.8 title
*
@ -46,12 +45,11 @@ public class DefaultTitleManager
* Title
* @throws ClassNotFoundException
*/
public DefaultTitleManager(final String title) throws ClassNotFoundException
{
public DefaultTitleManager(final String title) throws ClassNotFoundException {
this.title = title;
loadClasses();
}
/**
* Create a new 1.8 title
*
@ -61,13 +59,12 @@ public class DefaultTitleManager
* Subtitle text
* @throws ClassNotFoundException
*/
public DefaultTitleManager(final String title, final String subtitle) throws ClassNotFoundException
{
public DefaultTitleManager(final String title, final String subtitle) throws ClassNotFoundException {
this.title = title;
this.subtitle = subtitle;
loadClasses();
}
/**
* Copy 1.8 title
*
@ -75,8 +72,7 @@ public class DefaultTitleManager
* Title
* @throws ClassNotFoundException
*/
public DefaultTitleManager(final DefaultTitleManager title) throws ClassNotFoundException
{
public DefaultTitleManager(final DefaultTitleManager title) throws ClassNotFoundException {
// Copy title
this.title = title.title;
subtitle = title.subtitle;
@ -88,7 +84,7 @@ public class DefaultTitleManager
ticks = title.ticks;
loadClasses();
}
/**
* Create a new 1.8 title
*
@ -104,8 +100,7 @@ public class DefaultTitleManager
* Fade out time
* @throws ClassNotFoundException
*/
public DefaultTitleManager(final String title, final String subtitle, final int fadeInTime, final int stayTime, final int fadeOutTime) throws ClassNotFoundException
{
public DefaultTitleManager(final String title, final String subtitle, final int fadeInTime, final int stayTime, final int fadeOutTime) throws ClassNotFoundException {
this.title = title;
this.subtitle = subtitle;
this.fadeInTime = fadeInTime;
@ -113,132 +108,120 @@ public class DefaultTitleManager
this.fadeOutTime = fadeOutTime;
loadClasses();
}
/**
* Load spigot and NMS classes
* @throws ClassNotFoundException
*/
private void loadClasses() throws ClassNotFoundException
{
private void loadClasses() throws ClassNotFoundException {
packetTitle = getNMSClass("PacketPlayOutTitle");
packetActions = getNMSClass("EnumTitleAction");
chatBaseComponent = getNMSClass("IChatBaseComponent");
nmsChatSerializer = getNMSClass("ChatSerializer");
}
/**
* Set title text
*
* @param title
* Title
*/
public void setTitle(final String title)
{
public void setTitle(final String title) {
this.title = title;
}
/**
* Get title text
*
* @return Title text
*/
public String getTitle()
{
public String getTitle() {
return title;
}
/**
* Set subtitle text
*
* @param subtitle
* Subtitle text
*/
public void setSubtitle(final String subtitle)
{
public void setSubtitle(final String subtitle) {
this.subtitle = subtitle;
}
/**
* Get subtitle text
*
* @return Subtitle text
*/
public String getSubtitle()
{
public String getSubtitle() {
return subtitle;
}
/**
* Set the title color
*
* @param color
* Chat color
*/
public void setTitleColor(final ChatColor color)
{
public void setTitleColor(final ChatColor color) {
titleColor = color;
}
/**
* Set the subtitle color
*
* @param color
* Chat color
*/
public void setSubtitleColor(final ChatColor color)
{
public void setSubtitleColor(final ChatColor color) {
subtitleColor = color;
}
/**
* Set title fade in time
*
* @param time
* Time
*/
public void setFadeInTime(final int time)
{
public void setFadeInTime(final int time) {
fadeInTime = time;
}
/**
* Set title fade out time
*
* @param time
* Time
*/
public void setFadeOutTime(final int time)
{
public void setFadeOutTime(final int time) {
fadeOutTime = time;
}
/**
* Set title stay time
*
* @param time
* Time
*/
public void setStayTime(final int time)
{
public void setStayTime(final int time) {
stayTime = time;
}
/**
* Set timings to ticks
*/
public void setTimingsToTicks()
{
public void setTimingsToTicks() {
ticks = true;
}
/**
* Set timings to seconds
*/
public void setTimingsToSeconds()
{
public void setTimingsToSeconds() {
ticks = false;
}
/**
* Send the title to a player
*
@ -248,10 +231,8 @@ public class DefaultTitleManager
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public void send(final Player player) throws Exception
{
if (packetTitle != null)
{
public void send(final Player player) throws Exception {
if (packetTitle != null) {
// First reset previous settings
resetTitle(player);
// Send timings first
@ -259,11 +240,10 @@ public class DefaultTitleManager
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object[] actions = packetActions.getEnumConstants();
final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent, Integer.TYPE, Integer.TYPE, Integer.TYPE).newInstance(actions[2], 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[2], null, fadeInTime * (ticks ? 1 : 20),
stayTime * (ticks ? 1 : 20), fadeOutTime * (ticks ? 1 : 20));
// Send if set
if ((fadeInTime != -1) && (fadeOutTime != -1) && (stayTime != -1))
{
if ((fadeInTime != -1) && (fadeOutTime != -1) && (stayTime != -1)) {
sendPacket.invoke(connection, packet);
}
// Send title
@ -271,8 +251,7 @@ public class DefaultTitleManager
"{text:\"" + ChatColor.translateAlternateColorCodes('&', title) + "\",color:" + titleColor.name().toLowerCase() + "}");
packet = packetTitle.getConstructor(packetActions, chatBaseComponent).newInstance(actions[0], serialized);
sendPacket.invoke(connection, packet);
if (subtitle != "")
{
if (subtitle != "") {
// Send subtitle if present
serialized = getMethod(nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', subtitle) + "\",color:" + subtitleColor.name().toLowerCase() + "}");
@ -281,19 +260,17 @@ public class DefaultTitleManager
}
}
}
/**
* Broadcast the title to all players
* @throws Exception
*/
public void broadcast() throws Exception
{
for (final Player p : Bukkit.getOnlinePlayers())
{
public void broadcast() throws Exception {
for (final Player p : Bukkit.getOnlinePlayers()) {
send(p);
}
}
/**
* Clear the title
*
@ -302,8 +279,7 @@ public class DefaultTitleManager
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public void clearTitle(final Player player) throws Exception
{
public void clearTitle(final Player player) throws Exception {
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
@ -312,15 +288,14 @@ public class DefaultTitleManager
final Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent).newInstance(actions[3], null);
sendPacket.invoke(connection, packet);
}
/**
* Reset the title settings
*
* @param player
* Player
*/
public void resetTitle(final Player player) throws Exception
{
public void resetTitle(final Player player) throws Exception {
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
@ -329,108 +304,93 @@ public class DefaultTitleManager
final Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent).newInstance(actions[4], null);
sendPacket.invoke(connection, packet);
}
private Class<?> getPrimitiveType(final Class<?> clazz)
{
private Class<?> getPrimitiveType(final Class<?> clazz) {
return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz;
}
private Class<?>[] toPrimitiveTypeArray(final Class<?>[] classes)
{
private Class<?>[] toPrimitiveTypeArray(final Class<?>[] classes) {
final int a = classes != null ? classes.length : 0;
final Class<?>[] types = new Class<?>[a];
for (int i = 0; i < a; i++)
{
for (int i = 0; i < a; i++) {
types[i] = getPrimitiveType(classes[i]);
}
return types;
}
private static boolean equalsTypeArray(final Class<?>[] a, final 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; }
private static boolean equalsTypeArray(final Class<?>[] a, final 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(final Object obj)
{
try
{
private Object getHandle(final Object obj) {
try {
return getMethod("getHandle", obj.getClass()).invoke(obj);
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
return null;
}
}
private Method getMethod(final String name, final Class<?> clazz, final Class<?>... paramTypes)
{
private Method getMethod(final String name, final Class<?> clazz, final Class<?>... paramTypes) {
final Class<?>[] t = toPrimitiveTypeArray(paramTypes);
for (final Method m : clazz.getMethods())
{
for (final Method m : clazz.getMethods()) {
final Class<?>[] types = toPrimitiveTypeArray(m.getParameterTypes());
if (m.getName().equals(name) && equalsTypeArray(types, t)) { return m; }
if (m.getName().equals(name) && equalsTypeArray(types, t)) {
return m;
}
}
return null;
}
private String getVersion()
{
private String getVersion() {
final String name = Bukkit.getServer().getClass().getPackage().getName();
final String version = name.substring(name.lastIndexOf('.') + 1) + ".";
return version;
}
private Class<?> getNMSClass(final String className) throws ClassNotFoundException
{
private Class<?> getNMSClass(final String className) throws ClassNotFoundException {
final String fullName = "net.minecraft.server." + getVersion() + className;
Class<?> clazz = null;
clazz = Class.forName(fullName);
return clazz;
}
private Field getField(final Class<?> clazz, final String name)
{
try
{
private Field getField(final Class<?> clazz, final String name) {
try {
final Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field;
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
return null;
}
}
private Method getMethod(final Class<?> clazz, final String name, final Class<?>... args)
{
for (final Method m : clazz.getMethods())
{
if (m.getName().equals(name) && ((args.length == 0) || ClassListEqual(args, m.getParameterTypes())))
{
private Method getMethod(final Class<?> clazz, final String name, final Class<?>... args) {
for (final Method m : clazz.getMethods()) {
if (m.getName().equals(name) && ((args.length == 0) || ClassListEqual(args, m.getParameterTypes()))) {
m.setAccessible(true);
return m;
}
}
return null;
}
private boolean ClassListEqual(final Class<?>[] l1, final Class<?>[] l2)
{
private boolean ClassListEqual(final Class<?>[] l1, final Class<?>[] l2) {
boolean equal = true;
if (l1.length != l2.length) { return false; }
for (int i = 0; i < l1.length; i++)
{
if (l1[i] != l2[i])
{
if (l1.length != l2.length) {
return false;
}
for (int i = 0; i < l1.length; i++) {
if (l1[i] != l2[i]) {
equal = false;
break;
}

View File

@ -17,8 +17,7 @@ import org.bukkit.entity.Player;
* @author Maxim Van de Wynckel
*
*/
public class DefaultTitleManager_183
{
public class DefaultTitleManager_183 {
/* Title packet */
private Class<?> packetTitle;
/* Title packet actions ENUM */
@ -38,7 +37,7 @@ public class DefaultTitleManager_183
private int fadeOutTime = -1;
private boolean ticks = false;
private static final Map<Class<?>, Class<?>> CORRESPONDING_TYPES = new HashMap<Class<?>, Class<?>>();
/**
* Create a new 1.8 title
*
@ -46,12 +45,11 @@ public class DefaultTitleManager_183
* Title
* @throws ClassNotFoundException
*/
public DefaultTitleManager_183(final String title) throws ClassNotFoundException
{
public DefaultTitleManager_183(final String title) throws ClassNotFoundException {
this.title = title;
loadClasses();
}
/**
* Create a new 1.8 title
*
@ -61,13 +59,12 @@ public class DefaultTitleManager_183
* Subtitle text
* @throws ClassNotFoundException
*/
public DefaultTitleManager_183(final String title, final String subtitle) throws ClassNotFoundException
{
public DefaultTitleManager_183(final String title, final String subtitle) throws ClassNotFoundException {
this.title = title;
this.subtitle = subtitle;
loadClasses();
}
/**
* Copy 1.8 title
*
@ -75,8 +72,7 @@ public class DefaultTitleManager_183
* Title
* @throws ClassNotFoundException
*/
public DefaultTitleManager_183(final DefaultTitleManager_183 title) throws ClassNotFoundException
{
public DefaultTitleManager_183(final DefaultTitleManager_183 title) throws ClassNotFoundException {
// Copy title
this.title = title.title;
subtitle = title.subtitle;
@ -88,7 +84,7 @@ public class DefaultTitleManager_183
ticks = title.ticks;
loadClasses();
}
/**
* Create a new 1.8 title
*
@ -104,8 +100,7 @@ public class DefaultTitleManager_183
* Fade out time
* @throws ClassNotFoundException
*/
public DefaultTitleManager_183(final String title, final String subtitle, final int fadeInTime, final int stayTime, final int fadeOutTime) throws ClassNotFoundException
{
public DefaultTitleManager_183(final String title, final String subtitle, final int fadeInTime, final int stayTime, final int fadeOutTime) throws ClassNotFoundException {
this.title = title;
this.subtitle = subtitle;
this.fadeInTime = fadeInTime;
@ -113,133 +108,121 @@ public class DefaultTitleManager_183
this.fadeOutTime = fadeOutTime;
loadClasses();
}
/**
* Load spigot and NMS classes
* @throws ClassNotFoundException
*/
private void loadClasses() throws ClassNotFoundException
{
private void loadClasses() throws ClassNotFoundException {
packetTitle = getNMSClass("PacketPlayOutTitle");
chatBaseComponent = getNMSClass("IChatBaseComponent");
packetActions = getNMSClass("PacketPlayOutTitle$EnumTitleAction");
nmsChatSerializer = getNMSClass("IChatBaseComponent$ChatSerializer");
}
/**
* Set title text
*
* @param title
* Title
*/
public void setTitle(final String title)
{
public void setTitle(final String title) {
this.title = title;
}
/**
* Get title text
*
* @return Title text
*/
public String getTitle()
{
public String getTitle() {
return title;
}
/**
* Set subtitle text
*
* @param subtitle
* Subtitle text
*/
public void setSubtitle(final String subtitle)
{
public void setSubtitle(final String subtitle) {
this.subtitle = subtitle;
}
/**
* Get subtitle text
*
* @return Subtitle text
*/
public String getSubtitle()
{
public String getSubtitle() {
return subtitle;
}
/**
* Set the title color
*
* @param color
* Chat color
*/
public void setTitleColor(final ChatColor color)
{
public void setTitleColor(final ChatColor color) {
titleColor = color;
}
/**
* Set the subtitle color
*
* @param color
* Chat color
*/
public void setSubtitleColor(final ChatColor color)
{
public void setSubtitleColor(final ChatColor color) {
subtitleColor = color;
}
/**
* Set title fade in time
*
* @param time
* Time
*/
public void setFadeInTime(final int time)
{
public void setFadeInTime(final int time) {
fadeInTime = time;
}
/**
* Set title fade out time
*
* @param time
* Time
*/
public void setFadeOutTime(final int time)
{
public void setFadeOutTime(final int time) {
fadeOutTime = time;
}
/**
* Set title stay time
*
* @param time
* Time
*/
public void setStayTime(final int time)
{
public void setStayTime(final int time) {
stayTime = time;
}
/**
* Set timings to ticks
*/
public void setTimingsToTicks()
{
public void setTimingsToTicks() {
ticks = true;
}
/**
* Set timings to seconds
*/
public void setTimingsToSeconds()
{
public void setTimingsToSeconds() {
ticks = false;
}
/**
* Send the title to a player
*
@ -249,10 +232,8 @@ public class DefaultTitleManager_183
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public void send(final Player player) throws Exception
{
if (packetTitle != null)
{
public void send(final Player player) throws Exception {
if (packetTitle != null) {
// First reset previous settings
resetTitle(player);
// Send timings first
@ -260,11 +241,10 @@ public class DefaultTitleManager_183
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object[] actions = packetActions.getEnumConstants();
final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent, Integer.TYPE, Integer.TYPE, Integer.TYPE).newInstance(actions[2], 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[2], null, fadeInTime * (ticks ? 1 : 20),
stayTime * (ticks ? 1 : 20), fadeOutTime * (ticks ? 1 : 20));
// Send if set
if ((fadeInTime != -1) && (fadeOutTime != -1) && (stayTime != -1))
{
if ((fadeInTime != -1) && (fadeOutTime != -1) && (stayTime != -1)) {
sendPacket.invoke(connection, packet);
}
// Send title
@ -272,8 +252,7 @@ public class DefaultTitleManager_183
"{text:\"" + ChatColor.translateAlternateColorCodes('&', title) + "\",color:" + titleColor.name().toLowerCase() + "}");
packet = packetTitle.getConstructor(packetActions, chatBaseComponent).newInstance(actions[0], serialized);
sendPacket.invoke(connection, packet);
if (subtitle != "")
{
if (subtitle != "") {
// Send subtitle if present
serialized = getMethod(nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', subtitle) + "\",color:" + subtitleColor.name().toLowerCase() + "}");
@ -282,19 +261,17 @@ public class DefaultTitleManager_183
}
}
}
/**
* Broadcast the title to all players
* @throws Exception
*/
public void broadcast() throws Exception
{
for (final Player p : Bukkit.getOnlinePlayers())
{
public void broadcast() throws Exception {
for (final Player p : Bukkit.getOnlinePlayers()) {
send(p);
}
}
/**
* Clear the title
*
@ -303,8 +280,7 @@ public class DefaultTitleManager_183
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public void clearTitle(final Player player) throws Exception
{
public void clearTitle(final Player player) throws Exception {
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
@ -313,7 +289,7 @@ public class DefaultTitleManager_183
final Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent).newInstance(actions[3], null);
sendPacket.invoke(connection, packet);
}
/**
* Reset the title settings
*
@ -326,8 +302,7 @@ public class DefaultTitleManager_183
* @throws IllegalAccessException
* @throws InstantiationException
*/
public void resetTitle(final Player player) throws Exception
{
public void resetTitle(final Player player) throws Exception {
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
@ -336,108 +311,93 @@ public class DefaultTitleManager_183
final Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent).newInstance(actions[4], null);
sendPacket.invoke(connection, packet);
}
private Class<?> getPrimitiveType(final Class<?> clazz)
{
private Class<?> getPrimitiveType(final Class<?> clazz) {
return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz;
}
private Class<?>[] toPrimitiveTypeArray(final Class<?>[] classes)
{
private Class<?>[] toPrimitiveTypeArray(final Class<?>[] classes) {
final int a = classes != null ? classes.length : 0;
final Class<?>[] types = new Class<?>[a];
for (int i = 0; i < a; i++)
{
for (int i = 0; i < a; i++) {
types[i] = getPrimitiveType(classes[i]);
}
return types;
}
private static boolean equalsTypeArray(final Class<?>[] a, final 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; }
private static boolean equalsTypeArray(final Class<?>[] a, final 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(final Object obj)
{
try
{
private Object getHandle(final Object obj) {
try {
return getMethod("getHandle", obj.getClass()).invoke(obj);
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
return null;
}
}
private Method getMethod(final String name, final Class<?> clazz, final Class<?>... paramTypes)
{
private Method getMethod(final String name, final Class<?> clazz, final Class<?>... paramTypes) {
final Class<?>[] t = toPrimitiveTypeArray(paramTypes);
for (final Method m : clazz.getMethods())
{
for (final Method m : clazz.getMethods()) {
final Class<?>[] types = toPrimitiveTypeArray(m.getParameterTypes());
if (m.getName().equals(name) && equalsTypeArray(types, t)) { return m; }
if (m.getName().equals(name) && equalsTypeArray(types, t)) {
return m;
}
}
return null;
}
private String getVersion()
{
private String getVersion() {
final String name = Bukkit.getServer().getClass().getPackage().getName();
final String version = name.substring(name.lastIndexOf('.') + 1) + ".";
return version;
}
private Class<?> getNMSClass(final String className) throws ClassNotFoundException
{
private Class<?> getNMSClass(final String className) throws ClassNotFoundException {
final String fullName = "net.minecraft.server." + getVersion() + className;
Class<?> clazz = null;
clazz = Class.forName(fullName);
return clazz;
}
private Field getField(final Class<?> clazz, final String name)
{
try
{
private Field getField(final Class<?> clazz, final String name) {
try {
final Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field;
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
return null;
}
}
private Method getMethod(final Class<?> clazz, final String name, final Class<?>... args)
{
for (final Method m : clazz.getMethods())
{
if (m.getName().equals(name) && ((args.length == 0) || ClassListEqual(args, m.getParameterTypes())))
{
private Method getMethod(final Class<?> clazz, final String name, final Class<?>... args) {
for (final Method m : clazz.getMethods()) {
if (m.getName().equals(name) && ((args.length == 0) || ClassListEqual(args, m.getParameterTypes()))) {
m.setAccessible(true);
return m;
}
}
return null;
}
private boolean ClassListEqual(final Class<?>[] l1, final Class<?>[] l2)
{
private boolean ClassListEqual(final Class<?>[] l1, final Class<?>[] l2) {
boolean equal = true;
if (l1.length != l2.length) { return false; }
for (int i = 0; i < l1.length; i++)
{
if (l1[i] != l2[i])
{
if (l1.length != l2.length) {
return false;
}
for (int i = 0; i < l1.length; i++) {
if (l1[i] != l2[i]) {
equal = false;
break;
}

View File

@ -4,18 +4,13 @@ import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.AbstractTitle;
import com.plotsquared.bukkit.object.BukkitPlayer;
public class DefaultTitle_183 extends AbstractTitle
{
public class DefaultTitle_183 extends AbstractTitle {
@Override
public void sendTitle(final PlotPlayer player, final String head, final String sub, final int in, final int delay, final int out)
{
try
{
public void sendTitle(final PlotPlayer player, final String head, final String sub, final int in, final int delay, final int out) {
try {
final DefaultTitleManager_183 title = new DefaultTitleManager_183(head, sub, in, delay, out);
title.send(((BukkitPlayer) player).player);
}
catch (final Throwable e)
{
} catch (final Throwable e) {
AbstractTitle.TITLE_CLASS = new HackTitle();
AbstractTitle.TITLE_CLASS.sendTitle(player, head, sub, in, delay, out);
}

View File

@ -6,18 +6,13 @@ import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.AbstractTitle;
import com.plotsquared.bukkit.object.BukkitPlayer;
public class HackTitle extends AbstractTitle
{
public class HackTitle extends AbstractTitle {
@Override
public void sendTitle(final PlotPlayer player, final String head, final String sub, final int in, final int delay, final int out)
{
try
{
public void sendTitle(final PlotPlayer player, final String head, final String sub, final int in, final int delay, final int out) {
try {
final HackTitleManager title = new HackTitleManager(head, sub, in, delay, out);
title.send(((BukkitPlayer) player).player);
}
catch (final Throwable e)
{
} catch (final Throwable e) {
PS.debug("&cYour server version does not support titles!");
Settings.TITLES = false;
AbstractTitle.TITLE_CLASS = null;

View File

@ -15,8 +15,7 @@ import org.bukkit.entity.Player;
* @version 1.0.4
* @author Maxim Van de Wynckel
*/
public class HackTitleManager
{
public class HackTitleManager {
/* Title packet */
private Class<?> packetTitle;
/* Title packet actions ENUM */
@ -35,7 +34,7 @@ public class HackTitleManager
private int fadeOutTime = -1;
private boolean ticks = false;
private static final Map<Class<?>, Class<?>> CORRESPONDING_TYPES = new HashMap<Class<?>, Class<?>>();
/**
* Create a new 1.8 title
*
@ -43,12 +42,11 @@ public class HackTitleManager
* Title
* @throws ClassNotFoundException
*/
public HackTitleManager(final String title) throws ClassNotFoundException
{
public HackTitleManager(final String title) throws ClassNotFoundException {
this.title = title;
loadClasses();
}
/**
* Create a new 1.8 title
*
@ -58,13 +56,12 @@ public class HackTitleManager
* Subtitle text
* @throws ClassNotFoundException
*/
public HackTitleManager(final String title, final String subtitle) throws ClassNotFoundException
{
public HackTitleManager(final String title, final String subtitle) throws ClassNotFoundException {
this.title = title;
this.subtitle = subtitle;
loadClasses();
}
/**
* Copy 1.8 title
*
@ -72,8 +69,7 @@ public class HackTitleManager
* Title
* @throws ClassNotFoundException
*/
public HackTitleManager(final HackTitleManager title) throws ClassNotFoundException
{
public HackTitleManager(final HackTitleManager title) throws ClassNotFoundException {
// Copy title
this.title = title.title;
subtitle = title.subtitle;
@ -85,7 +81,7 @@ public class HackTitleManager
ticks = title.ticks;
loadClasses();
}
/**
* Create a new 1.8 title
*
@ -101,8 +97,7 @@ public class HackTitleManager
* Fade out time
* @throws ClassNotFoundException
*/
public HackTitleManager(final String title, final String subtitle, final int fadeInTime, final int stayTime, final int fadeOutTime) throws ClassNotFoundException
{
public HackTitleManager(final String title, final String subtitle, final int fadeInTime, final int stayTime, final int fadeOutTime) throws ClassNotFoundException {
this.title = title;
this.subtitle = subtitle;
this.fadeInTime = fadeInTime;
@ -110,141 +105,127 @@ public class HackTitleManager
this.fadeOutTime = fadeOutTime;
loadClasses();
}
/**
* Load spigot and NMS classes
* @throws ClassNotFoundException
*/
private void loadClasses() throws ClassNotFoundException
{
private void loadClasses() throws ClassNotFoundException {
packetTitle = getClass("org.spigotmc.ProtocolInjector$PacketTitle");
packetActions = getClass("org.spigotmc.ProtocolInjector$PacketTitle$Action");
nmsChatSerializer = getNMSClass("ChatSerializer");
}
/**
* Set title text
*
* @param title
* Title
*/
public void setTitle(final String title)
{
public void setTitle(final String title) {
this.title = title;
}
/**
* Get title text
*
* @return Title text
*/
public String getTitle()
{
public String getTitle() {
return title;
}
/**
* Set subtitle text
*
* @param subtitle
* Subtitle text
*/
public void setSubtitle(final String subtitle)
{
public void setSubtitle(final String subtitle) {
this.subtitle = subtitle;
}
/**
* Get subtitle text
*
* @return Subtitle text
*/
public String getSubtitle()
{
public String getSubtitle() {
return subtitle;
}
/**
* Set the title color
*
* @param color
* Chat color
*/
public void setTitleColor(final ChatColor color)
{
public void setTitleColor(final ChatColor color) {
titleColor = color;
}
/**
* Set the subtitle color
*
* @param color
* Chat color
*/
public void setSubtitleColor(final ChatColor color)
{
public void setSubtitleColor(final ChatColor color) {
subtitleColor = color;
}
/**
* Set title fade in time
*
* @param time
* Time
*/
public void setFadeInTime(final int time)
{
public void setFadeInTime(final int time) {
fadeInTime = time;
}
/**
* Set title fade out time
*
* @param time
* Time
*/
public void setFadeOutTime(final int time)
{
public void setFadeOutTime(final int time) {
fadeOutTime = time;
}
/**
* Set title stay time
*
* @param time
* Time
*/
public void setStayTime(final int time)
{
public void setStayTime(final int time) {
stayTime = time;
}
/**
* Set timings to ticks
*/
public void setTimingsToTicks()
{
public void setTimingsToTicks() {
ticks = true;
}
/**
* Set timings to seconds
*/
public void setTimingsToSeconds()
{
public void setTimingsToSeconds() {
ticks = false;
}
/**
* Send the title to a player
*
* @param player
* Player
*/
public void send(final Player player) throws Exception
{
if ((getProtocolVersion(player) >= 47) && isSpigot() && (packetTitle != null))
{
public void send(final Player player) throws Exception {
if ((getProtocolVersion(player) >= 47) && isSpigot() && (packetTitle != null)) {
// First reset previous settings
resetTitle(player);
// Send timings first
@ -252,11 +233,10 @@ public class HackTitleManager
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object[] actions = packetActions.getEnumConstants();
final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = packetTitle.getConstructor(packetActions, Integer.TYPE, Integer.TYPE, Integer.TYPE).newInstance(actions[2], fadeInTime * (ticks ? 1 : 20),
stayTime * (ticks ? 1 : 20), fadeOutTime * (ticks ? 1 : 20));
Object packet = packetTitle.getConstructor(packetActions, Integer.TYPE, Integer.TYPE, Integer.TYPE).newInstance(actions[2], fadeInTime * (ticks ? 1 : 20), stayTime * (ticks ? 1 : 20),
fadeOutTime * (ticks ? 1 : 20));
// Send if set
if ((fadeInTime != -1) && (fadeOutTime != -1) && (stayTime != -1))
{
if ((fadeInTime != -1) && (fadeOutTime != -1) && (stayTime != -1)) {
sendPacket.invoke(connection, packet);
}
// Send title
@ -264,8 +244,7 @@ public class HackTitleManager
"{text:\"" + ChatColor.translateAlternateColorCodes('&', title) + "\",color:" + titleColor.name().toLowerCase() + "}");
packet = packetTitle.getConstructor(packetActions, getNMSClass("IChatBaseComponent")).newInstance(actions[0], serialized);
sendPacket.invoke(connection, packet);
if (subtitle != "")
{
if (subtitle != "") {
// Send subtitle if present
serialized = getMethod(nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', subtitle) + "\",color:" + subtitleColor.name().toLowerCase() + "}");
@ -274,18 +253,16 @@ public class HackTitleManager
}
}
}
/**
* Broadcast the title to all players
*/
public void broadcast() throws Exception
{
for (final Player p : Bukkit.getOnlinePlayers())
{
public void broadcast() throws Exception {
for (final Player p : Bukkit.getOnlinePlayers()) {
send(p);
}
}
/**
* Clear the title
*
@ -293,10 +270,8 @@ public class HackTitleManager
* Player
* @throws Exception
*/
public void clearTitle(final Player player) throws Exception
{
if ((getProtocolVersion(player) >= 47) && isSpigot())
{
public void clearTitle(final Player player) throws Exception {
if ((getProtocolVersion(player) >= 47) && isSpigot()) {
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
@ -306,7 +281,7 @@ public class HackTitleManager
sendPacket.invoke(connection, packet);
}
}
/**
* Reset the title settings
*
@ -314,10 +289,8 @@ public class HackTitleManager
* Player
* @throws Exception
*/
public void resetTitle(final Player player) throws Exception
{
if ((getProtocolVersion(player) >= 47) && isSpigot())
{
public void resetTitle(final Player player) throws Exception {
if ((getProtocolVersion(player) >= 47) && isSpigot()) {
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
@ -327,7 +300,7 @@ public class HackTitleManager
sendPacket.invoke(connection, packet);
}
}
/**
* Get the protocol version of the player
*
@ -336,25 +309,23 @@ public class HackTitleManager
* @return Protocol version
* @throws Exception
*/
private int getProtocolVersion(final Player player) throws Exception
{
private int getProtocolVersion(final Player player) throws Exception {
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object networkManager = getValue("networkManager", connection);
final Integer version = (Integer) getMethod("getVersion", networkManager.getClass()).invoke(networkManager);
return version;
}
/**
* Check if running spigot
*
* @return Spigot
*/
private boolean isSpigot()
{
private boolean isSpigot() {
return Bukkit.getVersion().contains("Spigot");
}
/**
* Get class by url
*
@ -362,130 +333,109 @@ public class HackTitleManager
* Namespace url
* @return Class
*/
private Class<?> getClass(final String namespace)
{
try
{
private Class<?> getClass(final String namespace) {
try {
return Class.forName(namespace);
}
catch (final Exception e)
{}
} catch (final Exception e) {}
return null;
}
private Field getField(final String name, final Class<?> clazz) throws Exception
{
private Field getField(final String name, final Class<?> clazz) throws Exception {
return clazz.getDeclaredField(name);
}
private Object getValue(final String name, final Object obj) throws Exception
{
private Object getValue(final String name, final Object obj) throws Exception {
final Field f = getField(name, obj.getClass());
f.setAccessible(true);
return f.get(obj);
}
private Class<?> getPrimitiveType(final Class<?> clazz)
{
private Class<?> getPrimitiveType(final Class<?> clazz) {
return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz;
}
private Class<?>[] toPrimitiveTypeArray(final Class<?>[] classes)
{
private Class<?>[] toPrimitiveTypeArray(final Class<?>[] classes) {
final int a = classes != null ? classes.length : 0;
final Class<?>[] types = new Class<?>[a];
for (int i = 0; i < a; i++)
{
for (int i = 0; i < a; i++) {
types[i] = getPrimitiveType(classes[i]);
}
return types;
}
private static boolean equalsTypeArray(final Class<?>[] a, final 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; }
private static boolean equalsTypeArray(final Class<?>[] a, final 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(final Object obj)
{
try
{
private Object getHandle(final Object obj) {
try {
return getMethod("getHandle", obj.getClass()).invoke(obj);
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
return null;
}
}
private Method getMethod(final String name, final Class<?> clazz, final Class<?>... paramTypes)
{
private Method getMethod(final String name, final Class<?> clazz, final Class<?>... paramTypes) {
final Class<?>[] t = toPrimitiveTypeArray(paramTypes);
for (final Method m : clazz.getMethods())
{
for (final Method m : clazz.getMethods()) {
final Class<?>[] types = toPrimitiveTypeArray(m.getParameterTypes());
if (m.getName().equals(name) && equalsTypeArray(types, t)) { return m; }
if (m.getName().equals(name) && equalsTypeArray(types, t)) {
return m;
}
}
return null;
}
private String getVersion()
{
private String getVersion() {
final String name = Bukkit.getServer().getClass().getPackage().getName();
final String version = name.substring(name.lastIndexOf('.') + 1) + ".";
return version;
}
private Class<?> getNMSClass(final String className) throws ClassNotFoundException
{
private Class<?> getNMSClass(final String className) throws ClassNotFoundException {
final String fullName = "net.minecraft.server." + getVersion() + className;
Class<?> clazz = null;
clazz = Class.forName(fullName);
return clazz;
}
private Field getField(final Class<?> clazz, final String name)
{
try
{
private Field getField(final Class<?> clazz, final String name) {
try {
final Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field;
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
return null;
}
}
private Method getMethod(final Class<?> clazz, final String name, final Class<?>... args)
{
for (final Method m : clazz.getMethods())
{
if (m.getName().equals(name) && ((args.length == 0) || ClassListEqual(args, m.getParameterTypes())))
{
private Method getMethod(final Class<?> clazz, final String name, final Class<?>... args) {
for (final Method m : clazz.getMethods()) {
if (m.getName().equals(name) && ((args.length == 0) || ClassListEqual(args, m.getParameterTypes()))) {
m.setAccessible(true);
return m;
}
}
return null;
}
private boolean ClassListEqual(final Class<?>[] l1, final Class<?>[] l2)
{
private boolean ClassListEqual(final Class<?>[] l1, final Class<?>[] l2) {
boolean equal = true;
if (l1.length != l2.length) { return false; }
for (int i = 0; i < l1.length; i++)
{
if (l1[i] != l2[i])
{
if (l1.length != l2.length) {
return false;
}
for (int i = 0; i < l1.length; i++) {
if (l1[i] != l2[i]) {
equal = false;
break;
}

View File

@ -13,61 +13,49 @@ import com.intellectualcrafters.plot.util.ChatManager;
import com.plotsquared.bukkit.chat.FancyMessage;
import com.plotsquared.bukkit.object.BukkitPlayer;
public class BukkitChatManager extends ChatManager<FancyMessage>
{
public class BukkitChatManager extends ChatManager<FancyMessage> {
@Override
public FancyMessage builder()
{
public FancyMessage builder() {
return new FancyMessage("");
}
@Override
public void color(final PlotMessage m, final String color)
{
public void color(final PlotMessage m, final String color) {
m.$(this).color(ChatColor.getByChar(C.color(color).substring(1)));
}
@Override
public void tooltip(final PlotMessage m, final PlotMessage... tooltips)
{
public void tooltip(final PlotMessage m, final PlotMessage... tooltips) {
final List<FancyMessage> lines = new ArrayList<>();
for (final PlotMessage tooltip : tooltips)
{
for (final PlotMessage tooltip : tooltips) {
lines.add(tooltip.$(this));
}
m.$(this).formattedTooltip(lines);
}
@Override
public void command(final PlotMessage m, final String command)
{
public void command(final PlotMessage m, final String command) {
m.$(this).command(command);
}
@Override
public void text(final PlotMessage m, final String text)
{
public void text(final PlotMessage m, final String text) {
m.$(this).then(ChatColor.stripColor(text));
}
@Override
public void send(final PlotMessage m, final PlotPlayer player)
{
if (ConsolePlayer.isConsole(player))
{
public void send(final PlotMessage m, final PlotPlayer player) {
if (ConsolePlayer.isConsole(player)) {
player.sendMessage(m.$(this).toOldMessageFormat());
}
else
{
} else {
m.$(this).send(((BukkitPlayer) player).player);
}
}
@Override
public void suggest(final PlotMessage m, final String command)
{
public void suggest(final PlotMessage m, final String command) {
m.$(this).suggest(command);
}
}

View File

@ -23,54 +23,51 @@ import com.plotsquared.general.commands.Command;
* Created 2015-02-20 for PlotSquared
*
*/
public class BukkitCommand implements CommandExecutor, TabCompleter
{
public BukkitCommand()
*/
public class BukkitCommand implements CommandExecutor, TabCompleter {
public BukkitCommand() {
MainCommand.getInstance().addCommand(new DebugUUID());
}
}
@Override
public boolean onCommand(final CommandSender commandSender, final org.bukkit.command.Command command, final String commandLabel, final String[] args)
{
@Override
public boolean onCommand(final CommandSender commandSender, final org.bukkit.command.Command command, final String commandLabel, final String[] args) {
if (commandSender instanceof Player) {
return MainCommand.onCommand(BukkitUtil.getPlayer((Player) commandSender), commandLabel, args);
}
return MainCommand.onCommand(ConsolePlayer.getConsole(), commandLabel, args);
}
}
@Override
public List<String> onTabComplete(final CommandSender commandSender, final org.bukkit.command.Command command, final String s, final String[] strings)
{
if (!(commandSender instanceof Player)) { return null; }
final PlotPlayer player = BukkitUtil.getPlayer((Player) commandSender);
if (strings.length < 1)
{
@Override
public List<String> onTabComplete(final CommandSender commandSender, final org.bukkit.command.Command command, final String s, final String[] strings) {
if (!(commandSender instanceof Player)) {
return null;
}
final PlotPlayer player = BukkitUtil.getPlayer((Player) commandSender);
if (strings.length < 1) {
if ((strings.length == 0) || "plots".startsWith(s)) {
return Collections.singletonList("plots");
}
}
if (strings.length > 1) {
return null;
}
if (!command.getLabel().equalsIgnoreCase("plots")) {
return null;
}
if (strings.length > 1) { return null; }
}
final Set<String> tabOptions = new HashSet<>();
final ArrayList<Command<PlotPlayer>> commands = MainCommand.getInstance().getCommands();
final String best = new StringComparison(strings[0], commands).getBestMatch();
tabOptions.add(best);
final String arg = strings[0].toLowerCase();
for (final Command<PlotPlayer> cmd : MainCommand.getInstance().getCommands())
final String arg = strings[0].toLowerCase();
for (final Command<PlotPlayer> cmd : MainCommand.getInstance().getCommands()) {
final String label = cmd.getCommand();
if (!label.equalsIgnoreCase(best))
{
if (label.startsWith(arg))
{
if (Permissions.hasPermission(player, cmd.getPermission()))
final String label = cmd.getCommand();
if (!label.equalsIgnoreCase(best)) {
if (label.startsWith(arg)) {
if (Permissions.hasPermission(player, cmd.getPermission())) {
tabOptions.add(cmd.getCommand());
}
else if (cmd.getAliases().size() > 0)
{
for (final String alias : cmd.getAliases())
{
if (alias.startsWith(arg))
tabOptions.add(cmd.getCommand());
} else if (cmd.getAliases().size() > 0) {
for (final String alias : cmd.getAliases()) {
if (alias.startsWith(arg)) {
tabOptions.add(label);
break;
@ -79,7 +76,9 @@ public class BukkitCommand implements CommandExecutor, TabCompleter
}
}
}
}
}
if (tabOptions.size() > 0) {
return new ArrayList<>(tabOptions);
}
return null;
}

View File

@ -11,96 +11,80 @@ import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.EconHandler;
import com.plotsquared.bukkit.object.BukkitOfflinePlayer;
public class BukkitEconHandler extends EconHandler
{
public class BukkitEconHandler extends EconHandler {
private Economy econ;
private Permission perms;
public Economy getEconomy()
{
public Economy getEconomy() {
init();
return econ;
}
public Permission getPermissions()
{
public Permission getPermissions() {
init();
return perms;
}
public boolean init()
{
if ((econ == null) || (perms == null))
{
public boolean init() {
if ((econ == null) || (perms == null)) {
setupPermissions();
setupEconomy();
}
return (econ != null) && (perms != null);
}
private boolean setupPermissions()
{
private boolean setupPermissions() {
final RegisteredServiceProvider<Permission> permissionProvider = Bukkit.getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class);
if (permissionProvider != null)
{
if (permissionProvider != null) {
perms = permissionProvider.getProvider();
}
return (perms != null);
}
private boolean setupEconomy()
{
private boolean setupEconomy() {
final RegisteredServiceProvider<Economy> economyProvider = Bukkit.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
if (economyProvider != null)
{
if (economyProvider != null) {
econ = economyProvider.getProvider();
}
return (econ != null);
}
@Override
public double getMoney(final PlotPlayer player)
{
public double getMoney(final PlotPlayer player) {
final double bal = super.getMoney(player);
if (Double.isNaN(bal)) { return econ.getBalance(player.getName()); }
if (Double.isNaN(bal)) {
return econ.getBalance(player.getName());
}
return bal;
}
@Override
public void withdrawMoney(final PlotPlayer player, final double amount)
{
public void withdrawMoney(final PlotPlayer player, final double amount) {
econ.withdrawPlayer(player.getName(), amount);
}
@Override
public void depositMoney(final PlotPlayer player, final double amount)
{
public void depositMoney(final PlotPlayer player, final double amount) {
econ.depositPlayer(player.getName(), amount);
}
@Override
public void depositMoney(final OfflinePlotPlayer player, final double amount)
{
public void depositMoney(final OfflinePlotPlayer player, final double amount) {
econ.depositPlayer(((BukkitOfflinePlayer) player).player, amount);
}
@Override
public void setPermission(final String world, final String player, final String perm, final boolean value)
{
if (value)
{
public void setPermission(final String world, final String player, final String perm, final boolean value) {
if (value) {
perms.playerAdd(world, player, perm);
}
else
{
} else {
perms.playerRemove(world, player, perm);
}
}
@Override
public boolean hasPermission(final String world, final String player, final String perm)
{
public boolean hasPermission(final String world, final String player, final String perm) {
return perms.playerHas(world, Bukkit.getOfflinePlayer(player), perm);
}
}

View File

@ -33,112 +33,98 @@ import com.plotsquared.bukkit.events.PlotRateEvent;
import com.plotsquared.bukkit.events.PlotUnlinkEvent;
import com.plotsquared.bukkit.object.BukkitPlayer;
public class BukkitEventUtil extends EventUtil
{
public Player getPlayer(final PlotPlayer player)
{
if (player instanceof BukkitPlayer) { return ((BukkitPlayer) player).player; }
public class BukkitEventUtil extends EventUtil {
public Player getPlayer(final PlotPlayer player) {
if (player instanceof BukkitPlayer) {
return ((BukkitPlayer) player).player;
}
return null;
}
public boolean callEvent(final Event event)
{
public boolean callEvent(final Event event) {
Bukkit.getServer().getPluginManager().callEvent(event);
if (event instanceof Cancellable) { return !((Cancellable) event).isCancelled(); }
if (event instanceof Cancellable) {
return !((Cancellable) event).isCancelled();
}
return true;
}
@Override
public boolean callClaim(final PlotPlayer player, final Plot plot, final boolean auto)
{
public boolean callClaim(final PlotPlayer player, final Plot plot, final boolean auto) {
return callEvent(new PlayerClaimPlotEvent(getPlayer(player), plot, auto));
}
@Override
public boolean callTeleport(final PlotPlayer player, final Location from, final Plot plot)
{
public boolean callTeleport(final PlotPlayer player, final Location from, final Plot plot) {
return callEvent(new PlayerTeleportToPlotEvent(getPlayer(player), from, plot));
}
@Override
public boolean callClear(final String world, final PlotId id)
{
public boolean callClear(final String world, final PlotId id) {
return callEvent(new PlotClearEvent(world, id));
}
@Override
public void callDelete(final String world, final PlotId id)
{
public void callDelete(final String world, final PlotId id) {
callEvent(new PlotDeleteEvent(world, id));
}
@Override
public boolean callFlagAdd(final Flag flag, final Plot plot)
{
public boolean callFlagAdd(final Flag flag, final Plot plot) {
return callEvent(new PlotFlagAddEvent(flag, plot));
}
@Override
public boolean callFlagRemove(final Flag flag, final Plot plot)
{
public boolean callFlagRemove(final Flag flag, final Plot plot) {
return callEvent(new PlotFlagRemoveEvent(flag, plot));
}
@Override
public boolean callMerge(final String world, final Plot plot, final ArrayList<PlotId> plots)
{
public boolean callMerge(final String world, final Plot plot, final ArrayList<PlotId> plots) {
return callEvent(new PlotMergeEvent(BukkitUtil.getWorld(world), plot, plots));
}
@Override
public boolean callUnlink(final String world, final ArrayList<PlotId> plots)
{
public boolean callUnlink(final String world, final ArrayList<PlotId> plots) {
return callEvent(new PlotUnlinkEvent(BukkitUtil.getWorld(world), plots));
}
@Override
public void callEntry(final PlotPlayer player, final Plot plot)
{
public void callEntry(final PlotPlayer player, final Plot plot) {
callEvent(new PlayerEnterPlotEvent(getPlayer(player), plot));
}
@Override
public void callLeave(final PlotPlayer player, final Plot plot)
{
public void callLeave(final PlotPlayer player, final Plot plot) {
callEvent(new PlayerLeavePlotEvent(getPlayer(player), plot));
}
@Override
public void callDenied(final PlotPlayer initiator, final Plot plot, final UUID player, final boolean added)
{
public void callDenied(final PlotPlayer initiator, final Plot plot, final UUID player, final boolean added) {
callEvent(new PlayerPlotDeniedEvent(getPlayer(initiator), plot, player, added));
}
@Override
public void callTrusted(final PlotPlayer initiator, final Plot plot, final UUID player, final boolean added)
{
public void callTrusted(final PlotPlayer initiator, final Plot plot, final UUID player, final boolean added) {
callEvent(new PlayerPlotHelperEvent(getPlayer(initiator), plot, player, added));
}
@Override
public void callMember(final PlotPlayer initiator, final Plot plot, final UUID player, final boolean added)
{
public void callMember(final PlotPlayer initiator, final Plot plot, final UUID player, final boolean added) {
callEvent(new PlayerPlotTrustedEvent(getPlayer(initiator), plot, player, added));
}
@Override
public boolean callFlagRemove(final Flag flag, final PlotCluster cluster)
{
public boolean callFlagRemove(final Flag flag, final PlotCluster cluster) {
return callEvent(new ClusterFlagRemoveEvent(flag, cluster));
}
@Override
public Rating callRating(final PlotPlayer player, final Plot plot, final Rating rating)
{
public Rating callRating(final PlotPlayer player, final Plot plot, final Rating rating) {
final PlotRateEvent event = new PlotRateEvent(player, rating, plot);
Bukkit.getServer().getPluginManager().callEvent(event);
return event.getRating();
}
}

View File

@ -28,12 +28,10 @@ import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.TaskManager;
public class BukkitHybridUtils extends HybridUtils
{
public class BukkitHybridUtils extends HybridUtils {
@Override
public void analyzePlot(final Plot plot, final RunnableVal<PlotAnalysis> whenDone)
{
public void analyzePlot(final Plot plot, final RunnableVal<PlotAnalysis> whenDone) {
// int diff, int variety, int verticies, int rotation, int height_sd
/*
* diff: compare to base by looping through all blocks
@ -46,25 +44,20 @@ public class BukkitHybridUtils extends HybridUtils
* - recheck each block
*
*/
TaskManager.runTaskAsync(new Runnable()
{
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run()
{
public void run() {
final World world = Bukkit.getWorld(plot.world);
final ChunkGenerator gen = world.getGenerator();
if (gen == null) {
return;
}
final BiomeGrid base = new BiomeGrid()
{
final BiomeGrid base = new BiomeGrid() {
@Override
public void setBiome(final int a, final int b, final Biome c)
{}
public void setBiome(final int a, final int b, final Biome c) {}
@Override
public Biome getBiome(final int a, final int b)
{
public Biome getBiome(final int a, final int b) {
return null;
}
};
@ -82,42 +75,33 @@ public class BukkitHybridUtils extends HybridUtils
MainUtil.initCache();
final int width = (tx - bx) + 1;
final int length = (tz - bz) + 1;
System.gc();
System.gc();
final short[][][] oldblocks = new short[256][width][length];
final short[][][] newblocks = new short[256][width][length];
final Runnable run = new Runnable()
{
final Runnable run = new Runnable() {
@Override
public void run()
{
ChunkManager.chunkTask(bot, top, new RunnableVal<int[]>()
{
public void run() {
ChunkManager.chunkTask(bot, top, new RunnableVal<int[]>() {
@Override
public void run()
{
public void run() {
// TODO [chunkx, chunkz, pos1x, pos1z, pos2x, pos2z, isedge]
final int X = value[0];
final int Z = value[1];
final short[][] result = gen.generateExtBlockSections(world, r, X, Z, base);
final int xb = ((X) << 4) - bx;
final int zb = ((Z) << 4) - bz;
for (int i = 0; i < result.length; i++)
{
if (result[i] == null)
{
for (int j = 0; j < 4096; j++)
{
for (int i = 0; i < result.length; i++) {
if (result[i] == null) {
for (int j = 0; j < 4096; j++) {
final int x = MainUtil.x_loc[i][j] + xb;
if ((x < 0) || (x >= width))
{
if ((x < 0) || (x >= width)) {
continue;
}
final int z = MainUtil.z_loc[i][j] + zb;
if ((z < 0) || (z >= length))
{
if ((z < 0) || (z >= length)) {
continue;
}
final int y = MainUtil.y_loc[i][j];
@ -125,34 +109,27 @@ public class BukkitHybridUtils extends HybridUtils
}
continue;
}
for (int j = 0; j < result[i].length; j++)
{
for (int j = 0; j < result[i].length; j++) {
final int x = MainUtil.x_loc[i][j] + xb;
if ((x < 0) || (x >= width))
{
if ((x < 0) || (x >= width)) {
continue;
}
final int z = MainUtil.z_loc[i][j] + zb;
if ((z < 0) || (z >= length))
{
if ((z < 0) || (z >= length)) {
continue;
}
final int y = MainUtil.y_loc[i][j];
oldblocks[y][x][z] = result[i][j];
}
}
}
}, new Runnable()
{
}, new Runnable() {
@Override
public void run()
{
TaskManager.runTaskAsync(new Runnable()
{
public void run() {
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run()
{
public void run() {
final int size = width * length;
final int[] changes = new int[size];
final int[] faces = new int[size];
@ -160,63 +137,46 @@ public class BukkitHybridUtils extends HybridUtils
final int[] air = new int[size];
final int[] variety = new int[size];
int i = 0;
for (int x = 0; x < width; x++)
{
for (int z = 0; z < length; z++)
{
for (int x = 0; x < width; x++) {
for (int z = 0; z < length; z++) {
final HashSet<Short> types = new HashSet<>();
for (int y = 0; y < 256; y++)
{
for (int y = 0; y < 256; y++) {
final short old = oldblocks[y][x][z];
final short now = newblocks[y][x][z];
if (old != now)
{
if (old != now) {
changes[i]++;
}
if (now == 0)
{
if (now == 0) {
air[i]++;
}
else
{
} else {
// check verticies
// modifications_adjacent
if ((x > 0) && (z > 0) && (y > 0) && (x < (width - 1)) && (z < (length - 1)) && (y < 255))
{
if (newblocks[y - 1][x][z] == 0)
{
if ((x > 0) && (z > 0) && (y > 0) && (x < (width - 1)) && (z < (length - 1)) && (y < 255)) {
if (newblocks[y - 1][x][z] == 0) {
faces[i]++;
}
if (newblocks[y][x - 1][z] == 0)
{
if (newblocks[y][x - 1][z] == 0) {
faces[i]++;
}
if (newblocks[y][x][z - 1] == 0)
{
if (newblocks[y][x][z - 1] == 0) {
faces[i]++;
}
if (newblocks[y + 1][x][z] == 0)
{
if (newblocks[y + 1][x][z] == 0) {
faces[i]++;
}
if (newblocks[y][x + 1][z] == 0)
{
if (newblocks[y][x + 1][z] == 0) {
faces[i]++;
}
if (newblocks[y][x][z + 1] == 0)
{
if (newblocks[y][x][z + 1] == 0) {
faces[i]++;
}
}
final Material material = Material.getMaterial(now);
final Class<? extends MaterialData> md = material.getData();
if (md.equals(Directional.class))
{
if (md.equals(Directional.class)) {
data[i] += 8;
}
else if (!md.equals(MaterialData.class))
{
} else if (!md.equals(MaterialData.class)) {
data[i]++;
}
types.add(now);
@ -228,7 +188,7 @@ public class BukkitHybridUtils extends HybridUtils
}
// analyze plot
// put in analysis obj
// run whenDone
final PlotAnalysis analysis = new PlotAnalysis();
analysis.changes = (int) (MathMan.getMean(changes) * 100);
@ -236,20 +196,20 @@ public class BukkitHybridUtils extends HybridUtils
analysis.data = (int) (MathMan.getMean(data) * 100);
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.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));
final List<Integer> result = new ArrayList<>();
result.add(analysis.changes);
result.add(analysis.faces);
result.add(analysis.data);
result.add(analysis.air);
result.add(analysis.variety);
result.add(analysis.changes_sd);
result.add(analysis.faces_sd);
result.add(analysis.data_sd);
@ -265,17 +225,15 @@ public class BukkitHybridUtils extends HybridUtils
});
}
}, 5);
}
};
System.gc();
MainUtil.initCache();
ChunkManager.chunkTask(bot, top, new RunnableVal<int[]>()
{
ChunkManager.chunkTask(bot, top, new RunnableVal<int[]>() {
@Override
public void run()
{
public void run() {
final int X = value[0];
final int Z = value[1];
world.loadChunk(X, Z);
@ -283,52 +241,37 @@ public class BukkitHybridUtils extends HybridUtils
int minZ;
int maxX;
int maxZ;
if (X == cbx)
{
if (X == cbx) {
minX = bx & 15;
}
else
{
} else {
minX = 0;
}
if (Z == cbz)
{
if (Z == cbz) {
minZ = bz & 15;
}
else
{
} else {
minZ = 0;
}
if (X == ctx)
{
if (X == ctx) {
maxX = tx & 15;
}
else
{
} else {
maxX = 16;
}
if (Z == ctz)
{
if (Z == ctz) {
maxZ = tz & 15;
}
else
{
} else {
maxZ = 16;
}
final int cbx = X << 4;
final int cbz = Z << 4;
final int xb = (cbx) - bx;
final int zb = (cbz) - bz;
for (int x = minX; x <= maxX; x++)
{
for (int x = minX; x <= maxX; x++) {
final int xx = cbx + x;
for (int z = minZ; z <= maxZ; z++)
{
for (int z = minZ; z <= maxZ; z++) {
final int zz = cbz + z;
for (int y = 0; y < 256; y++)
{
for (int y = 0; y < 256; y++) {
final Block block = world.getBlockAt(xx, y, zz);
final int xr = xb + x;
final int zr = zb + z;
@ -338,42 +281,33 @@ public class BukkitHybridUtils extends HybridUtils
}
world.unloadChunkRequest(X, Z, true);
}
}, new Runnable()
{
}, new Runnable() {
@Override
public void run()
{
public void run() {
TaskManager.runTaskAsync(run);
}
}, 5);
}
});
}
@Override
public int checkModified(final String worldname, final int x1, final int x2, final int y1, final int y2, final int z1, final int z2, final PlotBlock[] blocks)
{
public int checkModified(final String worldname, final int x1, final int x2, final int y1, final int y2, final int z1, final int z2, final PlotBlock[] blocks) {
final World world = BukkitUtil.getWorld(worldname);
int count = 0;
for (int y = y1; y <= y2; y++)
{
for (int x = x1; x <= x2; x++)
{
for (int z = z1; z <= z2; z++)
{
for (int y = y1; y <= y2; y++) {
for (int x = x1; x <= x2; x++) {
for (int z = z1; z <= z2; z++) {
final Block block = world.getBlockAt(x, y, z);
final int id = block.getTypeId();
boolean same = false;
for (final PlotBlock p : blocks)
{
if (id == p.id)
{
for (final PlotBlock p : blocks) {
if (id == p.id) {
same = true;
break;
}
}
if (!same)
{
if (!same) {
count++;
}
}
@ -381,24 +315,18 @@ public class BukkitHybridUtils extends HybridUtils
}
return count;
}
@Override
public int get_ey(final String worldname, final int sx, final int ex, final int sz, final int ez, final int sy)
{
public int get_ey(final String worldname, final int sx, final int ex, final int sz, final int ez, final int sy) {
final World world = BukkitUtil.getWorld(worldname);
final int maxY = world.getMaxHeight();
int ey = sy;
for (int x = sx; x <= ex; x++)
{
for (int z = sz; z <= ez; z++)
{
for (int y = sy; y < maxY; y++)
{
if (y > ey)
{
for (int x = sx; x <= ex; x++) {
for (int z = sz; z <= ez; z++) {
for (int y = sy; y < maxY; y++) {
if (y > ey) {
final Block block = world.getBlockAt(x, y, z);
if (block.getTypeId() != 0)
{
if (block.getTypeId() != 0) {
ey = y;
}
}

View File

@ -18,117 +18,108 @@ import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.InventoryUtil;
import com.plotsquared.bukkit.object.BukkitPlayer;
public class BukkitInventoryUtil extends InventoryUtil
{
public class BukkitInventoryUtil extends InventoryUtil {
@Override
public void open(final PlotInventory inv)
{
public void open(final PlotInventory inv) {
final BukkitPlayer bp = ((BukkitPlayer) inv.player);
final Inventory inventory = Bukkit.createInventory(null, inv.size * 9, inv.getTitle());
final PlotItemStack[] items = inv.getItems();
for (int i = 0; i < (inv.size * 9); i++)
{
for (int i = 0; i < (inv.size * 9); i++) {
final PlotItemStack item = items[i];
if (item != null)
{
if (item != null) {
inventory.setItem(i, getItem(item));
}
}
inv.player.setMeta("inventory", inv);
bp.player.openInventory(inventory);
}
@Override
public void close(final PlotInventory inv)
{
if (!inv.isOpen()) { return; }
public void close(final PlotInventory inv) {
if (!inv.isOpen()) {
return;
}
inv.player.deleteMeta("inventory");
final BukkitPlayer bp = ((BukkitPlayer) inv.player);
bp.player.closeInventory();
}
@Override
public void setItem(final PlotInventory inv, final int index, final PlotItemStack item)
{
public void setItem(final PlotInventory inv, final int index, final PlotItemStack item) {
final BukkitPlayer bp = ((BukkitPlayer) inv.player);
final InventoryView opened = bp.player.getOpenInventory();
if (!inv.isOpen()) { return; }
if (!inv.isOpen()) {
return;
}
opened.setItem(index, getItem(item));
bp.player.updateInventory();
}
public PlotItemStack getItem(final ItemStack item)
{
if (item == null) { return null; }
public PlotItemStack getItem(final ItemStack item) {
if (item == null) {
return null;
}
final int id = item.getTypeId();
final short data = item.getDurability();
final int amount = item.getAmount();
String name = null;
String[] lore = null;
if (item.hasItemMeta())
{
if (item.hasItemMeta()) {
final ItemMeta meta = item.getItemMeta();
if (meta.hasDisplayName())
{
if (meta.hasDisplayName()) {
name = meta.getDisplayName();
}
if (meta.hasLore())
{
if (meta.hasLore()) {
final List<String> itemLore = meta.getLore();
lore = itemLore.toArray(new String[itemLore.size()]);
}
}
return new PlotItemStack(id, data, amount, name, lore);
}
public static ItemStack getItem(final PlotItemStack item)
{
if (item == null) { return null; }
public static ItemStack getItem(final PlotItemStack item) {
if (item == null) {
return null;
}
final ItemStack stack = new ItemStack(item.id, item.amount, item.data);
ItemMeta meta = null;
if (item.name != null)
{
if (item.name != null) {
meta = stack.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', item.name));
}
if (item.lore != null)
{
if (meta == null)
{
if (item.lore != null) {
if (meta == null) {
meta = stack.getItemMeta();
}
final List<String> lore = new ArrayList<>();
for (final String entry : item.lore)
{
for (final String entry : item.lore) {
lore.add(ChatColor.translateAlternateColorCodes('&', entry));
}
meta.setLore(lore);
}
if (meta != null)
{
if (meta != null) {
stack.setItemMeta(meta);
}
return stack;
}
@Override
public PlotItemStack[] getItems(final PlotPlayer player)
{
public PlotItemStack[] getItems(final PlotPlayer player) {
final BukkitPlayer bp = ((BukkitPlayer) player);
final PlayerInventory inv = bp.player.getInventory();
final PlotItemStack[] items = new PlotItemStack[36];
for (int i = 0; i < 36; i++)
{
for (int i = 0; i < 36; i++) {
items[i] = getItem(inv.getItem(i));
}
return items;
}
@Override
public boolean isOpen(final PlotInventory inv)
{
if (!inv.isOpen()) { return false; }
public boolean isOpen(final PlotInventory inv) {
if (!inv.isOpen()) {
return false;
}
final BukkitPlayer bp = ((BukkitPlayer) inv.player);
final InventoryView opened = bp.player.getOpenInventory();
return (inv.isOpen() && (opened.getType() == InventoryType.CRAFTING) && (opened.getTitle() == null));

View File

@ -9,49 +9,40 @@ import com.intellectualcrafters.plot.object.PlotMessage;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.ChatManager;
public class BukkitPlainChatManager extends ChatManager<List<StringBuilder>>
{
public class BukkitPlainChatManager extends ChatManager<List<StringBuilder>> {
@Override
public List<StringBuilder> builder()
{
public List<StringBuilder> builder() {
return new ArrayList<StringBuilder>();
}
@Override
public void color(final PlotMessage m, final String color)
{
public void color(final PlotMessage m, final String color) {
final List<StringBuilder> parts = m.$(this);
parts.get(parts.size() - 1).insert(0, color);
}
@Override
public void tooltip(final PlotMessage m, final PlotMessage... tooltips)
{}
public void tooltip(final PlotMessage m, final PlotMessage... tooltips) {}
@Override
public void command(final PlotMessage m, final String command)
{}
public void command(final PlotMessage m, final String command) {}
@Override
public void text(final PlotMessage m, final String text)
{
public void text(final PlotMessage m, final String text) {
m.$(this).add(new StringBuilder(ChatColor.stripColor(text)));
}
@Override
public void send(final PlotMessage m, final PlotPlayer player)
{
public void send(final PlotMessage m, final PlotPlayer player) {
final StringBuilder built = new StringBuilder();
for (final StringBuilder sb : m.$(this))
{
for (final StringBuilder sb : m.$(this)) {
built.append(sb);
}
player.sendMessage(built.toString());
}
@Override
public void suggest(final PlotMessage m, final String command)
{}
public void suggest(final PlotMessage m, final String command) {}
}

View File

@ -37,14 +37,13 @@ import com.intellectualcrafters.plot.util.UUIDHandler;
/**
* Functions involving players, plots and locations.
*/
public class BukkitPlayerFunctions
{
public class BukkitPlayerFunctions {
/*
* =========== NOTICE ================
* - We will try to move as many functions as we can out of this class and into the MainUtil class
*/
/**
* Clear a plot. Use null player if no player is present
* @param player
@ -52,67 +51,59 @@ public class BukkitPlayerFunctions
* @param plot
* @param isDelete
*/
public static void clear(final Player player, final String world, final Plot plot, final boolean isDelete)
{
public static void clear(final Player player, final String world, final Plot plot, final boolean isDelete) {
final long start = System.currentTimeMillis();
final Runnable whenDone = new Runnable()
{
final Runnable whenDone = new Runnable() {
@Override
public void run()
{
if ((player != null) && player.isOnline())
{
public void run() {
if ((player != null) && player.isOnline()) {
MainUtil.sendMessage(BukkitUtil.getPlayer(player), C.CLEARING_DONE, "" + (System.currentTimeMillis() - start));
}
}
};
if (!MainUtil.clearAsPlayer(plot, isDelete, whenDone))
{
if (!MainUtil.clearAsPlayer(plot, isDelete, whenDone)) {
MainUtil.sendMessage(null, C.WAIT_FOR_TIMER);
}
}
public static String getPlayerName(final UUID uuid)
{
if (uuid == null) { return "unknown"; }
public static String getPlayerName(final UUID uuid) {
if (uuid == null) {
return "unknown";
}
final String name = UUIDHandler.getName(uuid);
if (name == null) { return "unknown"; }
if (name == null) {
return "unknown";
}
return name;
}
/**
* @param player player
*
* @return boolean
*/
public static boolean isInPlot(final Player player)
{
public static boolean isInPlot(final Player player) {
return getCurrentPlot(player) != null;
}
public static ArrayList<PlotId> getMaxPlotSelectionIds(final String world, PlotId pos1, PlotId pos2)
{
public static ArrayList<PlotId> getMaxPlotSelectionIds(final String world, PlotId pos1, PlotId pos2) {
final Plot plot1 = PS.get().getPlot(world, pos1);
final Plot plot2 = PS.get().getPlot(world, pos2);
if (plot1 != null)
{
if (plot1 != null) {
pos1 = MainUtil.getBottomPlot(plot1).id;
}
if (plot2 != null)
{
if (plot2 != null) {
pos2 = MainUtil.getTopPlot(plot2).id;
}
final ArrayList<PlotId> myplots = new ArrayList<>();
for (int x = pos1.x; x <= pos2.x; x++)
{
for (int y = pos1.y; y <= pos2.y; y++)
{
for (int x = pos1.x; x <= pos2.x; x++) {
for (int y = pos1.y; y <= pos2.y; y++) {
myplots.add(new PlotId(x, y));
}
}
return myplots;
}
/**
* Returns the plot a player is currently in.
*
@ -120,15 +111,18 @@ public class BukkitPlayerFunctions
*
* @return boolean
*/
public static Plot getCurrentPlot(final Player player)
{
if (!PS.get().isPlotWorld(player.getWorld().getName())) { return null; }
public static Plot getCurrentPlot(final Player player) {
if (!PS.get().isPlotWorld(player.getWorld().getName())) {
return null;
}
final PlotId id = MainUtil.getPlotId(BukkitUtil.getLocation(player));
final String world = player.getWorld().getName();
if (id == null) { return null; }
if (id == null) {
return null;
}
return MainUtil.getPlot(world, id);
}
/**
* Get the plots for a player
*
@ -136,10 +130,11 @@ public class BukkitPlayerFunctions
*
* @return boolean
*/
public static Set<Plot> getPlayerPlots(final String world, final Player plr)
{
public static Set<Plot> getPlayerPlots(final String world, final Player plr) {
final Set<Plot> p = PS.get().getPlots(world, plr.getName());
if (p == null) { return new HashSet<>(); }
if (p == null) {
return new HashSet<>();
}
return p;
}
}

View File

@ -50,20 +50,16 @@ import com.plotsquared.object.schematic.StateWrapper;
* Schematic Handler
*
*/
public class BukkitSchematicHandler extends SchematicHandler
*/
public class BukkitSchematicHandler extends SchematicHandler {
@Override
public void getCompoundTag(final String world, final Location pos1, final Location pos2, final RunnableVal<CompoundTag> whenDone)
@Override
public void getCompoundTag(final String world, final Location pos1, final Location pos2, final RunnableVal<CompoundTag> whenDone) {
// async
TaskManager.runTaskAsync(new Runnable()
// async
TaskManager.runTaskAsync(new Runnable() {
@Override
@Override
public void run() {
// Main positions
@ -75,14 +71,14 @@ public class BukkitSchematicHandler extends SchematicHandler
final int bcz = p1z >> 4;
final int tcx = p2x >> 4;
final int tcz = p2z >> 4;
final int sy = pos1.getY();
final int sy = pos1.getY();
final int ey = pos2.getY();
final int width = (pos2.getX() - pos1.getX()) + 1;
final int height = (pos2.getY() - pos1.getY()) + 1;
final int height = (pos2.getY() - pos1.getY()) + 1;
final int length = (pos2.getZ() - pos1.getZ()) + 1;
// Main Schematic tag
// Main Schematic tag
final HashMap<String, Tag> schematic = new HashMap<>();
schematic.put("Width", new ShortTag("Width", (short) width));
@ -93,80 +89,66 @@ public class BukkitSchematicHandler extends SchematicHandler
schematic.put("WEOriginY", new IntTag("WEOriginY", 0));
schematic.put("WEOriginZ", new IntTag("WEOriginZ", 0));
schematic.put("WEOffsetX", new IntTag("WEOffsetX", 0));
schematic.put("WEOffsetY", new IntTag("WEOffsetY", 0));
schematic.put("WEOffsetY", new IntTag("WEOffsetY", 0));
schematic.put("WEOffsetZ", new IntTag("WEOffsetZ", 0));
// Arrays of data types
final List<Tag> tileEntities = new ArrayList<Tag>();
final byte[] blocks = new byte[width * height * length];
final byte[] blocks = new byte[width * height * length];
final byte[] blockData = new byte[width * height * length];
// Generate list of chunks
final ArrayList<ChunkLoc> chunks = new ArrayList<ChunkLoc>();
for (int x = bcx; x <= tcx; x++)
{
// Generate list of chunks
final ArrayList<ChunkLoc> chunks = new ArrayList<ChunkLoc>();
for (int x = bcx; x <= tcx; x++) {
for (int z = bcz; z <= tcz; z++) {
chunks.add(new ChunkLoc(x, z));
}
}
}
final World worldObj = Bukkit.getWorld(world);
// Main thread
final World worldObj = Bukkit.getWorld(world);
// Main thread
{
@Override
TaskManager.runTask(new Runnable() {
@Override
{
final long start = System.currentTimeMillis();
public void run() {
final long start = System.currentTimeMillis();
while ((chunks.size() > 0) && ((System.currentTimeMillis() - start) < 20)) {
// save schematics
// save schematics
final ChunkLoc chunk = chunks.remove(0);
final Chunk bc = worldObj.getChunkAt(chunk.x, chunk.z);
final Chunk bc = worldObj.getChunkAt(chunk.x, chunk.z);
if (!bc.load(false)) {
continue;
continue;
}
final int X = chunk.x;
final int Z = chunk.z;
int xxb = X << 4;
int zzb = Z << 4;
int xxt = xxb + 15;
int zzt = zzb + 15;
int xxt = xxb + 15;
int zzt = zzb + 15;
if (X == bcx) {
xxb = p1x;
}
xxb = p1x;
}
if (X == tcx) {
xxt = p2x;
}
xxt = p2x;
}
if (Z == bcz) {
zzb = p1z;
}
zzb = p1z;
}
if (Z == tcz) {
zzt = p2z;
}
zzt = p2z;
}
for (int y = sy; y <= Math.min(255, ey); y++) {
final int ry = y - sy;
final int i1 = (ry * width * length);
final int ry = y - sy;
final int i1 = (ry * width * length);
for (int z = zzb; z <= zzt; z++) {
final int rz = z - p1z;
final int i2 = i1 + (rz * width);
final int rz = z - p1z;
final int i2 = i1 + (rz * width);
for (int x = xxb; x <= xxt; x++) {
final int rx = x - p1x;
final int index = i2 + rx;
final Block block = worldObj.getBlockAt(x, y, z);
final int id = block.getTypeId();
final Block block = worldObj.getBlockAt(x, y, z);
final int id = block.getTypeId();
switch (id) {
case 0:
@ -237,8 +219,7 @@ public class BukkitSchematicHandler extends SchematicHandler
case 182:
case 188:
case 189:
case 190:
case 191:
case 190:
case 191:
case 192: {
break;
@ -275,19 +256,15 @@ public class BukkitSchematicHandler extends SchematicHandler
case 123:
case 124:
case 29:
case 33:
case 151:
case 33:
case 151:
case 178: {
// TODO implement fully
final BlockState state = block.getState();
// TODO implement fully
final BlockState state = block.getState();
if (state != null) {
final StateWrapper wrapper = new StateWrapper(state);
final CompoundTag rawTag = wrapper.getTag();
final StateWrapper wrapper = new StateWrapper(state);
final CompoundTag rawTag = wrapper.getTag();
{
final Map<String, Tag> values = new HashMap<String, Tag>();
if (rawTag != null) {
final Map<String, Tag> values = new HashMap<String, Tag>();
for (final Entry<String, Tag> entry : rawTag.getValue().entrySet()) {
values.put(entry.getKey(), entry.getValue());
@ -299,8 +276,7 @@ public class BukkitSchematicHandler extends SchematicHandler
final CompoundTag tileEntityTag = new CompoundTag(values);
tileEntities.add(tileEntityTag);
}
}
}
}
}
default: {
blockData[index] = block.getData();
@ -316,19 +292,14 @@ public class BukkitSchematicHandler extends SchematicHandler
// }
blocks[index] = (byte) id;
}
}
}
}
}
}
{
TaskManager.runTaskLater(this, 1);
}
else
{
if (chunks.size() != 0) {
TaskManager.runTaskLater(this, 1);
} else {
{
@Override
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
schematic.put("Blocks", new ByteArrayTag("Blocks", blocks));

View File

@ -9,21 +9,18 @@ import org.bukkit.World;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.util.BlockUpdateUtil;
public abstract class BukkitSetBlockManager extends BlockUpdateUtil
{
public abstract class BukkitSetBlockManager extends BlockUpdateUtil {
public static BukkitSetBlockManager setBlockManager = null;
public abstract void set(final org.bukkit.World world, final int x, final int y, final int z, final int blockId, final byte data);
public abstract void update(final Collection<Chunk> list);
@Override
public void update(final String worldname, final Collection<ChunkLoc> chunkLocs)
{
public void update(final String worldname, final Collection<ChunkLoc> chunkLocs) {
final World world = BukkitUtil.getWorld(worldname);
final ArrayList<Chunk> chunks = new ArrayList<Chunk>();
for (final ChunkLoc loc : chunkLocs)
{
for (final ChunkLoc loc : chunkLocs) {
chunks.add(world.getChunkAt(loc.x, loc.z));
}
setBlockManager.update(chunks);

View File

@ -23,21 +23,18 @@ import com.plotsquared.bukkit.generator.AugmentedPopulator;
import com.plotsquared.bukkit.generator.BukkitGeneratorWrapper;
import com.plotsquared.bukkit.generator.BukkitPlotGenerator;
public class BukkitSetupUtils extends SetupUtils
{
public class BukkitSetupUtils extends SetupUtils {
@Override
public void updateGenerators()
{
if (SetupUtils.generators.size() > 0) { return; }
public void updateGenerators() {
if (SetupUtils.generators.size() > 0) {
return;
}
final String testWorld = "CheckingPlotSquaredGenerator";
for (final Plugin plugin : Bukkit.getPluginManager().getPlugins())
{
if (plugin.isEnabled())
{
for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
if (plugin.isEnabled()) {
final ChunkGenerator generator = plugin.getDefaultWorldGenerator(testWorld, "");
if (generator != null)
{
if (generator != null) {
PS.get().removePlotWorld(testWorld);
final String name = plugin.getDescription().getName();
SetupUtils.generators.put(name, new BukkitGeneratorWrapper("CheckingPlotSquaredGenerator", generator));
@ -45,114 +42,107 @@ public class BukkitSetupUtils extends SetupUtils
}
}
}
@Override
public String setupWorld(final SetupObject object)
{
public String setupWorld(final SetupObject object) {
SetupUtils.manager.updateGenerators();
final ConfigurationNode[] steps = object.step;
final String world = object.world;
for (final ConfigurationNode step : steps)
{
for (final ConfigurationNode step : steps) {
PS.get().config.set("worlds." + world + "." + step.getConstant(), step.getValue());
}
if (object.type != 0)
{
if (object.type != 0) {
PS.get().config.set("worlds." + world + "." + "generator.type", object.type);
PS.get().config.set("worlds." + world + "." + "generator.terrain", object.terrain);
PS.get().config.set("worlds." + world + "." + "generator.plugin", object.plotManager);
if ((object.setupGenerator != null) && !object.setupGenerator.equals(object.plotManager))
{
if ((object.setupGenerator != null) && !object.setupGenerator.equals(object.plotManager)) {
PS.get().config.set("worlds." + world + "." + "generator.init", object.setupGenerator);
}
final PlotGenerator<ChunkGenerator> gen = (PlotGenerator<ChunkGenerator>) generators.get(object.setupGenerator);
if ((gen != null) && (gen.generator instanceof BukkitPlotGenerator))
{
if ((gen != null) && (gen.generator instanceof BukkitPlotGenerator)) {
object.setupGenerator = null;
}
}
try
{
try {
PS.get().config.save(PS.get().configFile);
}
catch (final IOException e)
{
} catch (final IOException e) {
e.printStackTrace();
}
if (object.setupGenerator != null)
{
if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) && Bukkit.getPluginManager().getPlugin("Multiverse-Core").isEnabled())
{
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);
setGenerator(world, object.setupGenerator);
if (Bukkit.getWorld(world) != null) { return world; }
if (Bukkit.getWorld(world) != null) {
return world;
}
}
if ((Bukkit.getPluginManager().getPlugin("MultiWorld") != null) && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled())
{
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; }
if (Bukkit.getWorld(world) != null) {
return world;
}
}
final WorldCreator wc = new WorldCreator(object.world);
wc.generator(object.setupGenerator);
wc.environment(Environment.NORMAL);
Bukkit.createWorld(wc);
setGenerator(world, object.setupGenerator);
}
else
{
if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) && Bukkit.getPluginManager().getPlugin("Multiverse-Core").isEnabled())
{
} 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.getWorld(world) != null) { return world; }
if (Bukkit.getWorld(world) != null) {
return world;
}
}
if ((Bukkit.getPluginManager().getPlugin("MultiWorld") != null) && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled())
{
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; }
if (Bukkit.getWorld(world) != null) {
return world;
}
}
Bukkit.createWorld(new WorldCreator(object.world).environment(World.Environment.NORMAL));
}
return object.world;
}
public void setGenerator(final String world, final String generator)
{
if ((Bukkit.getWorlds().size() == 0) || !Bukkit.getWorlds().get(0).getName().equals(world)) { return; }
public void setGenerator(final String world, final String generator) {
if ((Bukkit.getWorlds().size() == 0) || !Bukkit.getWorlds().get(0).getName().equals(world)) {
return;
}
final File file = new File("bukkit.yml").getAbsoluteFile();
final YamlConfiguration yml = YamlConfiguration.loadConfiguration(file);
yml.set("worlds." + world + ".generator", generator);
try
{
try {
yml.save(file);
}
catch (final IOException e)
{
} catch (final IOException e) {
e.printStackTrace();
}
}
@Override
public String getGenerator(final PlotWorld plotworld)
{
if (SetupUtils.generators.size() == 0)
{
public String getGenerator(final PlotWorld plotworld) {
if (SetupUtils.generators.size() == 0) {
updateGenerators();
}
final World world = Bukkit.getWorld(plotworld.worldname);
if (world == null) { return null; }
if (world == null) {
return null;
}
final ChunkGenerator generator = world.getGenerator();
if (!(generator instanceof BukkitPlotGenerator)) { return null; }
for (final Entry<String, PlotGenerator<?>> entry : generators.entrySet())
{
if (entry.getValue().generator.getClass().getName().equals(generator.getClass().getName())) { return entry.getKey(); }
if (!(generator instanceof BukkitPlotGenerator)) {
return null;
}
for (final Entry<String, PlotGenerator<?>> entry : generators.entrySet()) {
if (entry.getValue().generator.getClass().getName().equals(generator.getClass().getName())) {
return entry.getKey();
}
}
return null;
}
@Override
public void removePopulator(final String world, final PlotCluster cluster)
{
public void removePopulator(final String world, final PlotCluster cluster) {
AugmentedPopulator.removePopulator(world, cluster);
}
}

View File

@ -5,49 +5,40 @@ import org.bukkit.Bukkit;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.bukkit.BukkitMain;
public class BukkitTaskManager extends TaskManager
{
public class BukkitTaskManager extends TaskManager {
@Override
public int taskRepeat(final Runnable r, final int interval)
{
public int taskRepeat(final Runnable r, final int interval) {
return BukkitMain.THIS.getServer().getScheduler().scheduleSyncRepeatingTask(BukkitMain.THIS, r, interval, interval);
}
@Override
public int taskRepeatAsync(final Runnable r, final int interval)
{
public int taskRepeatAsync(final Runnable r, final int interval) {
return BukkitMain.THIS.getServer().getScheduler().scheduleAsyncRepeatingTask(BukkitMain.THIS, r, interval, interval);
}
@Override
public void taskAsync(final Runnable r)
{
public void taskAsync(final Runnable r) {
BukkitMain.THIS.getServer().getScheduler().runTaskAsynchronously(BukkitMain.THIS, r).getTaskId();
}
@Override
public void task(final Runnable r)
{
public void task(final Runnable r) {
BukkitMain.THIS.getServer().getScheduler().runTask(BukkitMain.THIS, r).getTaskId();
}
@Override
public void taskLater(final Runnable r, final int delay)
{
public void taskLater(final Runnable r, final int delay) {
BukkitMain.THIS.getServer().getScheduler().runTaskLater(BukkitMain.THIS, r, delay).getTaskId();
}
@Override
public void taskLaterAsync(final Runnable r, final int delay)
{
public void taskLaterAsync(final Runnable r, final int delay) {
BukkitMain.THIS.getServer().getScheduler().runTaskLaterAsynchronously(BukkitMain.THIS, r, delay);
}
@Override
public void cancelTask(final int task)
{
if (task != -1)
{
public void cancelTask(final int task) {
if (task != -1) {
Bukkit.getScheduler().cancelTask(task);
}
}

View File

@ -34,21 +34,19 @@ import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.bukkit.object.BukkitPlayer;
public class BukkitUtil extends BlockManager
{
public class BukkitUtil extends BlockManager {
private static String lastString = null;
private static World lastWorld = null;
private static Player lastPlayer = null;
private static PlotPlayer lastPlotPlayer = null;
public static void removePlayer(final String plr)
{
public static void removePlayer(final String plr) {
lastPlayer = null;
lastPlotPlayer = null;
UUIDHandler.getPlayers().remove(plr);
}
// These weren't being used, but they might be useful later, so I'm just commenting them out
// private static int getMaxHeight(final String world) {
// return getWorld(world).getMaxHeight();
@ -109,228 +107,203 @@ public class BukkitUtil extends BlockManager
// private static int getViewDistance() {
// return Bukkit.getViewDistance();
// }
////////////////////////////////////////////////////////////////////////
/////////////////// USED BY EVENT SYSTEM AND SUCH //////////////////////
////////////////////////////////////////////////////////////////////////
public static PlotPlayer getPlayer(final OfflinePlayer op)
{
if (op.isOnline()) { return getPlayer(op.getPlayer()); }
public static PlotPlayer getPlayer(final OfflinePlayer op) {
if (op.isOnline()) {
return getPlayer(op.getPlayer());
}
final Player player = OfflinePlayerUtil.loadPlayer(op);
player.loadData();
return new BukkitPlayer(player, true);
}
public static PlotPlayer getPlayer(final Player player)
{
if (player == lastPlayer) { return lastPlotPlayer; }
public static PlotPlayer getPlayer(final Player player) {
if (player == lastPlayer) {
return lastPlotPlayer;
}
final String name = player.getName();
final PlotPlayer pp = UUIDHandler.getPlayers().get(name);
if (pp != null) { return pp; }
if (pp != null) {
return pp;
}
lastPlotPlayer = new BukkitPlayer(player);
UUIDHandler.getPlayers().put(name, lastPlotPlayer);
lastPlayer = player;
return lastPlotPlayer;
}
public static Location getLocation(final org.bukkit.Location loc)
{
public static Location getLocation(final org.bukkit.Location loc) {
return new Location(loc.getWorld().getName(), MathMan.roundInt(loc.getX()), MathMan.roundInt(loc.getY()), MathMan.roundInt(loc.getZ()));
}
public static org.bukkit.Location getLocation(final Location loc)
{
public static org.bukkit.Location getLocation(final Location loc) {
return new org.bukkit.Location(getWorld(loc.getWorld()), loc.getX(), loc.getY(), loc.getZ());
}
public static World getWorld(final String string)
{
if (StringMan.isEqual(string, lastString))
{
if (lastWorld != null) { return lastWorld; }
public static World getWorld(final String string) {
if (StringMan.isEqual(string, lastString)) {
if (lastWorld != null) {
return lastWorld;
}
}
final World world = Bukkit.getWorld(string);
lastString = string;
lastWorld = world;
return world;
}
public static String getWorld(final Entity entity)
{
public static String getWorld(final Entity entity) {
return entity.getWorld().getName();
}
public static List<Entity> getEntities(final String worldname)
{
public static List<Entity> getEntities(final String worldname) {
return getWorld(worldname).getEntities();
}
public static Location getLocation(final Entity entity)
{
public static Location getLocation(final Entity entity) {
final org.bukkit.Location loc = entity.getLocation();
final String world = loc.getWorld().getName();
return new Location(world, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
}
public static Location getLocationFull(final Entity entity)
{
public static Location getLocationFull(final Entity entity) {
final org.bukkit.Location loc = entity.getLocation();
return new Location(loc.getWorld().getName(), MathMan.roundInt(loc.getX()), MathMan.roundInt(loc.getY()), MathMan.roundInt(loc.getZ()), loc.getYaw(), loc.getPitch());
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////// CLASS ONLY METHODS //////////////////////////////
////////////////////////////////////////////////////////////////////////
private static void setBlock(final World world, final int x, final int y, final int z, final int id, final byte data)
{
try
{
private static void setBlock(final World world, final int x, final int y, final int z, final int id, final byte data) {
try {
BukkitSetBlockManager.setBlockManager.set(world, x, y, z, id, data);
}
catch (final Throwable e)
{
} catch (final Throwable e) {
BukkitSetBlockManager.setBlockManager = new SetBlockSlow();
BukkitSetBlockManager.setBlockManager.set(world, x, y, z, id, data);
}
}
////////////////////////////////////////////////////////////////////////
@Override
public boolean isWorld(final String world)
{
public boolean isWorld(final String world) {
return getWorld(world) != null;
}
@Override
public String getBiome(final String world, final int x, final int z)
{
public String getBiome(final String world, final int x, final int z) {
return getWorld(world).getBiome(x, z).name();
}
@Override
public void functionSetBlocks(final String worldname, final int[] x, final int[] y, final int[] z, final int[] id, final byte[] data)
{
public void functionSetBlocks(final String worldname, final int[] x, final int[] y, final int[] z, final int[] id, final byte[] data) {
final World world = getWorld(worldname);
for (int i = 0; i < x.length; i++)
{
for (int i = 0; i < x.length; i++) {
BukkitUtil.setBlock(world, x[i], y[i], z[i], id[i], data[i]);
}
}
@Override
public void functionSetSign(final String worldname, final int x, final int y, final int z, final String[] lines)
{
public void functionSetSign(final String worldname, final int x, final int y, final int z, final String[] lines) {
final World world = getWorld(worldname);
final Block block = world.getBlockAt(x, y, z);
block.setType(Material.AIR);
block.setTypeIdAndData(Material.WALL_SIGN.getId(), (byte) 2, false);
final BlockState blockstate = block.getState();
if ((blockstate instanceof Sign))
{
for (int i = 0; i < lines.length; i++)
{
if ((blockstate instanceof Sign)) {
for (int i = 0; i < lines.length; i++) {
((Sign) blockstate).setLine(i, lines[i]);
}
((Sign) blockstate).update(true);
}
}
@Override
public void functionSetBiomes(final String worldname, final int[] x, final int[] z, final String biomeStr)
{
public void functionSetBiomes(final String worldname, final int[] x, final int[] z, final String biomeStr) {
final World world = getWorld(worldname);
final Biome biome = Biome.valueOf(biomeStr.toUpperCase());
for (int i = 0; i < x.length; i++)
{
for (int i = 0; i < x.length; i++) {
world.setBiome(x[i], z[i], biome);
}
}
@Override
public void functionSetBlock(final String worldname, final int x, final int y, final int z, final int id, final byte data)
{
public void functionSetBlock(final String worldname, final int x, final int y, final int z, final int id, final byte data) {
BukkitUtil.setBlock(getWorld(worldname), x, y, z, id, data);
}
@Override
public String[] getSign(final Location loc)
{
public String[] getSign(final Location loc) {
final Block block = getWorld(loc.getWorld()).getBlockAt(loc.getX(), loc.getY(), loc.getZ());
if (block != null)
{
if (block.getState() instanceof Sign)
{
if (block != null) {
if (block.getState() instanceof Sign) {
final Sign sign = (Sign) block.getState();
return sign.getLines();
}
}
return null;
}
@Override
public Location getSpawn(final String world)
{
public Location getSpawn(final String world) {
final org.bukkit.Location temp = getWorld(world).getSpawnLocation();
return new Location(world, temp.getBlockX(), temp.getBlockY(), temp.getBlockZ(), temp.getYaw(), temp.getPitch());
}
@Override
public int getHeighestBlock(final String world, final int x, final int z)
{
public int getHeighestBlock(final String world, final int x, final int z) {
return getWorld(world).getHighestBlockAt(x, z).getY();
}
@Override
public int getBiomeFromString(final String biomeStr)
{
try
{
public int getBiomeFromString(final String biomeStr) {
try {
final Biome biome = Biome.valueOf(biomeStr.toUpperCase());
if (biome == null) { return -1; }
if (biome == null) {
return -1;
}
return Arrays.asList(Biome.values()).indexOf(biome);
}
catch (final IllegalArgumentException e)
{
} catch (final IllegalArgumentException e) {
return -1;
}
}
@Override
public String[] getBiomeList()
{
public String[] getBiomeList() {
final Biome[] biomes = Biome.values();
final String[] list = new String[biomes.length];
for (int i = 0; i < biomes.length; i++)
{
for (int i = 0; i < biomes.length; i++) {
list[i] = biomes[i].name();
}
return list;
}
@Override
public PlotBlock getPlotBlockFromString(final String block)
{
public PlotBlock getPlotBlockFromString(final String block) {
final Material material = Material.valueOf(block.toUpperCase());
if (material == null) { return new PlotBlock((short) -1, (byte) 0); }
if (material == null) {
return new PlotBlock((short) -1, (byte) 0);
}
return new PlotBlock((short) material.getId(), (byte) 0);
}
@Override
public boolean addItems(final String worldname, final PlotItem items)
{
public boolean addItems(final String worldname, final PlotItem items) {
final World world = getWorld(worldname);
final Block block = world.getBlockAt(items.x, items.y, items.z);
if (block == null) { return false; }
if (block == null) {
return false;
}
final BlockState state = block.getState();
if ((state != null) && (state instanceof InventoryHolder))
{
if ((state != null) && (state instanceof InventoryHolder)) {
final InventoryHolder holder = ((InventoryHolder) state);
final Inventory inv = holder.getInventory();
for (int i = 0; i < items.id.length; i++)
{
for (int i = 0; i < items.id.length; i++) {
final ItemStack item = new ItemStack(items.id[i], items.amount[i], items.data[i]);
inv.addItem(item);
}
@ -338,30 +311,24 @@ public class BukkitUtil extends BlockManager
return true;
}
return false;
}
@Override
public boolean isBlockSolid(final PlotBlock block)
{
try
{
public boolean isBlockSolid(final PlotBlock block) {
try {
final Material material = Material.getMaterial(block.id);
if (material.isBlock() && material.isSolid() && !material.hasGravity())
{
if (material.isBlock() && material.isSolid() && !material.hasGravity()) {
final 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))
{
switch (material)
{
|| data.equals(WoodenStep.class)) {
switch (material) {
case NOTE_BLOCK:
case MOB_SPAWNER:
{
case MOB_SPAWNER: {
return false;
}
default:
@ -370,51 +337,37 @@ public class BukkitUtil extends BlockManager
}
}
return false;
}
catch (final Exception e)
{
} catch (final Exception e) {
return false;
}
}
@Override
public String getClosestMatchingName(final PlotBlock block)
{
try
{
public String getClosestMatchingName(final PlotBlock block) {
try {
return Material.getMaterial(block.id).name();
}
catch (final Exception e)
{
} catch (final Exception e) {
return null;
}
}
@Override
public StringComparison<PlotBlock>.ComparisonResult getClosestBlock(String name)
{
try
{
public StringComparison<PlotBlock>.ComparisonResult getClosestBlock(String name) {
try {
double match;
short id;
byte data;
final String[] split = name.split(":");
if (split.length == 2)
{
if (split.length == 2) {
data = Byte.parseByte(split[1]);
name = split[0];
}
else
{
} else {
data = 0;
}
if (MathMan.isInteger(split[0]))
{
if (MathMan.isInteger(split[0])) {
id = Short.parseShort(split[0]);
match = 0;
}
else
{
} else {
final StringComparison<Material>.ComparisonResult comparison = new StringComparison<Material>(name, Material.values()).getBestMatchAdvanced();
match = comparison.match;
id = (short) comparison.best.getId();
@ -422,19 +375,18 @@ public class BukkitUtil extends BlockManager
final PlotBlock block = new PlotBlock(id, data);
final StringComparison<PlotBlock> outer = new StringComparison<PlotBlock>();
return outer.new ComparisonResult(match, block);
}
catch (final Exception e)
{}
} catch (final Exception e) {}
return null;
}
@Override
public PlotBlock getBlock(final Location loc)
{
public PlotBlock getBlock(final Location loc) {
final World world = getWorld(loc.getWorld());
final Block block = world.getBlockAt(loc.getX(), loc.getY(), loc.getZ());
if (block == null) { return new PlotBlock((short) 0, (byte) 0); }
if (block == null) {
return new PlotBlock((short) 0, (byte) 0);
}
return new PlotBlock((short) block.getTypeId(), block.getData());
}
}

View File

@ -51,8 +51,7 @@ import com.intellectualcrafters.configuration.InvalidConfigurationException;
import com.intellectualcrafters.configuration.file.YamlConfiguration;
import com.intellectualcrafters.plot.PS;
public class Metrics
{
public class Metrics {
/**
* The current revision number
*/
@ -101,10 +100,11 @@ public class Metrics
* The scheduled task
*/
private volatile BukkitTask task = null;
public Metrics(final Plugin plugin) throws IOException
{
if (plugin == null) { throw new IllegalArgumentException("Plugin cannot be null"); }
public Metrics(final Plugin plugin) throws IOException {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null");
}
this.plugin = plugin;
// load the config
configurationFile = getConfigFile();
@ -114,8 +114,7 @@ public class Metrics
configuration.addDefault("guid", UUID.randomUUID().toString());
configuration.addDefault("debug", false);
// Do we need to create the file?
if (configuration.get("guid", null) == null)
{
if (configuration.get("guid", null) == null) {
configuration.options().header("http://mcstats.org").copyDefaults(true);
configuration.save(configurationFile);
}
@ -123,7 +122,7 @@ public class Metrics
guid = configuration.getString("guid");
debug = configuration.getBoolean("debug", false);
}
/**
* GZip compress a string of bytes
*
@ -131,34 +130,24 @@ public class Metrics
*
* @return byte[] the file as a byte array
*/
public static byte[] gzip(final String input)
{
public static byte[] gzip(final String input) {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = null;
try
{
try {
gzos = new GZIPOutputStream(baos);
gzos.write(input.getBytes("UTF-8"));
}
catch (final IOException e)
{
} catch (final IOException e) {
e.printStackTrace();
}
finally
{
if (gzos != null)
{
try
{
} finally {
if (gzos != null) {
try {
gzos.close();
}
catch (final IOException ignore)
{}
} catch (final IOException ignore) {}
}
}
return baos.toByteArray();
}
/**
* Appends a json encoded key/value pair to the given string builder.
*
@ -168,37 +157,28 @@ public class Metrics
*
* @throws UnsupportedEncodingException
*/
private static void appendJSONPair(final StringBuilder json, final String key, final String value) throws UnsupportedEncodingException
{
private static void appendJSONPair(final StringBuilder json, final String key, final String value) throws UnsupportedEncodingException {
boolean isValueNumeric = false;
try
{
if (value.equals("0") || !value.endsWith("0"))
{
try {
if (value.equals("0") || !value.endsWith("0")) {
Double.parseDouble(value);
isValueNumeric = true;
}
}
catch (final NumberFormatException e)
{
} catch (final NumberFormatException e) {
isValueNumeric = false;
}
if (json.charAt(json.length() - 1) != '{')
{
if (json.charAt(json.length() - 1) != '{') {
json.append(',');
}
json.append(escapeJSON(key));
json.append(':');
if (isValueNumeric)
{
if (isValueNumeric) {
json.append(value);
}
else
{
} else {
json.append(escapeJSON(value));
}
}
/**
* Escape a string to create a valid JSON string
*
@ -206,15 +186,12 @@ public class Metrics
*
* @return String
*/
private static String escapeJSON(final String text)
{
private static String escapeJSON(final String text) {
final StringBuilder builder = new StringBuilder();
builder.append('"');
for (int index = 0; index < text.length(); index++)
{
for (int index = 0; index < text.length(); index++) {
final char chr = text.charAt(index);
switch (chr)
{
switch (chr) {
case '"':
case '\\':
builder.append('\\');
@ -233,13 +210,10 @@ public class Metrics
builder.append("\\r");
break;
default:
if (chr < ' ')
{
if (chr < ' ') {
final String t = "000" + Integer.toHexString(chr);
builder.append("\\u" + t.substring(t.length() - 4));
}
else
{
} else {
builder.append(chr);
}
break;
@ -248,7 +222,7 @@ public class Metrics
builder.append('"');
return builder.toString();
}
/**
* Encode text as UTF-8
*
@ -256,11 +230,10 @@ public class Metrics
*
* @return the encoded text, as UTF-8
*/
private static String urlEncode(final String text) throws UnsupportedEncodingException
{
private static String urlEncode(final String text) throws UnsupportedEncodingException {
return URLEncoder.encode(text, "UTF-8");
}
/**
* Construct and create a Graph that can be used to separate specific plotters to their own graphs on the metrics
* website. Plotters can be added to the graph object returned.
@ -269,9 +242,10 @@ public class Metrics
*
* @return Graph object created. Will never return NULL under normal circumstances unless bad parameters are given
*/
public Graph createGraph(final String name)
{
if (name == null) { throw new IllegalArgumentException("Graph name cannot be null"); }
public Graph createGraph(final String name) {
if (name == null) {
throw new IllegalArgumentException("Graph name cannot be null");
}
// Construct the graph object
final Graph graph = new Graph(name);
// Now we can add our graph
@ -279,18 +253,19 @@ public class Metrics
// and return back
return graph;
}
/**
* Add a Graph object to BukkitMetrics that represents data for the plugin that should be sent to the backend
*
* @param graph The name of the graph
*/
public void addGraph(final Graph graph)
{
if (graph == null) { throw new IllegalArgumentException("Graph cannot be null"); }
public void addGraph(final Graph graph) {
if (graph == null) {
throw new IllegalArgumentException("Graph cannot be null");
}
graphs.add(graph);
}
/**
* Start measuring statistics. This will immediately create an async repeating task as the plugin and send the
* initial data to the metrics backend, and then after that it will post in increments of PING_INTERVAL * 1200
@ -298,40 +273,36 @@ public class Metrics
*
* @return True if statistics measuring is running, otherwise false.
*/
public boolean start()
{
synchronized (optOutLock)
{
public boolean start() {
synchronized (optOutLock) {
// Did we opt out?
if (isOptOut()) { return false; }
if (isOptOut()) {
return false;
}
// Is metrics already running?
if (task != null) { return true; }
if (task != null) {
return true;
}
// Begin hitting the server with glorious data
task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable()
{
task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() {
private boolean firstPost = true;
@Override
public void run()
{
try
{
public void run() {
try {
// This has to be synchronized or it can collide
// with
// the disable method.
synchronized (optOutLock)
{
synchronized (optOutLock) {
// Disable Task, if it is running and the
// server
// owner decided to opt-out
if (isOptOut() && (task != null))
{
if (isOptOut() && (task != null)) {
task.cancel();
task = null;
// Tell all plotters to stop gathering
// information.
for (final Graph graph : graphs)
{
for (final Graph graph : graphs) {
graph.onOptOut();
}
}
@ -349,11 +320,8 @@ public class Metrics
// false
// Each post thereafter will be a ping
firstPost = false;
}
catch (final IOException e)
{
if (debug)
{
} catch (final IOException e) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage());
}
}
@ -362,33 +330,24 @@ public class Metrics
return true;
}
}
/**
* Has the server owner denied plugin metrics?
*
* @return true if metrics should be opted out of it
*/
public boolean isOptOut()
{
synchronized (optOutLock)
{
try
{
public boolean isOptOut() {
synchronized (optOutLock) {
try {
// Reload the metrics file
configuration.load(getConfigFile());
}
catch (final IOException ex)
{
if (debug)
{
} catch (final IOException ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
return true;
}
catch (final InvalidConfigurationException ex)
{
if (debug)
{
} catch (final InvalidConfigurationException ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
return true;
@ -396,67 +355,58 @@ public class Metrics
return configuration.getBoolean("opt-out", false);
}
}
/**
* Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task.
*
* @throws java.io.IOException
*/
public void enable() throws IOException
{
public void enable() throws IOException {
// This has to be synchronized or it can collide with the check in the
// task.
synchronized (optOutLock)
{
synchronized (optOutLock) {
// Check if the server owner has already set opt-out, if not, set
// it.
if (isOptOut())
{
if (isOptOut()) {
configuration.set("opt-out", false);
configuration.save(configurationFile);
}
// Enable Task, if it is not running
if (task == null)
{
if (task == null) {
start();
}
}
}
/**
* Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task.
*
* @throws java.io.IOException
*/
public void disable() throws IOException
{
public void disable() throws IOException {
// This has to be synchronized or it can collide with the check in the
// task.
synchronized (optOutLock)
{
synchronized (optOutLock) {
// Check if the server owner has already set opt-out, if not, set
// it.
if (!isOptOut())
{
if (!isOptOut()) {
configuration.set("opt-out", true);
configuration.save(configurationFile);
}
// Disable Task, if it is running
if (task != null)
{
if (task != null) {
task.cancel();
task = null;
}
}
}
/**
* Gets the File object of the config file that should be used to store data such as the GUID and opt-out status
*
* @return the File object for the config file
*/
public File getConfigFile()
{
public File getConfigFile() {
// I believe the easiest way to get the base folder (e.g craftbukkit set
// via -P) for plugins to use
// is to abuse the plugin object we already have
@ -467,12 +417,11 @@ public class Metrics
// return => base/plugins/PluginMetrics/config.yml
return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml");
}
/**
* Generic method that posts a plugin to the metrics website
*/
private void postPlugin(final boolean isPing) throws IOException
{
private void postPlugin(final boolean isPing) throws IOException {
// Server software specific section
final PluginDescriptionFile description = plugin.getDescription();
final String pluginName = description.getName();
@ -485,19 +434,13 @@ public class Metrics
final String pluginVersion = description.getVersion();
final String serverVersion = Bukkit.getVersion();
int playersOnline = 0;
try
{
if (Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).getReturnType() == Collection.class)
{
try {
if (Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).getReturnType() == Collection.class) {
playersOnline = ((Collection<?>) Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).invoke(null, new Object[0])).size();
}
else
{
} else {
playersOnline = ((Player[]) Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).invoke(null, new Object[0])).length;
}
}
catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex)
{}
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {}
// END server software specific section -- all code below does not use
// any code outside of this class / Java
// Construct the post data
@ -516,8 +459,7 @@ public class Metrics
final String java_version = System.getProperty("java.version");
final int coreCount = Runtime.getRuntime().availableProcessors();
// normalize os arch .. amd64 -> x86_64
if (osarch.equals("amd64"))
{
if (osarch.equals("amd64")) {
osarch = "x86_64";
}
appendJSONPair(json, "osname", osname);
@ -527,14 +469,11 @@ public class Metrics
appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0");
appendJSONPair(json, "java_version", java_version);
// If we're pinging, append it
if (isPing)
{
if (isPing) {
appendJSONPair(json, "ping", "1");
}
if (graphs.size() > 0)
{
synchronized (graphs)
{
if (graphs.size() > 0) {
synchronized (graphs) {
json.append(',');
json.append('"');
json.append("graphs");
@ -542,17 +481,14 @@ public class Metrics
json.append(':');
json.append('{');
boolean firstGraph = true;
for (final Graph graph : graphs)
{
for (final Graph graph : graphs) {
final StringBuilder graphJson = new StringBuilder();
graphJson.append('{');
for (final Plotter plotter : graph.getPlotters())
{
for (final Plotter plotter : graph.getPlotters()) {
appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue()));
}
graphJson.append('}');
if (!firstGraph)
{
if (!firstGraph) {
json.append(',');
}
json.append(escapeJSON(graph.getName()));
@ -571,12 +507,9 @@ public class Metrics
URLConnection connection;
// Mineshafter creates a socks proxy, so we can safely bypass it
// It does not reroute POST requests so we need to go around it
if (isMineshafterPresent())
{
if (isMineshafterPresent()) {
connection = url.openConnection(Proxy.NO_PROXY);
}
else
{
} else {
connection = url.openConnection();
}
final byte[] uncompressed = json.toString().getBytes();
@ -589,8 +522,7 @@ public class Metrics
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.setDoOutput(true);
if (debug)
{
if (debug) {
PS.debug("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length);
}
// Write the data
@ -603,29 +535,19 @@ public class Metrics
// close resources
os.close();
reader.close();
if ((response == null) || response.startsWith("ERR") || response.startsWith("7"))
{
if (response == null)
{
if ((response == null) || response.startsWith("ERR") || response.startsWith("7")) {
if (response == null) {
response = "null";
}
else if (response.startsWith("7"))
{
} else if (response.startsWith("7")) {
response = response.substring(response.startsWith("7,") ? 2 : 1);
}
throw new IOException(response);
}
else
{
} else {
// Is this the first update this hour?
if (response.equals("1") || response.contains("This is your first update this hour"))
{
synchronized (graphs)
{
for (final Graph graph : graphs)
{
for (final Plotter plotter : graph.getPlotters())
{
if (response.equals("1") || response.contains("This is your first update this hour")) {
synchronized (graphs) {
for (final Graph graph : graphs) {
for (final Plotter plotter : graph.getPlotters()) {
plotter.reset();
}
}
@ -633,30 +555,25 @@ public class Metrics
}
}
}
/**
* Check if mineshafter is present. If it is, we need to bypass it to send POST requests
*
* @return true if mineshafter is installed on the server
*/
private boolean isMineshafterPresent()
{
try
{
private boolean isMineshafterPresent() {
try {
Class.forName("mineshafter.MineServer");
return true;
}
catch (final Exception e)
{
} catch (final Exception e) {
return false;
}
}
/**
* Represents a custom graph on the website
*/
public static class Graph
{
public static class Graph {
/**
* The graph's name, alphanumeric and spaces only :) If it does not comply to the above when submitted, it is
* rejected
@ -666,101 +583,92 @@ public class Metrics
* The set of plotters that are contained within this graph
*/
private final Set<Plotter> plotters = new LinkedHashSet<Plotter>();
private Graph(final String name)
{
private Graph(final String name) {
this.name = name;
}
/**
* Gets the graph's name
*
* @return the Graph's name
*/
public String getName()
{
public String getName() {
return name;
}
/**
* Add a plotter to the graph, which will be used to plot entries
*
* @param plotter the plotter to add to the graph
*/
public void addPlotter(final Plotter plotter)
{
public void addPlotter(final Plotter plotter) {
plotters.add(plotter);
}
/**
* Remove a plotter from the graph
*
* @param plotter the plotter to remove from the graph
*/
public void removePlotter(final Plotter plotter)
{
public void removePlotter(final Plotter plotter) {
plotters.remove(plotter);
}
/**
* Gets an <b>unmodifiable</b> set of the plotter objects in the graph
*
* @return an unmodifiable {@link java.util.Set} of the plotter objects
*/
public Set<Plotter> getPlotters()
{
public Set<Plotter> getPlotters() {
return Collections.unmodifiableSet(plotters);
}
@Override
public int hashCode()
{
public int hashCode() {
return name.hashCode();
}
@Override
public boolean equals(final Object object)
{
if (!(object instanceof Graph)) { return false; }
public boolean equals(final Object object) {
if (!(object instanceof Graph)) {
return false;
}
final Graph graph = (Graph) object;
return graph.name.equals(name);
}
/**
* Called when the server owner decides to opt-out of BukkitMetrics while the server is running.
*/
protected void onOptOut()
{}
protected void onOptOut() {}
}
/**
* Interface used to collect custom data for a plugin
*/
public static abstract class Plotter
{
public static abstract class Plotter {
/**
* The plot's name
*/
private final String name;
/**
* Construct a plotter with the default plot name
*/
public Plotter()
{
public Plotter() {
this("Default");
}
/**
* Construct a plotter with a specific plot name
*
* @param name the name of the plotter to use, which will show up on the website
*/
public Plotter(final String name)
{
public Plotter(final String name) {
this.name = name;
}
/**
* Get the current value for the plotted point. Since this function defers to an external function it may or may
* not return immediately thus cannot be guaranteed to be thread friendly or safe. This function can be called
@ -769,33 +677,31 @@ public class Metrics
* @return the current value for the point to be plotted.
*/
public abstract int getValue();
/**
* Get the column name for the plotted point
*
* @return the plotted point's column name
*/
public String getColumnName()
{
public String getColumnName() {
return name;
}
/**
* Called after the website graphs have been updated
*/
public void reset()
{}
public void reset() {}
@Override
public int hashCode()
{
public int hashCode() {
return getColumnName().hashCode();
}
@Override
public boolean equals(final Object object)
{
if (!(object instanceof Plotter)) { return false; }
public boolean equals(final Object object) {
if (!(object instanceof Plotter)) {
return false;
}
final Plotter plotter = (Plotter) object;
return plotter.name.equals(name) && (plotter.getValue() == getValue());
}

View File

@ -17,28 +17,27 @@ import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
public class OfflinePlayerUtil
{
public static Player loadPlayer(final String name)
{
public class OfflinePlayerUtil {
public static Player loadPlayer(final String name) {
return loadPlayer(Bukkit.getOfflinePlayer(name));
}
public static Player loadPlayer(final UUID id)
{
public static Player loadPlayer(final UUID id) {
return loadPlayer(Bukkit.getOfflinePlayer(id));
}
public static Player loadPlayer(final OfflinePlayer player)
{
if (player == null) { return null; }
if (player instanceof Player) { return (Player) player; }
public static Player loadPlayer(final OfflinePlayer player) {
if (player == null) {
return null;
}
if (player instanceof Player) {
return (Player) player;
}
return loadPlayer(player.getUniqueId(), player.getName());
}
private static Player loadPlayer(final UUID id, final String name)
{
private static Player loadPlayer(final UUID id, final String name) {
final Object server = getMinecraftServer();
final Object interactManager = newPlayerInteractManager();
final Object worldServer = getWorldServer();
@ -50,53 +49,44 @@ public class OfflinePlayerUtil
final Player player = (Player) getBukkitEntity(entityPlayer);
return player;
}
private static Object newGameProfile(final UUID id, final String name)
{
private static Object newGameProfile(final UUID id, final String name) {
final Class<?> gameProfileClass = getUtilClass("com.mojang.authlib.GameProfile");
if (gameProfileClass == null)
{ //Before uuids
if (gameProfileClass == null) { //Before uuids
return name;
}
Constructor gameProfileConstructor = null;
gameProfileConstructor = makeConstructor(gameProfileClass, UUID.class, String.class);
if (gameProfileConstructor == null)
{ //Verson has string constructor
if (gameProfileConstructor == null) { //Verson has string constructor
gameProfileConstructor = makeConstructor(gameProfileClass, String.class, String.class);
return callConstructor(gameProfileConstructor, id.toString(), name);
}
else
{ //Version has uuid constructor
} else { //Version has uuid constructor
return callConstructor(gameProfileConstructor, id, name);
}
}
private static Object newPlayerInteractManager()
{
private static Object newPlayerInteractManager() {
final Object worldServer = getWorldServer();
final Class<?> playerInteractClass = getNmsClass("PlayerInteractManager");
final Class<?> worldClass = getNmsClass("World");
final Constructor c = makeConstructor(playerInteractClass, worldClass);
return callConstructor(c, worldServer);
}
private static Object getWorldServer()
{
private static Object getWorldServer() {
final Object server = getMinecraftServer();
final Class<?> minecraftServerClass = getNmsClass("MinecraftServer");
final Method getWorldServer = makeMethod(minecraftServerClass, "getWorldServer", int.class);
return callMethod(getWorldServer, server, 0);
}
//NMS Utils
private static Object getMinecraftServer()
{
private static Object getMinecraftServer() {
return callMethod(makeMethod(getCbClass("CraftServer"), "getServer"), Bukkit.getServer());
}
private static Entity getBukkitEntity(final Object o)
{
private static Entity getBukkitEntity(final Object o) {
final Method getBukkitEntity = makeMethod(o.getClass(), "getBukkitEntity");
return callMethod(getBukkitEntity, o);
}

View File

@ -11,187 +11,137 @@ import org.bukkit.Bukkit;
* Reflection Utilities for minecraft
*
*/
public class ReflectionUtil
{
public static Class<?> getNmsClass(final String name)
{
public class ReflectionUtil {
public static Class<?> getNmsClass(final String name) {
final String className = "net.minecraft.server." + getVersion() + "." + name;
return getClass(className);
}
public static Class<?> getCbClass(final String name)
{
public static Class<?> getCbClass(final String name) {
final String className = "org.bukkit.craftbukkit." + getVersion() + "." + name;
return getClass(className);
}
public static Class<?> getUtilClass(final String name)
{
try
{
public static Class<?> getUtilClass(final String name) {
try {
return Class.forName(name); //Try before 1.8 first
}
catch (final ClassNotFoundException ex)
{
try
{
} catch (final ClassNotFoundException ex) {
try {
return Class.forName("net.minecraft.util." + name); //Not 1.8
}
catch (final ClassNotFoundException ex2)
{
} catch (final ClassNotFoundException ex2) {
return null;
}
}
}
public static String getVersion()
{
public static String getVersion() {
final String packageName = Bukkit.getServer().getClass().getPackage().getName();
return packageName.substring(packageName.lastIndexOf('.') + 1);
}
public static Object getHandle(final Object wrapper)
{
public static Object getHandle(final Object wrapper) {
final Method getHandle = makeMethod(wrapper.getClass(), "getHandle");
return callMethod(getHandle, wrapper);
}
//Utils
public static Method makeMethod(final Class<?> clazz, final String methodName, final Class<?>... paramaters)
{
try
{
public static Method makeMethod(final Class<?> clazz, final String methodName, final Class<?>... paramaters) {
try {
return clazz.getDeclaredMethod(methodName, paramaters);
}
catch (final NoSuchMethodException ex)
{
} catch (final NoSuchMethodException ex) {
return null;
}
catch (final Exception ex)
{
} catch (final Exception ex) {
throw new RuntimeException(ex);
}
}
@SuppressWarnings("unchecked")
public static <T> T callMethod(final Method method, final Object instance, final Object... paramaters)
{
if (method == null) { throw new RuntimeException("No such method"); }
public static <T> T callMethod(final Method method, final Object instance, final Object... paramaters) {
if (method == null) {
throw new RuntimeException("No such method");
}
method.setAccessible(true);
try
{
try {
return (T) method.invoke(instance, paramaters);
}
catch (final InvocationTargetException ex)
{
} catch (final InvocationTargetException ex) {
throw new RuntimeException(ex.getCause());
}
catch (final Exception ex)
{
} catch (final Exception ex) {
throw new RuntimeException(ex);
}
}
@SuppressWarnings("unchecked")
public static <T> Constructor<T> makeConstructor(final Class<?> clazz, final Class<?>... paramaterTypes)
{
try
{
public static <T> Constructor<T> makeConstructor(final Class<?> clazz, final Class<?>... paramaterTypes) {
try {
return (Constructor<T>) clazz.getConstructor(paramaterTypes);
}
catch (final NoSuchMethodException ex)
{
} catch (final NoSuchMethodException ex) {
return null;
}
catch (final Exception ex)
{
} catch (final Exception ex) {
throw new RuntimeException(ex);
}
}
public static <T> T callConstructor(final Constructor<T> constructor, final Object... paramaters)
{
if (constructor == null) { throw new RuntimeException("No such constructor"); }
public static <T> T callConstructor(final Constructor<T> constructor, final Object... paramaters) {
if (constructor == null) {
throw new RuntimeException("No such constructor");
}
constructor.setAccessible(true);
try
{
try {
return constructor.newInstance(paramaters);
}
catch (final InvocationTargetException ex)
{
} catch (final InvocationTargetException ex) {
throw new RuntimeException(ex.getCause());
}
catch (final Exception ex)
{
} catch (final Exception ex) {
throw new RuntimeException(ex);
}
}
public static Field makeField(final Class<?> clazz, final String name)
{
try
{
public static Field makeField(final Class<?> clazz, final String name) {
try {
return clazz.getDeclaredField(name);
}
catch (final NoSuchFieldException ex)
{
} catch (final NoSuchFieldException ex) {
return null;
}
catch (final Exception ex)
{
} catch (final Exception ex) {
throw new RuntimeException(ex);
}
}
@SuppressWarnings("unchecked")
public static <T> T getField(final Field field, final Object instance)
{
if (field == null) { throw new RuntimeException("No such field"); }
public static <T> T getField(final Field field, final Object instance) {
if (field == null) {
throw new RuntimeException("No such field");
}
field.setAccessible(true);
try
{
try {
return (T) field.get(instance);
}
catch (final Exception ex)
{
} catch (final Exception ex) {
throw new RuntimeException(ex);
}
}
public static void setField(final Field field, final Object instance, final Object value)
{
if (field == null) { throw new RuntimeException("No such field"); }
public static void setField(final Field field, final Object instance, final Object value) {
if (field == null) {
throw new RuntimeException("No such field");
}
field.setAccessible(true);
try
{
try {
field.set(instance, value);
}
catch (final Exception ex)
{
} catch (final Exception ex) {
throw new RuntimeException(ex);
}
}
public static Class<?> getClass(final String name)
{
try
{
public static Class<?> getClass(final String name) {
try {
return Class.forName(name);
}
catch (final ClassNotFoundException ex)
{
} catch (final ClassNotFoundException ex) {
return null;
}
}
public static <T> Class<? extends T> getClass(final String name, final Class<T> superClass)
{
try
{
public static <T> Class<? extends T> getClass(final String name, final Class<T> superClass) {
try {
return Class.forName(name).asSubclass(superClass);
}
catch (ClassCastException | ClassNotFoundException ex)
{
} catch (ClassCastException | ClassNotFoundException ex) {
return null;
}
}

View File

@ -30,9 +30,8 @@ import com.plotsquared.bukkit.object.BukkitPlayer;
* An utility that can be used to send chunks, rather than using bukkit code to do so (uses heavy NMS)
*
*/
public class SendChunk
{
*/
public class SendChunk {
// // Ref Class
private final RefClass classEntityPlayer = getRefClass("{nms}.EntityPlayer");
@ -47,14 +46,13 @@ public class SendChunk
private final RefConstructor MapChunk;
private final RefField connection;
private final RefMethod send;
private final RefMethod methodInitLighting;
private final RefMethod methodInitLighting;
/**
* Constructor
*
* @throws NoSuchMethodException
*/
public SendChunk() throws NoSuchMethodException
*/
public SendChunk() throws NoSuchMethodException {
methodGetHandlePlayer = classCraftPlayer.getMethod("getHandle");
methodGetHandleChunk = classCraftChunk.getMethod("getHandle");
@ -62,18 +60,15 @@ public class SendChunk
MapChunk = classMapChunk.getConstructor(classChunk.getRealClass(), boolean.class, int.class);
connection = classEntityPlayer.getField("playerConnection");
send = classConnection.getMethod("sendPacket", classPacket.getRealClass());
}
public void sendChunk(final Collection<Chunk> input)
}
public void sendChunk(final Collection<Chunk> input) {
final HashSet<Chunk> chunks = new HashSet<Chunk>(input);
final HashMap<String, ArrayList<Chunk>> map = new HashMap<>();
final int view = Bukkit.getServer().getViewDistance();
for (final Chunk chunk : chunks)
final int view = Bukkit.getServer().getViewDistance();
for (final Chunk chunk : chunks) {
final String world = chunk.getWorld().getName();
ArrayList<Chunk> list = map.get(world);
if (list == null)
ArrayList<Chunk> list = map.get(world);
if (list == null) {
list = new ArrayList<>();
map.put(world, list);
@ -81,40 +76,32 @@ public class SendChunk
list.add(chunk);
final Object c = methodGetHandleChunk.of(chunk).call();
methodInitLighting.of(c).call();
}
for (final PlotPlayer pp : UUIDHandler.getPlayers().values())
}
for (final PlotPlayer pp : UUIDHandler.getPlayers().values()) {
final Plot plot = pp.getCurrentPlot();
Location loc = null;
String world;
if (plot != null)
String world;
if (plot != null) {
world = plot.world;
}
else
world = plot.world;
} else {
loc = pp.getLocation();
world = loc.getWorld();
}
final ArrayList<Chunk> list = map.get(world);
if (list == null)
final ArrayList<Chunk> list = map.get(world);
if (list == null) {
continue;
}
if (loc == null)
}
if (loc == null) {
loc = pp.getLocation();
}
final int cx = loc.getX() >> 4;
final int cz = loc.getZ() >> 4;
final Player player = ((BukkitPlayer) pp).player;
final Object entity = methodGetHandlePlayer.of(player).call();
for (final Chunk chunk : list)
final Object entity = methodGetHandlePlayer.of(player).call();
for (final Chunk chunk : list) {
final int dx = Math.abs(cx - chunk.getX());
final int dz = Math.abs(cz - chunk.getZ());
if ((dx > view) || (dz > view))
final int dz = Math.abs(cz - chunk.getZ());
if ((dx > view) || (dz > view)) {
continue;
}
@ -128,19 +115,13 @@ public class SendChunk
final Object packet = MapChunk.create(c, true, 65535);
send.of(con).call(packet);
}
}
for (final Chunk chunk : chunks)
{
TaskManager.runTask(new Runnable()
}
for (final Chunk chunk : chunks) {
TaskManager.runTask(new Runnable() {
@Override
public void run()
{
try
@Override
public void run() {
try {
chunk.unload(true, false);
}
catch (final Exception e)
chunk.unload(true, false);
} catch (final Exception e) {
final String worldname = chunk.getWorld().getName();
PS.debug("$4Could not save chunk: " + worldname + ";" + chunk.getX() + ";" + chunk.getZ());
@ -198,13 +179,11 @@ public class SendChunk
// }
//
// }
}
public void sendChunk(final String worldname, final List<ChunkLoc> locs)
}
public void sendChunk(final String worldname, final List<ChunkLoc> locs) {
final World myworld = Bukkit.getWorld(worldname);
final ArrayList<Chunk> chunks = new ArrayList<>();
for (final ChunkLoc loc : locs)
final ArrayList<Chunk> chunks = new ArrayList<>();
for (final ChunkLoc loc : locs) {
chunks.add(myworld.getChunkAt(loc.x, loc.z));
}

View File

@ -37,8 +37,7 @@ import com.intellectualcrafters.plot.util.TaskManager;
* SetBlockFast class<br> Used to do fast world editing
*
*/
public class SetBlockFast extends BukkitSetBlockManager
*/
public class SetBlockFast extends BukkitSetBlockManager {
private final RefClass classBlock = getRefClass("{nms}.Block");
private final RefClass classChunk = getRefClass("{nms}.Chunk");
@ -48,26 +47,23 @@ public class SetBlockFast extends BukkitSetBlockManager
private final RefMethod methodGetChunkAt;
private final RefMethod methodA;
private final RefMethod methodGetById;
private final SendChunk chunksender;
private final SendChunk chunksender;
public HashMap<ChunkLoc, Chunk> toUpdate = new HashMap<>();
public HashMap<ChunkLoc, Chunk> toUpdate = new HashMap<>();
/**
* Constructor
*
* @throws NoSuchMethodException
*/
public SetBlockFast() throws NoSuchMethodException
*/
public SetBlockFast() throws NoSuchMethodException {
methodGetHandle = classCraftWorld.getMethod("getHandle");
methodGetChunkAt = classWorld.getMethod("getChunkAt", int.class, int.class);
methodA = classChunk.getMethod("a", int.class, int.class, int.class, classBlock, int.class);
methodGetById = classBlock.getMethod("getById", int.class);
TaskManager.runTaskRepeat(new Runnable()
{
methodGetById = classBlock.getMethod("getById", int.class);
TaskManager.runTaskRepeat(new Runnable() {
@Override
public void run()
@Override
public void run() {
// TODO Auto-generated method stub
update(toUpdate.values());
@ -75,9 +71,9 @@ public class SetBlockFast extends BukkitSetBlockManager
}
}, 20);
chunksender = new SendChunk();
}
}
private final ChunkLoc lastLoc = null;
private final ChunkLoc lastLoc = null;
/**
* Set the block at the location
@ -90,58 +86,50 @@ public class SetBlockFast extends BukkitSetBlockManager
* @param data Block Data Value
*
*/
@Override
public void set(final org.bukkit.World world, final int x, final int y, final int z, final int blockId, final byte data)
{
if (blockId == -1)
@Override
public void set(final org.bukkit.World world, final int x, final int y, final int z, final int blockId, final byte data) {
if (blockId == -1) {
world.getBlockAt(x, y, z).setData(data, false);
return;
}
final int X = x >> 4;
final int Z = z >> 4;
final ChunkLoc loc = new ChunkLoc(X, Z);
if (!loc.equals(lastLoc))
final ChunkLoc loc = new ChunkLoc(X, Z);
if (!loc.equals(lastLoc)) {
Chunk chunk = toUpdate.get(loc);
if (chunk == null)
Chunk chunk = toUpdate.get(loc);
if (chunk == null) {
chunk = world.getChunkAt(X, Z);
toUpdate.put(loc, chunk);
}
chunk.load(false);
}
}
final Object w = methodGetHandle.of(world).call();
final Object chunk = methodGetChunkAt.of(w).call(x >> 4, z >> 4);
final Object block = methodGetById.of(null).call(blockId);
methodA.of(chunk).call(x & 0x0f, y, z & 0x0f, block, data);
}
}
/**
* Update chunks
*
* @param chunks list of chunks to update
*/
@Override
public void update(final Collection<Chunk> chunks)
{
if (chunks.size() == 0) { return; }
if (!MainUtil.canSendChunk)
{
for (final Chunk chunk : chunks)
@Override
public void update(final Collection<Chunk> chunks) {
if (chunks.size() == 0) {
return;
}
if (!MainUtil.canSendChunk) {
for (final Chunk chunk : chunks) {
chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ());
chunk.unload(true, false);
chunk.load();
}
return;
}
try
}
try {
chunksender.sendChunk(chunks);
}
catch (final Throwable e)
chunksender.sendChunk(chunks);
} catch (final Throwable e) {
e.printStackTrace();
MainUtil.canSendChunk = false;

View File

@ -43,8 +43,7 @@ import com.intellectualcrafters.plot.util.TaskManager;
* SetBlockFast class<br> Used to do fast world editing
*
*/
public class SetBlockFast_1_8 extends BukkitSetBlockManager
*/
public class SetBlockFast_1_8 extends BukkitSetBlockManager {
private final RefClass classBlock = getRefClass("{nms}.Block");
private final RefClass classBlockPosition = getRefClass("{nms}.BlockPosition");
@ -57,35 +56,31 @@ public class SetBlockFast_1_8 extends BukkitSetBlockManager
private RefMethod methodA;
private RefMethod methodGetByCombinedId;
private RefConstructor constructorBlockPosition;
private SendChunk chunksender;
private SendChunk chunksender;
public static HashMap<ChunkLoc, Chunk> toUpdate = new HashMap<>();
public static HashMap<ChunkLoc, Chunk> toUpdate = new HashMap<>();
/**
* Constructor
*
* @throws NoSuchMethodException
*/
public SetBlockFast_1_8() throws NoSuchMethodException
*/
public SetBlockFast_1_8() throws NoSuchMethodException {
constructorBlockPosition = classBlockPosition.getConstructor(int.class, int.class, int.class);
methodGetByCombinedId = classBlock.getMethod("getByCombinedId", int.class);
methodGetHandle = classCraftWorld.getMethod("getHandle");
methodGetChunkAt = classWorld.getMethod("getChunkAt", int.class, int.class);
methodA = classChunk.getMethod("a", classBlockPosition, classIBlockData);
TaskManager.runTaskRepeat(new Runnable()
{
methodA = classChunk.getMethod("a", classBlockPosition, classIBlockData);
TaskManager.runTaskRepeat(new Runnable() {
@Override
public void run()
@Override
public void run() {
if (toUpdate.size() == 0) {
return;
}
int count = 0;
final ArrayList<Chunk> chunks = new ArrayList<Chunk>();
final Iterator<Entry<ChunkLoc, Chunk>> i = toUpdate.entrySet().iterator();
while (i.hasNext() && (count < 128))
final Iterator<Entry<ChunkLoc, Chunk>> i = toUpdate.entrySet().iterator();
while (i.hasNext() && (count < 128)) {
chunks.add(i.next().getValue());
i.remove();
@ -98,9 +93,9 @@ public class SetBlockFast_1_8 extends BukkitSetBlockManager
}
}, 1);
chunksender = new SendChunk();
}
}
private final ChunkLoc lastLoc = null;
private final ChunkLoc lastLoc = null;
/**
* Set the block at the location
@ -113,16 +108,13 @@ public class SetBlockFast_1_8 extends BukkitSetBlockManager
* @param data Block Data Value
*/
@SuppressWarnings("deprecation")
@Override
public void set(final World world, final int x, final int y, final int z, final int id, final byte data)
{
if (id == -1)
@Override
public void set(final World world, final int x, final int y, final int z, final int id, final byte data) {
if (id == -1) {
world.getBlockAt(x, y, z).setData(data, false);
return;
}
// Start blockstate workaround //
switch (id)
// Start blockstate workaround //
switch (id) {
case 54:
case 130:
@ -159,38 +151,28 @@ public class SetBlockFast_1_8 extends BukkitSetBlockManager
case 124:
case 29:
case 33:
case 151:
case 178:
case 151:
case 178: {
final Block block = world.getBlockAt(x, y, z);
if (block.getData() == data)
{
if (block.getTypeId() != id)
final Block block = world.getBlockAt(x, y, z);
if (block.getData() == data) {
if (block.getTypeId() != id) {
block.setTypeId(id, false);
}
}
else
{
if (block.getTypeId() == id)
}
} else {
if (block.getTypeId() == id) {
block.setData(data, false);
}
else
block.setData(data, false);
} else {
block.setTypeIdAndData(id, data, false);
}
}
return;
}
}
}
// Start data value shortcut
final Block block = world.getBlockAt(x, y, z);
final int currentId = block.getTypeId();
if (currentId == id)
{
switch (id)
final int currentId = block.getTypeId();
if (currentId == id) {
switch (id) {
case 0:
case 2:
@ -272,18 +254,18 @@ public class SetBlockFast_1_8 extends BukkitSetBlockManager
case 188:
case 189:
case 190:
case 191:
case 192:
case 191:
case 192: {
return;
}
}
}
if (block.getData() == data) {
return;
}
block.setData(data);
return;
}
// blockstate
switch (currentId)
// blockstate
switch (currentId) {
case 54:
case 130:
@ -320,62 +302,52 @@ public class SetBlockFast_1_8 extends BukkitSetBlockManager
case 124:
case 29:
case 33:
case 151:
case 178:
{
if (block.getData() == data)
case 151:
case 178: {
if (block.getData() == data) {
block.setTypeId(id, false);
}
else
block.setTypeId(id, false);
} else {
block.setTypeIdAndData(id, data, false);
}
return;
}
}
// End blockstate workaround //
// End blockstate workaround //
final int X = x >> 4;
final int Z = z >> 4;
final ChunkLoc loc = new ChunkLoc(X, Z);
if (!loc.equals(lastLoc))
{
Chunk chunk = toUpdate.get(loc);
if (chunk == null)
{
chunk = world.getChunkAt(X, Z);
toUpdate.put(loc, chunk);
}
chunk.load(false);
}
// check sign
final Object w = methodGetHandle.of(world).call();
final Object chunk = methodGetChunkAt.of(w).call(x >> 4, z >> 4);
final Object pos = constructorBlockPosition.create(x & 0x0f, y, z & 0x0f);
final Object combined = methodGetByCombinedId.of(null).call(id + (data << 12));
final int X = x >> 4;
final int Z = z >> 4;
final ChunkLoc loc = new ChunkLoc(X, Z);
if (!loc.equals(lastLoc)) {
Chunk chunk = toUpdate.get(loc);
if (chunk == null) {
chunk = world.getChunkAt(X, Z);
toUpdate.put(loc, chunk);
}
chunk.load(false);
}
// check sign
final Object w = methodGetHandle.of(world).call();
final Object chunk = methodGetChunkAt.of(w).call(x >> 4, z >> 4);
final Object pos = constructorBlockPosition.create(x & 0x0f, y, z & 0x0f);
final Object combined = methodGetByCombinedId.of(null).call(id + (data << 12));
methodA.of(chunk).call(pos, combined);
}
}
@Override
public void update(final Collection<Chunk> chunks)
{
if (chunks.size() == 0) { return; }
if (!MainUtil.canSendChunk)
{
for (final Chunk chunk : chunks)
@Override
public void update(final Collection<Chunk> chunks) {
if (chunks.size() == 0) {
return;
}
if (!MainUtil.canSendChunk) {
for (final Chunk chunk : chunks) {
chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ());
chunk.unload(true, false);
chunk.load();
}
return;
}
try
}
try {
chunksender.sendChunk(chunks);
}
catch (final Throwable e)
chunksender.sendChunk(chunks);
} catch (final Throwable e) {
e.printStackTrace();
MainUtil.canSendChunk = false;

View File

@ -6,40 +6,29 @@ import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Block;
public class SetBlockSlow extends BukkitSetBlockManager
{
public class SetBlockSlow extends BukkitSetBlockManager {
@Override
public void set(final World world, final int x, final int y, final int z, final int id, final byte data)
{
public void set(final World world, final int x, final int y, final int z, final int id, final byte data) {
final Block block = world.getBlockAt(x, y, z);
if (id == -1)
{
if (id == -1) {
block.setData(data, false);
return;
}
if (block.getData() == data)
{
if (block.getTypeId() != id)
{
if (block.getData() == data) {
if (block.getTypeId() != id) {
block.setTypeId(id, false);
}
}
else
{
if (block.getTypeId() == id)
{
} else {
if (block.getTypeId() == id) {
block.setData(data, false);
}
else
{
} else {
block.setTypeIdAndData(id, data, false);
}
}
}
@Override
public void update(final Collection<Chunk> chunks)
{
public void update(final Collection<Chunk> chunks) {
// TODO nothing
}
}

View File

@ -14,21 +14,19 @@ import com.intellectualcrafters.plot.generator.PlotGenerator;
import com.intellectualcrafters.plot.util.SetupUtils;
import com.plotsquared.bukkit.generator.AugmentedPopulator;
public class SetGenCB
{
public static void setGenerator(final World world) throws Exception
{
public class SetGenCB {
public static void setGenerator(final World world) throws Exception {
SetupUtils.manager.updateGenerators();
PS.get().removePlotWorldAbs(world.getName());
final ChunkGenerator gen = world.getGenerator();
if (gen == null) { return; }
if (gen == null) {
return;
}
final String name = gen.getClass().getCanonicalName();
boolean set = false;
for (final PlotGenerator<?> wrapper : SetupUtils.generators.values())
{
for (final PlotGenerator<?> wrapper : SetupUtils.generators.values()) {
final ChunkGenerator newGen = (ChunkGenerator) wrapper.generator;
if (newGen.getClass().getCanonicalName().equals(name))
{
if (newGen.getClass().getCanonicalName().equals(name)) {
// set generator
final Field generator = world.getClass().getDeclaredField("generator");
final Field populators = world.getClass().getDeclaredField("populators");
@ -46,13 +44,10 @@ public class SetGenCB
break;
}
}
if (!set)
{
if (!set) {
final Iterator<BlockPopulator> iter = world.getPopulators().iterator();
while (iter.hasNext())
{
if (iter.next() instanceof AugmentedPopulator)
{
while (iter.hasNext()) {
if (iter.next() instanceof AugmentedPopulator) {
iter.remove();
}
}

View File

@ -13,10 +13,8 @@ import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.bukkit.BukkitWorld;
public class WorldEditSchematic
{
public void saveSchematic(final String file, final String world, final PlotId id)
{
public class WorldEditSchematic {
public void saveSchematic(final String file, final String world, final PlotId id) {
final Location bot = MainUtil.getPlotBottomLoc(world, id).add(1, 0, 1);
final Location top = MainUtil.getPlotTopLoc(world, id);
final Vector size = new Vector((top.getX() - bot.getX()) + 1, top.getY() - bot.getY() - 1, (top.getZ() - bot.getZ()) + 1);
@ -26,13 +24,10 @@ public class WorldEditSchematic
new Vector(top.getX(), top.getY(), top.getZ());
final EditSession session = BukkitMain.worldEdit.getWorldEdit().getEditSessionFactory().getEditSession(new BukkitWorld(Bukkit.getWorld(world)), 999999999);
clipboard.copy(session);
try
{
try {
clipboard.saveSchematic(new File(file));
MainUtil.sendMessage(null, "&7 - &a success: " + id);
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
MainUtil.sendMessage(null, "&7 - Failed to save &c" + id);
}

View File

@ -11,39 +11,32 @@ import com.intellectualcrafters.plot.uuid.UUIDWrapper;
import com.plotsquared.bukkit.object.BukkitOfflinePlayer;
import com.plotsquared.bukkit.object.BukkitPlayer;
public class DefaultUUIDWrapper extends UUIDWrapper
{
public class DefaultUUIDWrapper extends UUIDWrapper {
@Override
public UUID getUUID(final PlotPlayer player)
{
public UUID getUUID(final PlotPlayer player) {
return ((BukkitPlayer) player).player.getUniqueId();
}
@Override
public UUID getUUID(final OfflinePlotPlayer player)
{
public UUID getUUID(final OfflinePlotPlayer player) {
return player.getUUID();
}
@Override
public OfflinePlotPlayer getOfflinePlayer(final UUID uuid)
{
public OfflinePlotPlayer getOfflinePlayer(final UUID uuid) {
return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(uuid));
}
@Override
public UUID getUUID(final String name)
{
public UUID getUUID(final String name) {
return Bukkit.getOfflinePlayer(name).getUniqueId();
}
@Override
public OfflinePlotPlayer[] getOfflinePlayers()
{
public OfflinePlotPlayer[] getOfflinePlayers() {
final OfflinePlayer[] ops = Bukkit.getOfflinePlayers();
final BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length];
for (int i = 0; i < ops.length; i++)
{
for (int i = 0; i < ops.length; i++) {
toReturn[i] = new BukkitOfflinePlayer(ops[i]);
}
return toReturn;

View File

@ -31,106 +31,81 @@ import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.util.UUIDHandlerImplementation;
import com.intellectualcrafters.plot.uuid.UUIDWrapper;
public class FileUUIDHandler extends UUIDHandlerImplementation
{
public FileUUIDHandler(final UUIDWrapper wrapper)
{
public class FileUUIDHandler extends UUIDHandlerImplementation {
public FileUUIDHandler(final UUIDWrapper wrapper) {
super(wrapper);
}
@Override
public boolean startCaching(final Runnable whenDone)
{
if (!super.startCaching(whenDone)) { return false; }
public boolean startCaching(final Runnable whenDone) {
if (!super.startCaching(whenDone)) {
return false;
}
return cache(whenDone);
}
public boolean cache(final Runnable whenDone)
{
public boolean cache(final Runnable whenDone) {
final File container = Bukkit.getWorldContainer();
final List<World> worlds = Bukkit.getWorlds();
final String world;
if (worlds.size() == 0)
{
if (worlds.size() == 0) {
world = "world";
}
else
{
} else {
world = worlds.get(0).getName();
}
TaskManager.runTaskAsync(new Runnable()
{
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run()
{
public void run() {
PS.debug(C.PREFIX.s() + "&6Starting player data caching for: " + world);
final File uuidfile = new File(PS.get().IMP.getDirectory(), "uuids.txt");
if (uuidfile.exists())
{
try
{
if (uuidfile.exists()) {
try {
final List<String> lines = Files.readAllLines(uuidfile.toPath(), StandardCharsets.UTF_8);
for (String line : lines)
{
try
{
for (String line : lines) {
try {
line = line.trim();
if (line.length() == 0)
{
if (line.length() == 0) {
continue;
}
line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", "");
final String[] split = line.split("\\|");
final String name = split[0];
if ((name.length() == 0) || (name.length() > 16) || !StringMan.isAlphanumericUnd(name))
{
if ((name.length() == 0) || (name.length() > 16) || !StringMan.isAlphanumericUnd(name)) {
continue;
}
final UUID uuid = uuidWrapper.getUUID(name);
if (uuid == null)
{
if (uuid == null) {
continue;
}
UUIDHandler.add(new StringWrapper(name), uuid);
}
catch (final Exception e2)
{
} catch (final Exception e2) {
e2.printStackTrace();
}
}
}
catch (final IOException e)
{
} catch (final IOException e) {
e.printStackTrace();
}
}
if (Settings.TWIN_MODE_UUID)
{
if (Settings.TWIN_MODE_UUID) {
final HashBiMap<StringWrapper, UUID> toAdd = HashBiMap.create(new HashMap<StringWrapper, UUID>());
toAdd.put(new StringWrapper("*"), DBFunc.everyone);
final HashSet<UUID> all = UUIDHandler.getAllUUIDS();
PS.debug("&aFast mode UUID caching enabled!");
final File playerdataFolder = new File(container, world + File.separator + "playerdata");
final String[] dat = playerdataFolder.list(new FilenameFilter()
{
final String[] dat = playerdataFolder.list(new FilenameFilter() {
@Override
public boolean accept(final File f, final String s)
{
public boolean accept(final File f, final String s) {
return s.endsWith(".dat");
}
});
final boolean check = all.size() == 0;
if (dat != null)
{
for (final String current : dat)
{
if (dat != null) {
for (final String current : dat) {
final String s = current.replaceAll(".dat$", "");
try
{
try {
final UUID uuid = UUID.fromString(s);
if (check || all.remove(uuid))
{
if (check || all.remove(uuid)) {
final File file = new File(playerdataFolder + File.separator + current);
final InputSupplier<FileInputStream> is = com.google.common.io.Files.newInputStreamSupplier(file);
final NbtFactory.NbtCompound compound = NbtFactory.fromStream(is, NbtFactory.StreamOptions.GZIP_COMPRESSION);
@ -140,25 +115,19 @@ public class FileUUIDHandler extends UUIDHandlerImplementation
ExpireManager.dates.put(uuid, last);
toAdd.put(new StringWrapper(name), uuid);
}
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
PS.debug(C.PREFIX.s() + "Invalid playerdata: " + current);
}
}
}
add(toAdd);
if (all.size() == 0)
{
if (whenDone != null)
{
if (all.size() == 0) {
if (whenDone != null) {
whenDone.run();
}
return;
}
else
{
} else {
PS.debug("Failed to cache: " + all.size() + " uuids - slowly processing all files");
}
}
@ -170,30 +139,22 @@ public class FileUUIDHandler extends UUIDHandlerImplementation
final HashSet<UUID> uuids = new HashSet<>();
final HashSet<String> names = new HashSet<>();
File playerdataFolder = null;
for (final String worldname : worlds)
{
for (final String worldname : worlds) {
// Getting UUIDs
playerdataFolder = new File(container, worldname + File.separator + "playerdata");
String[] dat = playerdataFolder.list(new FilenameFilter()
{
String[] dat = playerdataFolder.list(new FilenameFilter() {
@Override
public boolean accept(final File f, final String s)
{
public boolean accept(final File f, final String s) {
return s.endsWith(".dat");
}
});
if ((dat != null) && (dat.length != 0))
{
for (final String current : dat)
{
if ((dat != null) && (dat.length != 0)) {
for (final String current : dat) {
final String s = current.replaceAll(".dat$", "");
try
{
try {
final UUID uuid = UUID.fromString(s);
uuids.add(uuid);
}
catch (final Exception e)
{
} catch (final Exception e) {
PS.debug(C.PREFIX.s() + "Invalid playerdata: " + current);
}
}
@ -201,41 +162,31 @@ public class FileUUIDHandler extends UUIDHandlerImplementation
}
// Getting names
final File playersFolder = new File(worldname + File.separator + "players");
dat = playersFolder.list(new FilenameFilter()
{
dat = playersFolder.list(new FilenameFilter() {
@Override
public boolean accept(final File f, final String s)
{
public boolean accept(final File f, final String s) {
return s.endsWith(".dat");
}
});
if ((dat != null) && (dat.length != 0))
{
for (final String current : dat)
{
if ((dat != null) && (dat.length != 0)) {
for (final String current : dat) {
names.add(current.replaceAll(".dat$", ""));
}
break;
}
}
for (UUID uuid : uuids)
{
try
{
for (UUID uuid : uuids) {
try {
final File file = new File(playerdataFolder + File.separator + uuid.toString() + ".dat");
final InputSupplier<FileInputStream> is = com.google.common.io.Files.newInputStreamSupplier(file);
final NbtFactory.NbtCompound compound = NbtFactory.fromStream(is, NbtFactory.StreamOptions.GZIP_COMPRESSION);
final NbtFactory.NbtCompound bukkit = (NbtFactory.NbtCompound) compound.get("bukkit");
final String name = (String) bukkit.get("lastKnownName");
final long last = (long) bukkit.get("lastPlayed");
if (Settings.OFFLINE_MODE)
{
if (Settings.UUID_LOWERCASE && !name.toLowerCase().equals(name))
{
if (Settings.OFFLINE_MODE) {
if (Settings.UUID_LOWERCASE && !name.toLowerCase().equals(name)) {
uuid = uuidWrapper.getUUID(name);
}
else
{
} else {
final long most = (long) compound.get("UUIDMost");
final long least = (long) compound.get("UUIDLeast");
uuid = new UUID(most, least);
@ -243,26 +194,20 @@ public class FileUUIDHandler extends UUIDHandlerImplementation
}
ExpireManager.dates.put(uuid, last);
toAdd.put(new StringWrapper(name), uuid);
}
catch (final Throwable e)
{
} catch (final Throwable e) {
PS.debug(C.PREFIX.s() + "&6Invalid playerdata: " + uuid.toString() + ".dat");
}
}
for (final String name : names)
{
for (final String name : names) {
final UUID uuid = uuidWrapper.getUUID(name);
final StringWrapper nameWrap = new StringWrapper(name);
toAdd.put(nameWrap, uuid);
}
if (getUUIDMap().size() == 0)
{
for (final OfflinePlotPlayer op : uuidWrapper.getOfflinePlayers())
{
if (getUUIDMap().size() == 0) {
for (final OfflinePlotPlayer op : uuidWrapper.getOfflinePlayers()) {
final long last = op.getLastPlayed();
if (last != 0)
{
if (last != 0) {
final String name = op.getName();
final StringWrapper wrap = new StringWrapper(name);
final UUID uuid = uuidWrapper.getUUID(op);
@ -272,23 +217,19 @@ public class FileUUIDHandler extends UUIDHandlerImplementation
}
}
add(toAdd);
if (whenDone != null)
{
if (whenDone != null) {
whenDone.run();
}
}
});
return true;
}
@Override
public void fetchUUID(final String name, final RunnableVal<UUID> ifFetch)
{
TaskManager.runTaskAsync(new Runnable()
{
public void fetchUUID(final String name, final RunnableVal<UUID> ifFetch) {
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run()
{
public void run() {
ifFetch.value = uuidWrapper.getUUID(name);
TaskManager.runTask(ifFetch);
}

View File

@ -18,109 +18,89 @@ import com.intellectualcrafters.plot.object.StringWrapper;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.bukkit.object.BukkitOfflinePlayer;
public class LowerOfflineUUIDWrapper extends OfflineUUIDWrapper
{
public class LowerOfflineUUIDWrapper extends OfflineUUIDWrapper {
private Method getOnline = null;
private final Object[] arg = new Object[0];
public LowerOfflineUUIDWrapper()
{
try
{
public LowerOfflineUUIDWrapper() {
try {
getOnline = Server.class.getMethod("getOnlinePlayers", new Class[0]);
}
catch (final NoSuchMethodException e)
{
} catch (final NoSuchMethodException e) {
e.printStackTrace();
}
catch (final SecurityException e)
{
} catch (final SecurityException e) {
e.printStackTrace();
}
}
@Override
public UUID getUUID(final PlotPlayer player)
{
public UUID getUUID(final PlotPlayer player) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8));
}
@Override
public UUID getUUID(final OfflinePlotPlayer player)
{
public UUID getUUID(final OfflinePlotPlayer player) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8));
}
@Override
public UUID getUUID(final OfflinePlayer player)
{
public UUID getUUID(final OfflinePlayer player) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8));
}
@Override
public OfflinePlotPlayer getOfflinePlayer(final UUID uuid)
{
public OfflinePlotPlayer getOfflinePlayer(final UUID uuid) {
final BiMap<UUID, StringWrapper> map = UUIDHandler.getUuidMap().inverse();
String name;
try
{
try {
name = map.get(uuid).value;
}
catch (final NullPointerException e)
{
} catch (final NullPointerException e) {
name = null;
}
if (name != null)
{
if (name != null) {
final OfflinePlayer op = Bukkit.getOfflinePlayer(name);
if (op.hasPlayedBefore()) { return new BukkitOfflinePlayer(op); }
if (op.hasPlayedBefore()) {
return new BukkitOfflinePlayer(op);
}
}
for (final OfflinePlayer player : Bukkit.getOfflinePlayers())
{
if (getUUID(player).equals(uuid)) { return new BukkitOfflinePlayer(player); }
for (final OfflinePlayer player : Bukkit.getOfflinePlayers()) {
if (getUUID(player).equals(uuid)) {
return new BukkitOfflinePlayer(player);
}
}
return null;
}
@Override
public Player[] getOnlinePlayers()
{
if (getOnline == null) { return Bukkit.getOnlinePlayers().toArray(new Player[0]); }
try
{
public Player[] getOnlinePlayers() {
if (getOnline == null) {
return Bukkit.getOnlinePlayers().toArray(new Player[0]);
}
try {
final Object players = getOnline.invoke(Bukkit.getServer(), arg);
if (players instanceof Player[])
{
if (players instanceof Player[]) {
return (Player[]) players;
}
else
{
} else {
@SuppressWarnings("unchecked")
final Collection<? extends Player> p = (Collection<? extends Player>) players;
return p.toArray(new Player[0]);
}
}
catch (final Exception e)
{
} catch (final Exception e) {
PS.debug("Failed to resolve online players");
getOnline = null;
return Bukkit.getOnlinePlayers().toArray(new Player[0]);
}
}
@Override
public UUID getUUID(final String name)
{
public UUID getUUID(final String name) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + name.toLowerCase()).getBytes(Charsets.UTF_8));
}
@Override
public OfflinePlotPlayer[] getOfflinePlayers()
{
public OfflinePlotPlayer[] getOfflinePlayers() {
final OfflinePlayer[] ops = Bukkit.getOfflinePlayers();
final BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length];
for (int i = 0; i < ops.length; i++)
{
for (int i = 0; i < ops.length; i++) {
toReturn[i] = new BukkitOfflinePlayer(ops[i]);
}
return toReturn;

View File

@ -19,107 +19,87 @@ import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.uuid.UUIDWrapper;
import com.plotsquared.bukkit.object.BukkitOfflinePlayer;
public class OfflineUUIDWrapper extends UUIDWrapper
{
public class OfflineUUIDWrapper extends UUIDWrapper {
private Method getOnline = null;
private final Object[] arg = new Object[0];
public OfflineUUIDWrapper()
{
try
{
public OfflineUUIDWrapper() {
try {
getOnline = Server.class.getMethod("getOnlinePlayers", new Class[0]);
}
catch (final NoSuchMethodException e)
{
} catch (final NoSuchMethodException e) {
e.printStackTrace();
}
catch (final SecurityException e)
{
} catch (final SecurityException e) {
e.printStackTrace();
}
}
@Override
public UUID getUUID(final PlotPlayer player)
{
public UUID getUUID(final PlotPlayer player) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8));
}
@Override
public UUID getUUID(final OfflinePlotPlayer player)
{
public UUID getUUID(final OfflinePlotPlayer player) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8));
}
public UUID getUUID(final OfflinePlayer player)
{
public UUID getUUID(final OfflinePlayer player) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8));
}
@Override
public OfflinePlotPlayer getOfflinePlayer(final UUID uuid)
{
public OfflinePlotPlayer getOfflinePlayer(final UUID uuid) {
final BiMap<UUID, StringWrapper> map = UUIDHandler.getUuidMap().inverse();
String name;
try
{
try {
name = map.get(uuid).value;
}
catch (final NullPointerException e)
{
} catch (final NullPointerException e) {
name = null;
}
if (name != null)
{
if (name != null) {
final OfflinePlayer op = Bukkit.getOfflinePlayer(name);
if (op.hasPlayedBefore()) { return new BukkitOfflinePlayer(op); }
if (op.hasPlayedBefore()) {
return new BukkitOfflinePlayer(op);
}
}
for (final OfflinePlayer player : Bukkit.getOfflinePlayers())
{
if (getUUID(player).equals(uuid)) { return new BukkitOfflinePlayer(player); }
for (final OfflinePlayer player : Bukkit.getOfflinePlayers()) {
if (getUUID(player).equals(uuid)) {
return new BukkitOfflinePlayer(player);
}
}
return null;
}
public Player[] getOnlinePlayers()
{
if (getOnline == null) { return Bukkit.getOnlinePlayers().toArray(new Player[0]); }
try
{
public Player[] getOnlinePlayers() {
if (getOnline == null) {
return Bukkit.getOnlinePlayers().toArray(new Player[0]);
}
try {
final Object players = getOnline.invoke(Bukkit.getServer(), arg);
if (players instanceof Player[])
{
if (players instanceof Player[]) {
return (Player[]) players;
}
else
{
} else {
@SuppressWarnings("unchecked")
final Collection<? extends Player> p = (Collection<? extends Player>) players;
return p.toArray(new Player[0]);
}
}
catch (final Exception e)
{
} catch (final Exception e) {
PS.debug("Failed to resolve online players");
getOnline = null;
return Bukkit.getOnlinePlayers().toArray(new Player[0]);
}
}
@Override
public UUID getUUID(final String name)
{
public UUID getUUID(final String name) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8));
}
@Override
public OfflinePlotPlayer[] getOfflinePlayers()
{
public OfflinePlotPlayer[] getOfflinePlayers() {
final OfflinePlayer[] ops = Bukkit.getOfflinePlayers();
final BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length];
for (int i = 0; i < ops.length; i++)
{
for (int i = 0; i < ops.length; i++) {
toReturn[i] = new BukkitOfflinePlayer(ops[i]);
}
return toReturn;

View File

@ -29,72 +29,57 @@ import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.util.UUIDHandlerImplementation;
import com.intellectualcrafters.plot.uuid.UUIDWrapper;
public class SQLUUIDHandler extends UUIDHandlerImplementation
{
public SQLUUIDHandler(final UUIDWrapper wrapper)
{
public class SQLUUIDHandler extends UUIDHandlerImplementation {
public SQLUUIDHandler(final UUIDWrapper wrapper) {
super(wrapper);
_sqLite = new SQLite("./plugins/PlotSquared/usercache.db");
try
{
try {
_sqLite.openConnection();
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
}
try
{
final PreparedStatement stmt = getConnection()
.prepareStatement("CREATE TABLE IF NOT EXISTS `usercache` (uuid VARCHAR(32) NOT NULL, username VARCHAR(32) NOT NULL, PRIMARY KEY (uuid, username))");
try {
final PreparedStatement stmt = getConnection().prepareStatement(
"CREATE TABLE IF NOT EXISTS `usercache` (uuid VARCHAR(32) NOT NULL, username VARCHAR(32) NOT NULL, PRIMARY KEY (uuid, username))");
stmt.execute();
stmt.close();
}
catch (final SQLException e)
{
} catch (final SQLException e) {
e.printStackTrace();
}
startCaching(null);
}
private class SQLUUIDHandlerException extends RuntimeException
{
SQLUUIDHandlerException(final String s, final Throwable c)
{
private class SQLUUIDHandlerException extends RuntimeException {
SQLUUIDHandlerException(final String s, final Throwable c) {
super("SQLUUIDHandler caused an exception: " + s, c);
}
}
private final SQLite _sqLite;
private Connection getConnection()
{
synchronized (_sqLite)
{
private Connection getConnection() {
synchronized (_sqLite) {
return _sqLite.getConnection();
}
}
@Override
public boolean startCaching(final Runnable whenDone)
{
if (!super.startCaching(whenDone)) { return false; }
TaskManager.runTaskAsync(new Runnable()
{
public boolean startCaching(final Runnable whenDone) {
if (!super.startCaching(whenDone)) {
return false;
}
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run()
{
try
{
public void run() {
try {
final HashBiMap<StringWrapper, UUID> toAdd = HashBiMap.create(new HashMap<StringWrapper, UUID>());
final PreparedStatement statement = getConnection().prepareStatement("SELECT `uuid`, `username` FROM `usercache`");
final ResultSet resultSet = statement.executeQuery();
StringWrapper username;
UUID uuid;
while (resultSet.next())
{
while (resultSet.next()) {
username = new StringWrapper(resultSet.getString("username"));
uuid = UUID.fromString(resultSet.getString("uuid"));
toAdd.put(new StringWrapper(username.value), uuid);
@ -102,176 +87,137 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation
statement.close();
add(toAdd);
add(new StringWrapper("*"), DBFunc.everyone);
// This should be called as long as there are some unknown plots
final List<UUID> toFetch = new ArrayList<>();
for (final UUID u : UUIDHandler.getAllUUIDS())
{
if (!uuidExists(u))
{
for (final UUID u : UUIDHandler.getAllUUIDS()) {
if (!uuidExists(u)) {
toFetch.add(u);
}
}
if (toFetch.isEmpty())
{
if (whenDone != null)
{
if (toFetch.isEmpty()) {
if (whenDone != null) {
whenDone.run();
}
return;
}
final FileUUIDHandler fileHandler = new FileUUIDHandler(SQLUUIDHandler.this.uuidWrapper);
fileHandler.startCaching(new Runnable()
{
fileHandler.startCaching(new Runnable() {
@Override
public void run()
{
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.OFFLINE_MODE)
{
if (whenDone != null)
{
if (Settings.OFFLINE_MODE) {
if (whenDone != null) {
whenDone.run();
}
return;
}
if (!Settings.OFFLINE_MODE)
{
if (!Settings.OFFLINE_MODE) {
PS.debug(C.PREFIX.s() + "&cWill fetch &6" + toFetch.size() + "&c from mojang!");
int i = 0;
final Iterator<UUID> iterator = toFetch.iterator();
while (iterator.hasNext())
{
while (iterator.hasNext()) {
final StringBuilder url = new StringBuilder("http://api.intellectualsites.com/uuid/?user=");
final List<UUID> currentIteration = new ArrayList<>();
while ((i++ <= 15) && iterator.hasNext())
{
while ((i++ <= 15) && iterator.hasNext()) {
final UUID _uuid = iterator.next();
url.append(_uuid.toString());
if (iterator.hasNext())
{
if (iterator.hasNext()) {
url.append(",");
}
currentIteration.add(_uuid);
}
PS.debug(C.PREFIX.s() + "&cWill attempt to fetch &6" + currentIteration.size() + "&c uuids from: &6" + url.toString());
try
{
try {
final HttpURLConnection connection = (HttpURLConnection) new URL(url.toString()).openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
final StringBuilder rawJSON = new StringBuilder();
while ((line = reader.readLine()) != null)
{
while ((line = reader.readLine()) != null) {
rawJSON.append(line);
}
reader.close();
final JSONObject object = new JSONObject(rawJSON.toString());
for (final UUID _u : currentIteration)
{
for (final UUID _u : currentIteration) {
final Object o = object.getJSONObject(_u.toString().replace("-", "")).get("username");
if ((o == null) || !(o instanceof String))
{
if ((o == null) || !(o instanceof String)) {
continue;
}
add(new StringWrapper(o.toString()), _u);
}
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
}
i = 0;
}
}
if (whenDone != null)
{
if (whenDone != null) {
whenDone.run();
}
}
});
}
catch (final SQLException e)
{
} catch (final SQLException e) {
throw new SQLUUIDHandlerException("Couldn't select :s", e);
}
}
});
return true;
}
@Override
public void fetchUUID(final String name, final RunnableVal<UUID> ifFetch)
{
public void fetchUUID(final String name, final RunnableVal<UUID> ifFetch) {
PS.debug(C.PREFIX.s() + "UUID for '" + name + "' was null. We'll cache this from the mojang servers!");
TaskManager.runTaskAsync(new Runnable()
{
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run()
{
public void run() {
final String url = "http://api.intellectualsites.com/uuid/?user=" + name;
try
{
try {
final HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
final StringBuilder rawJSON = new StringBuilder();
while ((line = reader.readLine()) != null)
{
while ((line = reader.readLine()) != null) {
rawJSON.append(line);
}
reader.close();
final JSONObject object = new JSONObject(rawJSON.toString());
ifFetch.value = UUID.fromString(object.getJSONObject(name).getString("dashed"));
add(new StringWrapper(name), ifFetch.value);
}
catch (final IOException e)
{
} catch (final IOException e) {
e.printStackTrace();
}
TaskManager.runTask(ifFetch);
}
});
}
@Override
public void handleShutdown()
{
public void handleShutdown() {
super.handleShutdown();
try
{
try {
getConnection().close();
}
catch (final SQLException e)
{
} catch (final SQLException e) {
throw new SQLUUIDHandlerException("Couldn't close database connection", e);
}
}
@Override
public boolean add(final StringWrapper name, final UUID uuid)
{
public boolean add(final StringWrapper name, final UUID uuid) {
// Ignoring duplicates
if (super.add(name, uuid))
{
TaskManager.runTaskAsync(new Runnable()
{
if (super.add(name, uuid)) {
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run()
{
try
{
public void run() {
try {
final PreparedStatement statement = getConnection().prepareStatement("INSERT INTO usercache (`uuid`, `username`) VALUES(?, ?)");
statement.setString(1, uuid.toString());
statement.setString(2, name.toString());
statement.execute();
PS.debug(C.PREFIX.s() + "&cAdded '&6" + uuid + "&c' - '&6" + name + "&c'");
}
catch (final SQLException e)
{
} catch (final SQLException e) {
e.printStackTrace();
}
}
@ -280,66 +226,53 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation
}
return false;
}
/**
* This isn't used as any UUID that is unknown is bulk cached (in lots of 16)
* @param uuid
* @return
*/
@Deprecated
public String getName__unused__(final UUID uuid)
{
public String getName__unused__(final UUID uuid) {
PS.debug(C.PREFIX.s() + "Name for '" + uuid + "' was null. We'll cache this from the mojang servers!");
TaskManager.runTaskAsync(new Runnable()
{
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run()
{
public void run() {
final String url = "http://api.intellectualsites.com/uuid/?user=" + uuid;
try
{
try {
final HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
final StringBuilder rawJSON = new StringBuilder();
while ((line = reader.readLine()) != null)
{
while ((line = reader.readLine()) != null) {
rawJSON.append(line);
}
reader.close();
final JSONObject object = new JSONObject(rawJSON.toString());
final String username = object.getJSONObject(uuid.toString().replace("-", "")).getString("username");
add(new StringWrapper(username), uuid);
}
catch (final IOException e)
{
} catch (final IOException e) {
e.printStackTrace();
}
}
});
return null;
}
@Override
public void rename(final UUID uuid, final StringWrapper name)
{
public void rename(final UUID uuid, final StringWrapper name) {
super.rename(uuid, name);
TaskManager.runTaskAsync(new Runnable()
{
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run()
{
try
{
public void run() {
try {
final PreparedStatement statement = getConnection().prepareStatement("UPDATE usercache SET `username`=? WHERE `uuid`=?");
statement.setString(1, name.value);
statement.setString(2, uuid.toString());
statement.execute();
PS.debug(C.PREFIX.s() + "Name change for '" + uuid + "' to '" + name.value + "'");
}
catch (final SQLException e)
{
} catch (final SQLException e) {
e.printStackTrace();
}
}

View File

@ -5,102 +5,79 @@ import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.util.MainUtil;
public abstract class Argument<T>
{
public abstract class Argument<T> {
private final String name;
private final T example;
public Argument(final String name, final T example)
{
public Argument(final String name, final T example) {
this.name = name;
this.example = example;
}
public abstract T parse(final String in);
@Override
public final String toString()
{
public final String toString() {
return this.getName();
}
public final String getName()
{
public final String getName() {
return this.name;
}
public final T getExample()
{
public final T getExample() {
return this.example;
}
public static final Argument<Integer> Integer = new Argument<Integer>("int", 16)
{
public static final Argument<Integer> Integer = new Argument<Integer>("int", 16) {
@Override
public Integer parse(final String in)
{
public Integer parse(final String in) {
Integer value = null;
try
{
try {
value = java.lang.Integer.parseInt(in);
}
catch (final Exception ignored)
{}
} catch (final Exception ignored) {}
return value;
}
};
public static final Argument<Boolean> Boolean = new Argument<Boolean>("boolean", true)
{
public static final Argument<Boolean> Boolean = new Argument<Boolean>("boolean", true) {
@Override
public Boolean parse(final String in)
{
public Boolean parse(final String in) {
Boolean value = null;
if (in.equalsIgnoreCase("true") || in.equalsIgnoreCase("Yes") || in.equalsIgnoreCase("1"))
{
if (in.equalsIgnoreCase("true") || in.equalsIgnoreCase("Yes") || in.equalsIgnoreCase("1")) {
value = true;
}
else if (in.equalsIgnoreCase("false") || in.equalsIgnoreCase("No") || in.equalsIgnoreCase("0"))
{
} else if (in.equalsIgnoreCase("false") || in.equalsIgnoreCase("No") || in.equalsIgnoreCase("0")) {
value = false;
}
return value;
}
};
public static final Argument<String> String = new Argument<String>("String", "Example")
{
public static final Argument<String> String = new Argument<String>("String", "Example") {
@Override
public String parse(final String in)
{
public String parse(final String in) {
return in;
}
};
public static Argument<String> PlayerName = new Argument<String>("PlayerName", "Dinnerbone")
{
public static Argument<String> PlayerName = new Argument<String>("PlayerName", "Dinnerbone") {
@Override
public String parse(final String in)
{
public String parse(final String in) {
return in.length() <= 16 ? in : null;
}
};
public static Argument<PlotId> PlotID = new Argument<PlotId>("PlotID", new PlotId(-6, 3))
{
public static Argument<PlotId> PlotID = new Argument<PlotId>("PlotID", new PlotId(-6, 3)) {
@Override
public PlotId parse(final String in)
{
public PlotId parse(final String in) {
return PlotId.fromString(in);
}
};
public static Argument<Plot> Plot = new Argument<Plot>("Plot", new Plot("plotworld", new PlotId(3, -6), null))
{
public static Argument<Plot> Plot = new Argument<Plot>("Plot", new Plot("plotworld", new PlotId(3, -6), null)) {
@Override
public Plot parse(final String in)
{
public Plot parse(final String in) {
return MainUtil.getPlotFromString(ConsolePlayer.getConsole(), in, false);
}
};

View File

@ -9,67 +9,58 @@ import java.util.Set;
import com.intellectualcrafters.plot.commands.CommandCategory;
import com.intellectualcrafters.plot.commands.RequiredType;
public abstract class Command<E extends CommandCaller> extends CommandManager
{
public abstract class Command<E extends CommandCaller> extends CommandManager {
private RequiredType requiredType = RequiredType.NONE;
private String command, usage = "", description = "", permission = "";
private Set<String> aliases = new HashSet<>();
private CommandCategory category;
protected Argument<?>[] requiredArguments;
public Command()
{
public Command() {
super(null, new ArrayList<Command>());
}
public Command(final String command)
{
public Command(final String command) {
super(null, new ArrayList<Command>());
this.command = command;
}
public Command(final String command, final String usage)
{
public Command(final String command, final String usage) {
super(null, new ArrayList<Command>());
this.command = command;
this.usage = usage;
}
public Command(final String command, final String usage, final String description)
{
public Command(final String command, final String usage, final String description) {
super(null, new ArrayList<Command>());
this.command = command;
this.usage = usage;
this.description = description;
}
public Command(final String command, final String usage, final String description, final String permission)
{
public Command(final String command, final String usage, final String description, final String permission) {
super(null, new ArrayList<Command>());
this.command = command;
this.usage = usage;
this.description = description;
this.permission = permission;
}
public Command(final String command, final String[] aliases, final String usage)
{
public Command(final String command, final String[] aliases, final String usage) {
super(null, new ArrayList<Command>());
this.command = command;
this.aliases = new HashSet<>(Arrays.asList(aliases));
this.usage = usage;
}
public Command(final String command, final String[] aliases)
{
public Command(final String command, final String[] aliases) {
super(null, new ArrayList<Command>());
this.command = command;
this.aliases = new HashSet<>(Arrays.asList(aliases));
}
public Command(final String command, final String usage, final String description, final String permission, final String[] aliases, final RequiredType requiredType)
{
public Command(final String command, final String usage, final String description, final String permission, final String[] aliases, final RequiredType requiredType) {
super(null, new ArrayList<Command>());
this.command = command;
this.usage = usage;
@ -78,16 +69,16 @@ public abstract class Command<E extends CommandCaller> extends CommandManager
this.aliases = new HashSet<>(Arrays.asList(aliases));
this.requiredType = requiredType;
}
final public RequiredType getRequiredType()
{
final public RequiredType getRequiredType() {
return this.requiredType;
}
final protected void create()
{
final protected void create() {
final Annotation annotation = getClass().getAnnotation(CommandDeclaration.class);
if (annotation == null) { throw new RuntimeException("Command does not have a CommandDeclaration"); }
if (annotation == null) {
throw new RuntimeException("Command does not have a CommandDeclaration");
}
final CommandDeclaration declaration = (CommandDeclaration) annotation;
this.command = declaration.command();
this.usage = declaration.usage();
@ -98,87 +89,89 @@ public abstract class Command<E extends CommandCaller> extends CommandManager
this.requiredType = declaration.requiredType();
this.category = declaration.category();
}
@Override
final public String toString()
{
final public String toString() {
return this.command;
}
public abstract boolean onCommand(final E plr, final String[] arguments);
final public int handle(final E plr, final String[] args)
{
if (args.length == 0) { return super.handle(plr, ""); }
final public int handle(final E plr, final String[] args) {
if (args.length == 0) {
return super.handle(plr, "");
}
final StringBuilder builder = new StringBuilder();
for (final String s : args)
{
for (final String s : args) {
builder.append(s).append(" ");
}
final String s = builder.substring(0, builder.length() - 1);
return super.handle(plr, s);
}
final public String getCommand()
{
final public String getCommand() {
return this.command;
}
public String getUsage()
{
if (this.usage.length() == 0) { return "/{label} " + command; }
public String getUsage() {
if (this.usage.length() == 0) {
return "/{label} " + command;
}
return this.usage;
}
final public String getPermission()
{
if ((this.permission == null) || (this.permission.length() == 0))
{
final public String getPermission() {
if ((this.permission == null) || (this.permission.length() == 0)) {
this.permission = "plots." + command.toLowerCase();
}
return this.permission;
}
public String getDescription()
{
public String getDescription() {
return this.description;
}
final public Set<String> getAliases()
{
final public Set<String> getAliases() {
return this.aliases;
}
final public Argument<?>[] getRequiredArguments()
{
if (this.requiredArguments == null) { return new Argument<?>[0]; }
final public Argument<?>[] getRequiredArguments() {
if (this.requiredArguments == null) {
return new Argument<?>[0];
}
return this.requiredArguments;
}
final public CommandCategory getCategory()
{
if (category == null) { return CommandCategory.DEBUG; }
final public CommandCategory getCategory() {
if (category == null) {
return CommandCategory.DEBUG;
}
return this.category;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj) { return true; }
if (obj == null) { return false; }
if (getClass() != obj.getClass()) { return false; }
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Command<?> other = (Command<?>) obj;
if (this.hashCode() != other.hashCode()) { return false; }
if (this.hashCode() != other.hashCode()) {
return false;
}
return this.command.equals(other.command);
}
private int hash;
@Override
public int hashCode()
{
if (hash == 0)
{
public int hashCode() {
if (hash == 0) {
hash = getCommand().hashCode();
}
return hash;

View File

@ -3,13 +3,12 @@ package com.plotsquared.general.commands;
import com.intellectualcrafters.plot.commands.RequiredType;
import com.intellectualcrafters.plot.config.C;
public interface CommandCaller
{
public interface CommandCaller {
void sendMessage(final String message);
void sendMessage(final C c, final String... args);
boolean hasPermission(final String perm);
RequiredType getSuperCaller();
}

View File

@ -10,20 +10,19 @@ import com.intellectualcrafters.plot.commands.RequiredType;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface CommandDeclaration
{
public @interface CommandDeclaration {
String command();
String[] aliases() default {};
String permission() default "";
String usage() default "";
String description() default "";
RequiredType requiredType() default RequiredType.NONE;
CommandCategory category();
}

View File

@ -2,31 +2,26 @@ package com.plotsquared.general.commands;
import java.lang.reflect.Field;
public class CommandHandlingOutput
{
public class CommandHandlingOutput {
public static int CALLER_OF_WRONG_TYPE = -6;
public static int NOT_COMMAND = -5;
public static int NOT_FOUND = -4;
public static int NOT_PERMITTED = -3;
public static int ERROR = -2;
public static int WRONG_USAGE = -1;
public static int SUCCESS = 1;
public static String nameField(final int code)
{
public static String nameField(final int code) {
final Field[] fields = CommandHandlingOutput.class.getDeclaredFields();
for (final Field field : fields)
{
if (field.getGenericType() == Integer.TYPE)
{
try
{
if ((Integer) field.get(CommandHandlingOutput.class) == code) { return field.getName(); }
}
catch (final IllegalAccessException e)
{
for (final Field field : fields) {
if (field.getGenericType() == Integer.TYPE) {
try {
if ((Integer) field.get(CommandHandlingOutput.class) == code) {
return field.getName();
}
} catch (final IllegalAccessException e) {
e.printStackTrace();
}
}

View File

@ -11,73 +11,57 @@ import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.util.Permissions;
@SuppressWarnings("unused")
public class CommandManager<T extends CommandCaller>
{
public class CommandManager<T extends CommandCaller> {
protected final ConcurrentHashMap<String, Command<T>> commands;
protected final Character initialCharacter;
public CommandManager()
{
public CommandManager() {
this('/', new ArrayList<Command<T>>());
}
public CommandManager(final Character initialCharacter, final List<Command<T>> commands)
{
public CommandManager(final Character initialCharacter, final List<Command<T>> commands) {
this.commands = new ConcurrentHashMap<>();
for (final Command<T> command : commands)
{
for (final Command<T> command : commands) {
addCommand(command);
}
this.initialCharacter = initialCharacter;
}
final public void addCommand(final Command<T> command)
{
if (command.getCommand() == null)
{
final public void addCommand(final Command<T> command) {
if (command.getCommand() == null) {
command.create();
}
this.commands.put(command.getCommand().toLowerCase(), command);
for (final String alias : command.getAliases())
{
for (final String alias : command.getAliases()) {
this.commands.put(alias.toLowerCase(), command);
}
}
final public Command<T> getCommand(final String command)
{
final public Command<T> getCommand(final String command) {
return commands.get(command);
}
final public boolean createCommand(final Command<T> command)
{
try
{
final public boolean createCommand(final Command<T> command) {
try {
command.create();
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
return false;
}
if (command.getCommand() != null)
{
if (command.getCommand() != null) {
addCommand(command);
return true;
}
return false;
}
final public ArrayList<Command<T>> getCommands()
{
final public ArrayList<Command<T>> getCommands() {
final HashSet<Command<T>> set = new HashSet<>(this.commands.values());
final ArrayList<Command<T>> result = new ArrayList<>(set);
Collections.sort(result, new Comparator<Command<T>>()
{
Collections.sort(result, new Comparator<Command<T>>() {
@Override
public int compare(final Command<T> a, final Command<T> b)
{
public int compare(final Command<T> a, final Command<T> b) {
if (a == b) {
return 0;
}
@ -92,87 +76,76 @@ public class CommandManager<T extends CommandCaller>
});
return result;
}
final public ArrayList<String> getCommandLabels(final ArrayList<Command<T>> cmds)
{
final public ArrayList<String> getCommandLabels(final ArrayList<Command<T>> cmds) {
final ArrayList<String> labels = new ArrayList<>(cmds.size());
for (final Command<T> cmd : cmds)
{
for (final Command<T> cmd : cmds) {
labels.add(cmd.getCommand());
}
return labels;
}
public int handle(final T plr, String input)
{
if ((initialCharacter != null) && !input.startsWith(initialCharacter + "")) { return CommandHandlingOutput.NOT_COMMAND; }
public int handle(final T plr, String input) {
if ((initialCharacter != null) && !input.startsWith(initialCharacter + "")) {
return CommandHandlingOutput.NOT_COMMAND;
}
input = initialCharacter == null ? input : input.substring(1);
final String[] parts = input.split(" ");
String[] args;
final String command = parts[0].toLowerCase();
if (parts.length == 1)
{
if (parts.length == 1) {
args = new String[0];
}
else
{
} else {
args = new String[parts.length - 1];
System.arraycopy(parts, 1, args, 0, args.length);
}
Command<T> cmd = null;
cmd = commands.get(command);
if (cmd == null) { return CommandHandlingOutput.NOT_FOUND; }
if (!cmd.getRequiredType().allows(plr)) { return CommandHandlingOutput.CALLER_OF_WRONG_TYPE; }
if (!Permissions.hasPermission(plr, cmd.getPermission())) { return CommandHandlingOutput.NOT_PERMITTED; }
if (cmd == null) {
return CommandHandlingOutput.NOT_FOUND;
}
if (!cmd.getRequiredType().allows(plr)) {
return CommandHandlingOutput.CALLER_OF_WRONG_TYPE;
}
if (!Permissions.hasPermission(plr, cmd.getPermission())) {
return CommandHandlingOutput.NOT_PERMITTED;
}
final Argument<?>[] requiredArguments = cmd.getRequiredArguments();
if ((requiredArguments != null) && (requiredArguments.length > 0))
{
if ((requiredArguments != null) && (requiredArguments.length > 0)) {
boolean success = true;
if (args.length < requiredArguments.length)
{
if (args.length < requiredArguments.length) {
success = false;
}
else
{
for (int i = 0; i < requiredArguments.length; i++)
{
if (requiredArguments[i].parse(args[i]) == null)
{
} else {
for (int i = 0; i < requiredArguments.length; i++) {
if (requiredArguments[i].parse(args[i]) == null) {
success = false;
break;
}
}
}
if (!success)
{
if (!success) {
cmd.getUsage().replaceAll("\\{label\\}", parts[0]);
C.COMMAND_SYNTAX.send(plr, cmd.getUsage());
return CommandHandlingOutput.WRONG_USAGE;
}
}
try
{
try {
final boolean a = cmd.onCommand(plr, args);
if (!a)
{
if (!a) {
final String usage = cmd.getUsage();
if ((usage != null) && !usage.isEmpty())
{
if ((usage != null) && !usage.isEmpty()) {
plr.sendMessage(usage);
}
return CommandHandlingOutput.WRONG_USAGE;
}
}
catch (final Throwable t)
{
} catch (final Throwable t) {
t.printStackTrace();
return CommandHandlingOutput.ERROR;
}
return CommandHandlingOutput.SUCCESS;
}
final public char getInitialCharacter()
{
final public char getInitialCharacter() {
return this.initialCharacter;
}
}

View File

@ -3,12 +3,10 @@ package com.plotsquared.listener;
import com.sk89q.worldedit.extent.AbstractDelegateExtent;
import com.sk89q.worldedit.extent.Extent;
public class ExtentWrapper extends AbstractDelegateExtent
{
protected ExtentWrapper(final Extent extent)
{
public class ExtentWrapper extends AbstractDelegateExtent {
protected ExtentWrapper(final Extent extent) {
super(extent);
}
}

View File

@ -6,25 +6,24 @@ import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.extent.AbstractDelegateExtent;
import com.sk89q.worldedit.extent.Extent;
public class HeightLimitExtent extends AbstractDelegateExtent
{
public class HeightLimitExtent extends AbstractDelegateExtent {
private final int max;
private final int min;
public HeightLimitExtent(final int min, final int max, final Extent child)
{
public HeightLimitExtent(final int min, final int max, final Extent child) {
super(child);
this.min = min;
this.max = max;
}
@Override
public boolean setBlock(final Vector location, final BaseBlock block) throws WorldEditException
{
public boolean setBlock(final Vector location, final BaseBlock block) throws WorldEditException {
final int y = location.getBlockY();
if ((y < min) || (y > max)) { return false; }
if ((y < min) || (y > max)) {
return false;
}
return super.setBlock(location, block);
}
}

View File

@ -15,73 +15,61 @@ import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.biome.BaseBiome;
public class NullExtent implements Extent
{
public class NullExtent implements Extent {
@Override
public BaseBiome getBiome(final Vector2D arg0)
{
public BaseBiome getBiome(final Vector2D arg0) {
return null;
}
@Override
public BaseBlock getBlock(final Vector arg0)
{
public BaseBlock getBlock(final Vector arg0) {
return null;
}
@Override
public BaseBlock getLazyBlock(final Vector arg0)
{
public BaseBlock getLazyBlock(final Vector arg0) {
return null;
}
@Override
public Operation commit()
{
public Operation commit() {
return null;
}
@Override
public boolean setBiome(final Vector2D arg0, final BaseBiome arg1)
{
public boolean setBiome(final Vector2D arg0, final BaseBiome arg1) {
return false;
}
@Override
public boolean setBlock(final Vector arg0, final BaseBlock arg1) throws WorldEditException
{
public boolean setBlock(final Vector arg0, final BaseBlock arg1) throws WorldEditException {
return false;
}
@Override
public Entity createEntity(final Location arg0, final BaseEntity arg1)
{
public Entity createEntity(final Location arg0, final BaseEntity arg1) {
return null;
}
@Override
public List<? extends Entity> getEntities()
{
public List<? extends Entity> getEntities() {
return new ArrayList<>();
}
@Override
public List<? extends Entity> getEntities(final Region arg0)
{
public List<? extends Entity> getEntities(final Region arg0) {
return new ArrayList<>();
}
@Override
public Vector getMaximumPoint()
{
public Vector getMaximumPoint() {
return new Vector(0, 0, 0);
}
@Override
public Vector getMinimumPoint()
{
public Vector getMinimumPoint() {
return new Vector(0, 0, 0);
}
}

View File

@ -50,160 +50,117 @@ import com.intellectualcrafters.plot.util.UUIDHandler;
/**
*/
public class PlotListener
{
public static boolean plotEntry(final PlotPlayer pp, final Plot plot)
*/
public class PlotListener {
public static boolean plotEntry(final PlotPlayer pp, final Plot plot) {
if (plot.isDenied(pp.getUUID()) && !Permissions.hasPermission(pp, "plots.admin.entry.denied")) {
return false;
if (plot.isDenied(pp.getUUID()) && !Permissions.hasPermission(pp, "plots.admin.entry.denied")) { return false; }
final Plot last = (Plot) pp.getMeta("lastplot");
}
final Plot last = (Plot) pp.getMeta("lastplot");
if ((last != null) && !last.id.equals(plot.id)) {
plotExit(pp, last);
}
pp.setMeta("lastplot", plot);
EventUtil.manager.callEntry(pp, plot);
pp.setMeta("lastplot", plot);
EventUtil.manager.callEntry(pp, plot);
if (plot.hasOwner()) {
final HashMap<String, Flag> flags = FlagManager.getPlotFlags(plot);
final int size = flags.size();
boolean titles = Settings.TITLES;
final String greeting;
boolean titles = Settings.TITLES;
final String greeting;
{
final Flag titleFlag = flags.get("titles");
if (size != 0) {
final Flag titleFlag = flags.get("titles");
if (titleFlag != null) {
titles = (Boolean) titleFlag.getValue();
}
final Flag greetingFlag = flags.get("greeting");
}
final Flag greetingFlag = flags.get("greeting");
if (greetingFlag != null) {
greeting = (String) greetingFlag.getValue();
pp.sendMessage(ChatColor.translateAlternateColorCodes('&', C.PREFIX_GREETING.s().replaceAll("%id%", plot.id + "") + greeting));
}
greeting = (String) greetingFlag.getValue();
pp.sendMessage(ChatColor.translateAlternateColorCodes('&', C.PREFIX_GREETING.s().replaceAll("%id%", plot.id + "") + greeting));
} else {
greeting = "";
}
if (greeting != null)
greeting = "";
}
if (greeting != null) {
}
final Flag enter = flags.get("notify-enter");
if ((enter != null) && ((Boolean) enter.getValue()))
{
if (!Permissions.hasPermission(pp, "plots.flag.notify-enter.bypass"))
{
}
final Flag enter = flags.get("notify-enter");
if ((enter != null) && ((Boolean) enter.getValue())) {
if (!Permissions.hasPermission(pp, "plots.flag.notify-enter.bypass")) {
{
final PlotPlayer owner = UUIDHandler.getPlayer(uuid);
for (final UUID uuid : PlotHandler.getOwners(plot)) {
final PlotPlayer owner = UUIDHandler.getPlayer(uuid);
if ((owner != null) && !owner.getUUID().equals(pp.getUUID())) {
MainUtil.sendMessage(pp, C.NOTIFY_ENTER.s().replace("%player", pp.getName()).replace("%plot", plot.getId().toString()));
}
}
}
}
final Flag gamemodeFlag = flags.get("gamemode");
if (gamemodeFlag != null)
{
if (pp.getGamemode() != gamemodeFlag.getValue())
{
}
final Flag gamemodeFlag = flags.get("gamemode");
if (gamemodeFlag != null) {
if (pp.getGamemode() != gamemodeFlag.getValue()) {
{
pp.setGamemode((PlotGamemode) gamemodeFlag.getValue());
}
if (!Permissions.hasPermission(pp, "plots.gamemode.bypass")) {
pp.setGamemode((PlotGamemode) gamemodeFlag.getValue());
} else {
MainUtil.sendMessage(pp, StringMan.replaceAll(C.GAMEMODE_WAS_BYPASSED.s(), "{plot}", plot.id, "{gamemode}", gamemodeFlag.getValue()));
}
}
}
final Flag flyFlag = flags.get("fly");
}
final Flag flyFlag = flags.get("fly");
if (flyFlag != null) {
pp.setFlight((boolean) flyFlag.getValue());
}
final Flag timeFlag = flags.get("time");
if (timeFlag != null)
{
}
final Flag timeFlag = flags.get("time");
if (timeFlag != null) {
try {
final long time = (long) timeFlag.getValue();
pp.setTime(time);
}
final long time = (long) timeFlag.getValue();
pp.setTime(time);
} catch (final Exception e) {
FlagManager.removePlotFlag(plot, "time");
}
}
final Flag weatherFlag = flags.get("weather");
}
final Flag weatherFlag = flags.get("weather");
if (weatherFlag != null) {
pp.setWeather((PlotWeather) weatherFlag.getValue());
pp.setWeather((PlotWeather) weatherFlag.getValue());
}
final Flag musicFlag = flags.get("music");
final Flag musicFlag = flags.get("music");
{
final Integer id = (Integer) musicFlag.getValue();
if (musicFlag != null) {
final Integer id = (Integer) musicFlag.getValue();
if (((id >= 2256) && (id <= 2267)) || (id == 0)) {
final Location loc = pp.getLocation();
final Location lastLoc = (Location) pp.getMeta("music");
final Location loc = pp.getLocation();
final Location lastLoc = (Location) pp.getMeta("music");
{
pp.playMusic(lastLoc, 0);
if (lastLoc != null) {
pp.playMusic(lastLoc, 0);
if (id == 0) {
pp.deleteMeta("music");
}
}
if (id != 0)
{
}
}
if (id != 0) {
try {
pp.setMeta("music", loc);
pp.playMusic(loc, id);
}
pp.setMeta("music", loc);
pp.playMusic(loc, id);
} catch (final Exception e) {}
}
}
}
}
}
{
final Location lastLoc = (Location) pp.getMeta("music");
} else {
final Location lastLoc = (Location) pp.getMeta("music");
if (lastLoc != null) {
pp.deleteMeta("music");
pp.playMusic(lastLoc, 0);
}
}
CommentManager.sendTitle(pp, plot);
}
}
CommentManager.sendTitle(pp, plot);
{
greeting = "";
}
} else if (titles) {
greeting = "";
} else {
return true;
}
if (titles)
{
if ((C.TITLE_ENTERED_PLOT.s().length() != 0) || (C.TITLE_ENTERED_PLOT_SUB.s().length() != 0))
{
return true;
}
if (titles) {
if ((C.TITLE_ENTERED_PLOT.s().length() != 0) || (C.TITLE_ENTERED_PLOT_SUB.s().length() != 0)) {
{
@Override
TaskManager.runTaskLaterAsync(new Runnable() {
@Override
{
final Plot lastPlot = (Plot) pp.getMeta("lastplot");
public void run() {
final Plot lastPlot = (Plot) pp.getMeta("lastplot");
if ((lastPlot != null) && plot.id.equals(lastPlot.id)) {
final Map<String, String> replacements = new HashMap<>();
@ -223,77 +180,61 @@ public class PlotListener
}
return true;
}
return true;
}
return true;
}
public static boolean plotExit(final PlotPlayer pp, final Plot plot) {
pp.deleteMeta("lastplot");
EventUtil.manager.callLeave(pp, plot);
pp.deleteMeta("lastplot");
EventUtil.manager.callLeave(pp, plot);
{
final PlotWorld pw = PS.get().getPlotWorld(pp.getLocation().getWorld());
if (pw == null) { return true; }
if (FlagManager.getPlotFlag(plot, "gamemode") != null)
{
if (pp.getGamemode() != pw.GAMEMODE)
{
if (plot.hasOwner()) {
final PlotWorld pw = PS.get().getPlotWorld(pp.getLocation().getWorld());
if (pw == null) {
return true;
}
if (FlagManager.getPlotFlag(plot, "gamemode") != null) {
if (pp.getGamemode() != pw.GAMEMODE) {
{
pp.setGamemode(pw.GAMEMODE);
}
if (!Permissions.hasPermission(pp, "plots.gamemode.bypass")) {
pp.setGamemode(pw.GAMEMODE);
} else {
MainUtil.sendMessage(pp, StringMan.replaceAll(C.GAMEMODE_WAS_BYPASSED.s(), "{plot}", plot.world, "{gamemode}", pw.GAMEMODE.name().toLowerCase()));
}
}
}
final Flag farewell = FlagManager.getPlotFlag(plot, "farewell");
}
final Flag farewell = FlagManager.getPlotFlag(plot, "farewell");
if (farewell != null) {
pp.sendMessage(ChatColor.translateAlternateColorCodes('&', C.PREFIX_FAREWELL.s().replaceAll("%id%", plot.id + "") + farewell.getValueString()));
}
final Flag leave = FlagManager.getPlotFlag(plot, "notify-leave");
if ((leave != null) && ((Boolean) leave.getValue()))
{
if (!Permissions.hasPermission(pp, "plots.flag.notify-enter.bypass"))
{
}
final Flag leave = FlagManager.getPlotFlag(plot, "notify-leave");
if ((leave != null) && ((Boolean) leave.getValue())) {
if (!Permissions.hasPermission(pp, "plots.flag.notify-enter.bypass")) {
{
final PlotPlayer owner = UUIDHandler.getPlayer(uuid);
for (final UUID uuid : PlotHandler.getOwners(plot)) {
final PlotPlayer owner = UUIDHandler.getPlayer(uuid);
if ((owner != null) && !owner.getUUID().equals(pp.getUUID())) {
MainUtil.sendMessage(pp, C.NOTIFY_LEAVE.s().replace("%player", pp.getName()).replace("%plot", plot.getId().toString()));
}
}
}
}
}
}
{
final PlotGamemode gamemode = pp.getGamemode();
if (FlagManager.getPlotFlag(plot, "fly") != null) {
final PlotGamemode gamemode = pp.getGamemode();
if ((gamemode == PlotGamemode.SURVIVAL) || (gamemode == PlotGamemode.ADVENTURE)) {
pp.setFlight(false);
}
}
}
}
if (FlagManager.getPlotFlag(plot, "time") != null) {
pp.setTime(Long.MAX_VALUE);
}
pp.setTime(Long.MAX_VALUE);
}
if (FlagManager.getPlotFlag(plot, "weather") != null) {
pp.setWeather(PlotWeather.RESET);
}
final Location lastLoc = (Location) pp.getMeta("music");
}
final Location lastLoc = (Location) pp.getMeta("music");
if (lastLoc != null) {
pp.deleteMeta("music");
pp.playMusic(lastLoc, 0);
}
}
return true;
}
return true;
}
public boolean getFlagValue(final String value) {
return Arrays.asList("true", "on", "enabled", "yes").contains(value.toLowerCase());

View File

@ -19,8 +19,7 @@ import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.biome.BaseBiome;
public class ProcessedWEExtent extends AbstractDelegateExtent
{
public class ProcessedWEExtent extends AbstractDelegateExtent {
private final HashSet<RegionWrapper> mask;
int BScount = 0;
int Ecount = 0;
@ -30,27 +29,23 @@ public class ProcessedWEExtent extends AbstractDelegateExtent
private final int max;
private int count;
private Extent parent;
public ProcessedWEExtent(final String world, final HashSet<RegionWrapper> mask, int max, final Extent child, final Extent parent)
{
public ProcessedWEExtent(final String world, final HashSet<RegionWrapper> mask, int max, final Extent child, final Extent parent) {
super(child);
this.mask = mask;
this.world = world;
if (max == -1)
{
if (max == -1) {
max = Integer.MAX_VALUE;
}
this.max = max;
count = 0;
this.parent = parent;
}
@Override
public boolean setBlock(final Vector location, final BaseBlock block) throws WorldEditException
{
public boolean setBlock(final Vector location, final BaseBlock block) throws WorldEditException {
final int id = block.getType();
switch (id)
{
switch (id) {
case 54:
case 130:
case 142:
@ -85,29 +80,23 @@ public class ProcessedWEExtent extends AbstractDelegateExtent
case 29:
case 33:
case 151:
case 178:
{
if (BSblocked) { return false; }
case 178: {
if (BSblocked) {
return false;
}
BScount++;
if (BScount > Settings.CHUNK_PROCESSOR_MAX_BLOCKSTATES)
{
if (BScount > Settings.CHUNK_PROCESSOR_MAX_BLOCKSTATES) {
BSblocked = true;
PS.debug("&cPlotSquared detected unsafe WorldEdit: " + (location.getBlockX()) + "," + (location.getBlockZ()));
}
if (WEManager.maskContains(mask, location.getBlockX(), location.getBlockY(), location.getBlockZ()))
{
if (count++ > max)
{
if (parent != null)
{
try
{
if (WEManager.maskContains(mask, location.getBlockX(), location.getBlockY(), location.getBlockZ())) {
if (count++ > max) {
if (parent != null) {
try {
final Field field = AbstractDelegateExtent.class.getDeclaredField("extent");
field.setAccessible(true);
field.set(parent, new NullExtent());
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
}
parent = null;
@ -118,33 +107,25 @@ public class ProcessedWEExtent extends AbstractDelegateExtent
}
break;
}
default:
{
default: {
final int x = location.getBlockX();
final int y = location.getBlockY();
final int z = location.getBlockZ();
if (WEManager.maskContains(mask, location.getBlockX(), location.getBlockY(), location.getBlockZ()))
{
if (count++ > max)
{
if (parent != null)
{
try
{
if (WEManager.maskContains(mask, location.getBlockX(), location.getBlockY(), location.getBlockZ())) {
if (count++ > max) {
if (parent != null) {
try {
final Field field = AbstractDelegateExtent.class.getDeclaredField("extent");
field.setAccessible(true);
field.set(parent, new NullExtent());
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
}
parent = null;
}
return false;
}
switch (id)
{
switch (id) {
case 0:
case 2:
case 4:
@ -229,26 +210,18 @@ public class ProcessedWEExtent extends AbstractDelegateExtent
case 189:
case 190:
case 191:
case 192:
{
if (Settings.EXPERIMENTAL_FAST_ASYNC_WORLDEDIT)
{
case 192: {
if (Settings.EXPERIMENTAL_FAST_ASYNC_WORLDEDIT) {
SetBlockQueue.setBlock(world, x, y, z, id);
}
else
{
} else {
super.setBlock(location, block);
}
break;
}
default:
{
if (Settings.EXPERIMENTAL_FAST_ASYNC_WORLDEDIT)
{
default: {
if (Settings.EXPERIMENTAL_FAST_ASYNC_WORLDEDIT) {
SetBlockQueue.setBlock(world, x, y, z, new PlotBlock((short) id, (byte) block.getData()));
}
else
{
} else {
super.setBlock(location, block);
}
break;
@ -259,29 +232,32 @@ public class ProcessedWEExtent extends AbstractDelegateExtent
// return super.setBlock(location, block);
}
}
}
return false;
}
@Override
public Entity createEntity(final Location location, final BaseEntity entity)
{
if (Eblocked) { return null; }
public Entity createEntity(final Location location, final BaseEntity entity) {
if (Eblocked) {
return null;
}
Ecount++;
if (Ecount > Settings.CHUNK_PROCESSOR_MAX_ENTITIES)
{
if (Ecount > Settings.CHUNK_PROCESSOR_MAX_ENTITIES) {
Eblocked = true;
PS.debug("&cPlotSquared detected unsafe WorldEdit: " + (location.getBlockX()) + "," + (location.getBlockZ()));
}
if (WEManager.maskContains(mask, location.getBlockX(), location.getBlockY(), location.getBlockZ())) { return super.createEntity(location, entity); }
if (WEManager.maskContains(mask, location.getBlockX(), location.getBlockY(), location.getBlockZ())) {
return super.createEntity(location, entity);
}
return null;
}
@Override
public boolean setBiome(final Vector2D position, final BaseBiome biome)
{
if (WEManager.maskContains(mask, position.getBlockX(), position.getBlockZ())) { return super.setBiome(position, biome); }
public boolean setBiome(final Vector2D position, final BaseBiome biome) {
if (WEManager.maskContains(mask, position.getBlockX(), position.getBlockZ())) {
return super.setBiome(position, biome);
}
return false;
}
}

View File

@ -14,34 +14,35 @@ import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.biome.BaseBiome;
public class WEExtent extends AbstractDelegateExtent
{
public class WEExtent extends AbstractDelegateExtent {
private final HashSet<RegionWrapper> mask;
public WEExtent(final HashSet<RegionWrapper> mask, final Extent extent)
{
public WEExtent(final HashSet<RegionWrapper> mask, final Extent extent) {
super(extent);
this.mask = mask;
}
@Override
public boolean setBlock(final Vector location, final BaseBlock block) throws WorldEditException
{
if (WEManager.maskContains(mask, location.getBlockX(), location.getBlockY(), location.getBlockZ())) { return super.setBlock(location, block); }
public boolean setBlock(final Vector location, final BaseBlock block) throws WorldEditException {
if (WEManager.maskContains(mask, location.getBlockX(), location.getBlockY(), location.getBlockZ())) {
return super.setBlock(location, block);
}
return false;
}
@Override
public Entity createEntity(final Location location, final BaseEntity entity)
{
if (WEManager.maskContains(mask, location.getBlockX(), location.getBlockY(), location.getBlockZ())) { return super.createEntity(location, entity); }
public Entity createEntity(final Location location, final BaseEntity entity) {
if (WEManager.maskContains(mask, location.getBlockX(), location.getBlockY(), location.getBlockZ())) {
return super.createEntity(location, entity);
}
return null;
}
@Override
public boolean setBiome(final Vector2D position, final BaseBiome biome)
{
if (WEManager.maskContains(mask, position.getBlockX(), position.getBlockZ())) { return super.setBiome(position, biome); }
public boolean setBiome(final Vector2D position, final BaseBiome biome) {
if (WEManager.maskContains(mask, position.getBlockX(), position.getBlockZ())) {
return super.setBiome(position, biome);
}
return false;
}
}

View File

@ -12,47 +12,41 @@ import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.RegionWrapper;
import com.intellectualcrafters.plot.util.MainUtil;
public class WEManager
{
public class WEManager {
// public static HashSet<String> bypass = new HashSet<>();
public static boolean maskContains(final HashSet<RegionWrapper> mask, final int x, final int y, final int z)
{
for (final RegionWrapper region : mask)
{
if (region.isIn(x, y, z)) { return true; }
public static boolean maskContains(final HashSet<RegionWrapper> mask, final int x, final int y, final int z) {
for (final RegionWrapper region : mask) {
if (region.isIn(x, y, z)) {
return true;
}
}
return false;
}
public static boolean maskContains(final HashSet<RegionWrapper> mask, final int x, final int z)
{
for (final RegionWrapper region : mask)
{
if (region.isIn(x, z)) { return true; }
public static boolean maskContains(final HashSet<RegionWrapper> mask, final int x, final int z) {
for (final RegionWrapper region : mask) {
if (region.isIn(x, z)) {
return true;
}
}
return false;
}
public static HashSet<RegionWrapper> getMask(final PlotPlayer player)
{
public static HashSet<RegionWrapper> getMask(final PlotPlayer player) {
final HashSet<RegionWrapper> regions = new HashSet<>();
final UUID uuid = player.getUUID();
final Location location = player.getLocation();
final String world = location.getWorld();
if (!PS.get().isPlotWorld(world))
{
if (!PS.get().isPlotWorld(world)) {
regions.add(new RegionWrapper(Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE));
return regions;
}
for (final Plot plot : PS.get().getPlotsInWorld(player.getLocation().getWorld()))
{
if (!plot.isBasePlot() || (Settings.DONE_RESTRICTS_BUILDING && (FlagManager.getPlotFlag(plot, "done") != null)))
{
for (final Plot plot : PS.get().getPlotsInWorld(player.getLocation().getWorld())) {
if (!plot.isBasePlot() || (Settings.DONE_RESTRICTS_BUILDING && (FlagManager.getPlotFlag(plot, "done") != null))) {
continue;
}
if (Settings.WE_ALLOW_HELPER ? plot.isAdded(uuid) : (plot.isOwner(uuid) || plot.getTrusted().contains(uuid)))
{
if (Settings.WE_ALLOW_HELPER ? plot.isAdded(uuid) : (plot.isOwner(uuid) || plot.getTrusted().contains(uuid))) {
final Location pos1 = MainUtil.getPlotBottomLoc(plot.world, plot.id).add(1, 0, 1);
final Location pos2 = MainUtil.getPlotTopLoc(plot.world, plot.id);
regions.add(new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getY(), pos2.getY(), pos1.getZ(), pos2.getZ()));
@ -60,17 +54,16 @@ public class WEManager
}
return regions;
}
public static boolean intersects(final RegionWrapper region1, final RegionWrapper region2)
{
public static boolean intersects(final RegionWrapper region1, final RegionWrapper region2) {
return (region1.minX <= region2.maxX) && (region1.maxX >= region2.minX) && (region1.minZ <= region2.maxZ) && (region1.maxZ >= region2.minZ);
}
public static boolean regionContains(final RegionWrapper selection, final HashSet<RegionWrapper> mask)
{
for (final RegionWrapper region : mask)
{
if (intersects(region, selection)) { return true; }
public static boolean regionContains(final RegionWrapper selection, final HashSet<RegionWrapper> mask) {
for (final RegionWrapper region : mask) {
if (intersects(region, selection)) {
return true;
}
}
return false;
}

View File

@ -27,118 +27,89 @@ import com.sk89q.worldedit.util.eventbus.EventHandler.Priority;
import com.sk89q.worldedit.util.eventbus.Subscribe;
import com.sk89q.worldedit.world.World;
public class WESubscriber
{
public class WESubscriber {
@Subscribe(priority = Priority.VERY_EARLY)
public void onEditSession(final EditSessionEvent event)
{
public void onEditSession(final EditSessionEvent event) {
final WorldEdit worldedit = PS.get().worldedit;
if (worldedit == null)
{
if (worldedit == null) {
WorldEdit.getInstance().getEventBus().unregister(this);
return;
}
final World worldObj = event.getWorld();
final String world = worldObj.getName();
final Actor actor = event.getActor();
if ((actor != null) && actor.isPlayer())
{
if ((actor != null) && actor.isPlayer()) {
final String name = actor.getName();
final PlotPlayer pp = PlotPlayer.wrap(name);
if ((pp != null) && pp.getAttribute("worldedit")) { return; }
if ((pp != null) && pp.getAttribute("worldedit")) {
return;
}
final HashSet<RegionWrapper> mask = WEManager.getMask(pp);
final PlotWorld plotworld = PS.get().getPlotWorld(world);
if (mask.size() == 0)
{
if (Permissions.hasPermission(pp, "plots.worldedit.bypass"))
{
if (mask.size() == 0) {
if (Permissions.hasPermission(pp, "plots.worldedit.bypass")) {
MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASS);
}
if (plotworld != null)
{
if (plotworld != null) {
event.setExtent(new NullExtent());
}
return;
}
if (Settings.CHUNK_PROCESSOR)
{
if (Settings.EXPERIMENTAL_FAST_ASYNC_WORLDEDIT)
{
try
{
if (Settings.CHUNK_PROCESSOR) {
if (Settings.EXPERIMENTAL_FAST_ASYNC_WORLDEDIT) {
try {
final LocalSession session = worldedit.getSession(name);
boolean hasMask = session.getMask() != null;
final Player objPlayer = (Player) actor;
final int item = objPlayer.getItemInHand();
if (!hasMask)
{
try
{
if (!hasMask) {
try {
final Tool tool = session.getTool(item);
if ((tool != null) && (tool instanceof BrushTool))
{
if ((tool != null) && (tool instanceof BrushTool)) {
hasMask = ((BrushTool) tool).getMask() != null;
}
}
catch (final Exception e)
{}
} catch (final Exception e) {}
}
AbstractDelegateExtent extent = (AbstractDelegateExtent) event.getExtent();
ChangeSetExtent history = null;
MultiStageReorder reorder = null;
MaskingExtent maskextent = null;
final boolean fast = session.hasFastMode();
while ((extent.getExtent() != null) && (extent.getExtent() instanceof AbstractDelegateExtent))
{
while ((extent.getExtent() != null) && (extent.getExtent() instanceof AbstractDelegateExtent)) {
final AbstractDelegateExtent tmp = (AbstractDelegateExtent) extent.getExtent();
if ((tmp.getExtent() != null) && (tmp.getExtent() instanceof AbstractDelegateExtent))
{
if (tmp instanceof ChangeSetExtent)
{
if ((tmp.getExtent() != null) && (tmp.getExtent() instanceof AbstractDelegateExtent)) {
if (tmp instanceof ChangeSetExtent) {
history = (ChangeSetExtent) tmp;
}
if (tmp instanceof MultiStageReorder)
{
if (tmp instanceof MultiStageReorder) {
reorder = (MultiStageReorder) tmp;
}
if (hasMask && (tmp instanceof MaskingExtent))
{
if (hasMask && (tmp instanceof MaskingExtent)) {
maskextent = (MaskingExtent) tmp;
}
extent = tmp;
}
else
{
} else {
break;
}
}
final int max = event.getMaxBlocks();
final Field field = AbstractDelegateExtent.class.getDeclaredField("extent");
field.setAccessible(true);
if (history == null)
{
if (history == null) {
final ExtentWrapper wrapper = new ExtentWrapper(event.getExtent());
event.setExtent(wrapper);
field.set(extent, new ProcessedWEExtent(world, mask, max, new FastModeExtent(worldObj, true), wrapper));
}
else
{
if (fast)
{
} else {
if (fast) {
event.setExtent(new ExtentWrapper(extent));
}
else
{
} else {
ExtentWrapper wrapper;
if (maskextent != null)
{
if (maskextent != null) {
wrapper = new ExtentWrapper(maskextent);
field.set(maskextent, history);
event.setExtent(wrapper);
}
else
{
} else {
wrapper = new ExtentWrapper(history);
event.setExtent(wrapper);
}
@ -147,19 +118,14 @@ public class WESubscriber
}
}
return;
}
catch (final Exception e)
{
} catch (final Exception e) {
e.printStackTrace();
}
}
if (PS.get().isPlotWorld(world))
{
if (PS.get().isPlotWorld(world)) {
event.setExtent(new ProcessedWEExtent(world, mask, event.getMaxBlocks(), event.getExtent(), event.getExtent()));
}
}
else if (plotworld != null)
{
} else if (plotworld != null) {
event.setExtent(new WEExtent(mask, event.getExtent()));
}
}

View File

@ -21,38 +21,34 @@ import com.intellectualcrafters.plot.object.schematic.PlotItem;
import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.SchematicHandler.Schematic;
public class StateWrapper
{
public class StateWrapper {
public BlockState state = null;
public CompoundTag tag = null;
public StateWrapper(final BlockState state)
{
public StateWrapper(final BlockState state) {
this.state = state;
}
public StateWrapper(final CompoundTag tag)
{
public StateWrapper(final CompoundTag tag) {
this.tag = tag;
}
public boolean restoreTag(final short x, final short y, final short z, final Schematic schematic)
{
if (tag == null) { return false; }
public boolean restoreTag(final short x, final short y, final short z, final Schematic schematic) {
if (tag == null) {
return false;
}
final List<Tag> itemsTag = tag.getListTag("Items").getValue();
final int length = itemsTag.size();
final short[] ids = new short[length];
final byte[] datas = new byte[length];
final byte[] amounts = new byte[length];
for (int i = 0; i < length; i++)
{
for (int i = 0; i < length; i++) {
final Tag itemTag = itemsTag.get(i);
final CompoundTag itemComp = (CompoundTag) itemTag;
short id = itemComp.getShort("id");
String idStr = itemComp.getString("id");
if ((idStr != null) && !MathMan.isInteger(idStr))
{
if ((idStr != null) && !MathMan.isInteger(idStr)) {
idStr = idStr.split(":")[1].toLowerCase();
id = (short) ItemType.getId(idStr);
}
@ -60,18 +56,17 @@ public class StateWrapper
datas[i] = (byte) itemComp.getShort("Damage");
amounts[i] = itemComp.getByte("Count");
}
if (length != 0)
{
if (length != 0) {
schematic.addItem(new PlotItem(x, y, z, ids, datas, amounts));
}
return true;
}
public CompoundTag getTag()
{
if (tag != null) { return tag; }
if (state instanceof InventoryHolder)
{
public CompoundTag getTag() {
if (tag != null) {
return tag;
}
if (state instanceof InventoryHolder) {
final InventoryHolder inv = (InventoryHolder) state;
final ItemStack[] contents = inv.getInventory().getContents();
final Map<String, Tag> values = new HashMap<String, Tag>();
@ -80,19 +75,15 @@ public class StateWrapper
}
return null;
}
public String getId()
{
public String getId() {
return "Chest";
}
public List<CompoundTag> serializeInventory(final ItemStack[] items)
{
public List<CompoundTag> serializeInventory(final ItemStack[] items) {
final List<CompoundTag> tags = new ArrayList<CompoundTag>();
for (int i = 0; i < items.length; ++i)
{
if (items[i] != null)
{
for (int i = 0; i < items.length; ++i) {
if (items[i] != null) {
final Map<String, Tag> tagData = serializeItem(items[i]);
tagData.put("Slot", new ByteTag("Slot", (byte) i));
tags.add(new CompoundTag(tagData));
@ -100,27 +91,23 @@ public class StateWrapper
}
return tags;
}
public Map<String, Tag> serializeItem(final org.spongepowered.api.item.inventory.ItemStack item)
{
public Map<String, Tag> serializeItem(final org.spongepowered.api.item.inventory.ItemStack item) {
final Map<String, Tag> data = new HashMap<String, Tag>();
// FIXME serialize sponge item
return data;
}
public Map<String, Tag> serializeItem(final ItemStack item)
{
public Map<String, Tag> serializeItem(final ItemStack item) {
final Map<String, Tag> data = new HashMap<String, Tag>();
data.put("id", new ShortTag("id", (short) item.getTypeId()));
data.put("Damage", new ShortTag("Damage", item.getDurability()));
data.put("Count", new ByteTag("Count", (byte) item.getAmount()));
if (!item.getEnchantments().isEmpty())
{
if (!item.getEnchantments().isEmpty()) {
final List<CompoundTag> enchantmentList = new ArrayList<CompoundTag>();
for (final Entry<Enchantment, Integer> entry : item.getEnchantments().entrySet())
{
for (final Entry<Enchantment, Integer> entry : item.getEnchantments().entrySet()) {
final Map<String, Tag> enchantment = new HashMap<String, Tag>();
enchantment.put("id", new ShortTag("id", (short) entry.getKey().getId()));
enchantment.put("lvl", new ShortTag("lvl", entry.getValue().shortValue()));

View File

@ -12,45 +12,35 @@ import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.plotsquared.sponge.util.SpongeUtil;
public class SpongeHybridUtils extends HybridUtils
{
public class SpongeHybridUtils extends HybridUtils {
@Override
public void analyzePlot(final Plot plot, final RunnableVal<PlotAnalysis> whenDone)
{
public void analyzePlot(final Plot plot, final RunnableVal<PlotAnalysis> whenDone) {
// TODO Auto-generated method stub
PS.debug("analyzePlot is not implemented");
if (whenDone != null)
{
if (whenDone != null) {
whenDone.run();
}
}
@Override
public int checkModified(final String worldname, final int x1, final int x2, final int y1, final int y2, final int z1, final int z2, final PlotBlock[] blocks)
{
public int checkModified(final String worldname, final int x1, final int x2, final int y1, final int y2, final int z1, final int z2, final PlotBlock[] blocks) {
PS.debug("checkModified is not implemented");
final World world = SpongeUtil.getWorld(worldname);
int count = 0;
for (int y = y1; y <= y2; y++)
{
for (int x = x1; x <= x2; x++)
{
for (int z = z1; z <= z2; z++)
{
for (int y = y1; y <= y2; y++) {
for (int x = x1; x <= x2; x++) {
for (int z = z1; z <= z2; z++) {
final BlockState state = world.getBlock(x, y, z);
final PlotBlock block = SpongeMain.THIS.getPlotBlock(state);
boolean same = false;
for (final PlotBlock p : blocks)
{
if (block.id == p.id)
{
for (final PlotBlock p : blocks) {
if (block.id == p.id) {
same = true;
break;
}
}
if (!same)
{
if (!same) {
count++;
}
}
@ -58,23 +48,17 @@ public class SpongeHybridUtils extends HybridUtils
}
return count;
}
@Override
public int get_ey(final String worldname, final int sx, final int ex, final int sz, final int ez, final int sy)
{
public int get_ey(final String worldname, final int sx, final int ex, final int sz, final int ez, final int sy) {
final World world = SpongeUtil.getWorld(worldname);
int ey = sy;
for (int x = sx; x <= ex; x++)
{
for (int z = sz; z <= ez; z++)
{
for (int y = sy; y < 256; y++)
{
if (y > ey)
{
for (int x = sx; x <= ex; x++) {
for (int z = sz; z <= ez; z++) {
for (int y = sy; y < 256; y++) {
if (y > ey) {
final BlockState state = world.getBlock(x, y, z);
if ((state != null) && (state.getType() != BlockTypes.AIR))
{
if ((state != null) && (state.getType() != BlockTypes.AIR)) {
ey = y;
}
}
@ -83,5 +67,5 @@ public class SpongeHybridUtils extends HybridUtils
}
return ey;
}
}

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